Skip to main content

ironwork_rt/cics/
run.rs

1//! Running a command against the task: what it asks of the executor (`CicsHost`), reading and
2//! storing its options, the EXEC interface block, raising conditions, and dispatch to the services.
3
4use super::command::{Cics, CicsCommand, Datum, Record, Resp};
5use super::{Condition, Task, file_control, maps, program, services};
6use crate::abend::{Abend, AbendCode, Ending};
7use crate::bms::Mapset;
8use crate::host::{self, Host};
9use crate::lir::{ParaId, Step};
10use crate::storage::{Loc, Val};
11use crate::store::{self, ProgramFacts};
12use crate::unit::{ADDRESS_BASE, Loader, RunUnit};
13use crate::vocab::Pos;
14use std::collections::HashMap;
15use zarch::decimal::{self, Decimal};
16use zarch::ebcdic::{self, CodePage};
17
18pub(super) type R<T> = Result<T, Abend>;
19
20pub const EIBTIME: usize = 0x00;
21pub const EIBDATE: usize = 0x04;
22pub const EIBTRNID: usize = 0x08;
23pub const EIBTASKN: usize = 0x0C;
24pub const EIBTRMID: usize = 0x10;
25pub const EIBCPOSN: usize = 0x16;
26pub const EIBCALEN: usize = 0x18;
27pub const EIBAID: usize = 0x1A;
28pub const EIBFN: usize = 0x1B;
29pub const EIBRSRCE: usize = 0x33;
30pub const EIBRESP: usize = 0x4C;
31pub const EIBRESP2: usize = 0x50;
32
33/// What a command asks of the executor running it beyond `Host`: the run unit, the program level's
34/// handlers, operands that are not data items, names only the executor can resolve, and running a
35/// program for LINK and XCTL.
36pub trait CicsHost<'w, P: Copy, O, S>: Host<P> {
37    type Program: Clone;
38    type Loader: Loader<Self::Program>;
39    fn unit(&mut self) -> &mut RunUnit<'w, Self::Program, Self::Loader>;
40    fn handlers(&mut self) -> &mut Handlers;
41    /// An operand's bytes as CALL BY CONTENT passes them.
42    fn content(&mut self, operand: &O, pos: Pos) -> R<Vec<u8>>;
43    /// An operand's value as a subscript takes it.
44    fn integer_of(&mut self, operand: &O, pos: Pos) -> R<i64>;
45    fn text(&self, text: &S) -> String;
46    /// The run unit's first program, from which RETURN TRANSID and COMMAREA end the task.
47    fn main(&self) -> bool;
48    fn program_id(&self) -> String;
49    /// Where DFHCOMMAREA is, when the program has one with an address.
50    fn commarea(&self) -> Option<usize>;
51    /// A mapset from the copy libraries; None when no library holds it.
52    fn mapset(&mut self, name: &str) -> Option<Result<Mapset, String>>;
53    /// The data item a name alone refers to, when it names one.
54    fn item_named(&mut self, name: &str, pos: Pos) -> R<Option<Loc>>;
55    /// The data item a name alone refers to, or the abend a reference to it gives.
56    fn locate_named(&mut self, name: &str, pos: Pos) -> R<Loc>;
57    /// Runs program `index` from its start with DFHEIBLK and `commarea` as its USING items; for
58    /// XCTL, in this program's place.
59    fn run_program(&mut self, program: Self::Program, index: usize, commarea: Option<usize>, xctl: bool) -> R<Ending>;
60}
61
62/// HANDLE CONDITION, IGNORE CONDITION and HANDLE ABEND, which belong to the program level.
63#[derive(Clone, Debug, Default)]
64pub struct Handlers {
65    pub conditions: HashMap<Condition, Handler>,
66    pub stack: Vec<HashMap<Condition, Handler>>,
67    pub abend: Option<ParaId>,
68}
69
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum Handler {
72    Label(ParaId),
73    Ignore,
74}
75
76/// Where control goes after a command.
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum Flow {
79    Next,
80    /// A handled condition or HANDLE ABEND.
81    GoTo(ParaId),
82    /// RETURN, XCTL, or a LINKed program's STOP RUN.
83    End(Ending),
84}
85
86impl From<Flow> for Step {
87    fn from(flow: Flow) -> Self {
88        match flow {
89            Flow::Next => Step::Next,
90            Flow::GoTo(p) => Step::GoTo(p),
91            Flow::End(e) => Step::End(e),
92        }
93    }
94}
95
96/// A command's name as written, which messages give, its RESP, RESP2 and NOHANDLE, and where it is.
97pub struct At<'c, P, O, S> {
98    pub name: &'c str,
99    pub resp: &'c Resp<P, O, S>,
100    pub pos: Pos,
101}
102
103/// EXEC CICS is refused outside a CICS task.
104pub fn in_task<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>, name: &str, pos: Pos) -> R<()> {
105    match unit.cics {
106        Some(_) => Ok(()),
107        None => Err(Abend::ironwork(format!("EXEC CICS {name} was reached outside a CICS task: run the program with `ironwork cics`"), pos)),
108    }
109}
110
111/// Every command starts with EIBRESP and EIBRESP2 zero.
112pub fn begin_command<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>) {
113    eib_fullword(unit, EIBRESP, 0);
114    eib_fullword(unit, EIBRESP2, 0);
115}
116
117/// Runs a command.
118pub fn run<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, command: &CicsCommand<P, O, S>, pos: Pos) -> R<Flow> {
119    let name = x.text(&command.name);
120    in_task(x.unit(), &name, pos)?;
121    begin_command(x.unit());
122    let at = At { name: &name, resp: &command.resp, pos };
123    match &command.command {
124        Cics::File { verb, file, options } => file_control::run(x, &at, *verb, file.as_ref(), options),
125        Cics::Return { transid, commarea, length } => program::cics_return(x, &at, transid.as_ref(), commarea.as_ref(), length.as_ref()),
126        Cics::Link(t) => program::link(x, &at, t, false),
127        Cics::Xctl(t) => program::link(x, &at, t, true),
128        Cics::Abend { abcode, cancel } => program::abend(x, &at, abcode.as_ref(), *cancel),
129        Cics::HandleCondition(labels) => program::handle_condition(x, &at, labels),
130        Cics::IgnoreCondition(conditions) => program::ignore_condition(x, &at, conditions),
131        Cics::PushHandle => program::push_handle(x, &at),
132        Cics::PopHandle => program::pop_handle(x, &at),
133        Cics::HandleAbend { program, label, reset } => program::handle_abend(x, &at, *program, *label, *reset),
134        Cics::HandleAid | Cics::Freemain | Cics::Enq | Cics::Deq | Cics::Delay => ok(x, &at),
135        Cics::SendMap { map, mapset, from, maponly, dataonly, cursor, control } => {
136            maps::send_map(x, &at, maps::MapNames { map: map.as_ref(), mapset: mapset.as_ref() }, from.as_ref(), (*maponly, *dataonly), cursor.as_ref(), *control)
137        }
138        Cics::ReceiveMap { map, mapset, into, set } => maps::receive_map(x, &at, maps::MapNames { map: map.as_ref(), mapset: mapset.as_ref() }, into.as_ref(), set.as_ref()),
139        Cics::SendControl { cursor, control } => maps::send_control(x, &at, cursor.as_ref(), *control),
140        Cics::Receive(record) => maps::receive_raw(x, &at, record),
141        Cics::Asktime { abstime } => services::asktime(x, &at, abstime.as_ref()),
142        Cics::Formattime { abstime, datesep, timesep, outputs } => services::formattime(x, &at, abstime.as_ref(), datesep.as_ref(), timesep.as_ref(), outputs),
143        Cics::Assign(assign) => services::assign(x, &at, assign),
144        Cics::Getmain { flength, length, initimg, set } => services::getmain(x, &at, flength.as_ref(), length.as_ref(), initimg.as_ref(), set.as_ref()),
145        Cics::Syncpoint { rollback } => services::syncpoint(x, &at, *rollback),
146        Cics::Address { eib, commarea, cwa, twa } => services::address(x, &at, eib.as_ref(), commarea.as_ref(), cwa.as_ref(), twa.as_ref()),
147        Cics::SendText { from, length } => services::send_text(x, &at, from.as_ref(), length.as_ref()),
148        Cics::WriteOperator { text, textlength } => services::write_operator(x, &at, text.as_ref(), textlength.as_ref()),
149        Cics::WriteqTs { queue, from, length, rewrite, item, numitems } => {
150            services::writeq_ts(x, &at, queue.as_ref(), (from.as_ref(), length.as_ref()), *rewrite, item.as_ref(), numitems.as_ref())
151        }
152        Cics::ReadqTs { queue, next, item, numitems, record } => services::readq_ts(x, &at, queue.as_ref(), *next, item.as_ref(), numitems.as_ref(), record),
153        Cics::DeleteqTs { queue } => services::deleteq_ts(x, &at, queue.as_ref()),
154        Cics::WriteqTd { queue, from, length } => services::writeq_td(x, &at, queue.as_ref(), from.as_ref(), length.as_ref()),
155        Cics::ReadqTd { queue, record } => services::readq_td(x, &at, queue.as_ref(), record),
156        Cics::DeleteqTd { queue } => services::deleteq_td(x, &at, queue.as_ref()),
157        Cics::Unsupported => Err(Abend::ironwork(unsupported(&name), pos)),
158    }
159}
160
161/// The abend message for a command ironwork does not carry out.
162pub fn unsupported(name: &str) -> String {
163    format!("EXEC CICS {name} is not supported yet")
164}
165
166/// The task; `run` has already refused to run a command outside one.
167pub(super) fn task<'a, 'w: 'a, P: Copy + 'a, O: 'a, S: 'a>(x: &'a mut impl CicsHost<'w, P, O, S>) -> &'a mut Task {
168    x.unit().cics.as_mut().expect("EXEC CICS runs only in a task")
169}
170
171pub(super) fn page<'w, P: Copy, O, S>(x: &impl CicsHost<'w, P, O, S>) -> &'static CodePage {
172    x.facts().page()
173}
174
175/// Text in the program's code page, a character it cannot encode as a space.
176pub(super) fn encoded(page: &CodePage, text: &str) -> Vec<u8> {
177    text.chars().map(|c| page.encode_char(c).unwrap_or(ebcdic::SPACE)).collect()
178}
179
180/// An option's bytes: a data item's storage, or another operand's as CALL BY CONTENT passes it.
181pub fn bytes<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<Vec<u8>>> {
182    Ok(match d {
183        Some(Datum::Place(p)) => {
184            let loc = x.locate(*p, false)?;
185            Some(store::bytes(x.mem(), loc).to_vec())
186        }
187        Some(Datum::Value(o)) => Some(x.content(o, pos)?),
188        _ => None,
189    })
190}
191
192/// An option's bytes, cut to a length option when that is shorter.
193pub(super) fn bytes_cut<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, data: Option<&Datum<P, O, S>>, length: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<Vec<u8>>> {
194    let Some(mut bytes) = bytes(x, data, pos)? else { return Ok(None) };
195    if let Some(n) = int(x, length, pos)? {
196        bytes.truncate(n.max(0) as usize);
197    }
198    Ok(Some(bytes))
199}
200
201/// FROM's bytes cut to LENGTH (or TEXT and TEXTLENGTH for WRITE OPERATOR); `from` names it.
202pub(super) fn sent<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, data: Option<&Datum<P, O, S>>, length: Option<&Datum<P, O, S>>, from: &str) -> R<Vec<u8>> {
203    bytes_cut(x, data, length, at.pos)?.ok_or_else(|| Abend::ironwork(format!("EXEC CICS {} needs {from}", at.name), at.pos))
204}
205
206pub(super) fn int<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<i64>> {
207    match d {
208        Some(Datum::Place(p)) => x.integer(*p, pos).map(Some),
209        Some(Datum::Value(o)) => x.integer_of(o, pos).map(Some),
210        _ => Ok(None),
211    }
212}
213
214/// A resource name (PROGRAM, TRANSID, QUEUE, FILE, ABCODE) with trailing spaces removed; text as
215/// written loses its quotes.
216pub(super) fn text<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, pos: Pos) -> R<Option<String>> {
217    if let Some(Datum::Text(t)) = d {
218        return Ok(Some(x.text(t).trim().trim_matches(|c| c == '\'' || c == '"').to_owned()));
219    }
220    let page = page(x);
221    Ok(bytes(x, d, pos)?.map(|b| page.decode(&b).trim_end().to_owned()))
222}
223
224/// MOVEs bytes into the data item an option names, as INTO and the like receive them; `name` is
225/// the option's.
226pub(super) fn store_bytes<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, d: Option<&Datum<P, O, S>>, name: &str, bytes: &[u8]) -> R<()> {
227    match d {
228        Some(Datum::Place(p)) => {
229            let loc = x.locate(*p, false)?;
230            x.assign(loc, Val::Bytes(bytes.to_vec()), None, at.pos)
231        }
232        Some(Datum::Value(_)) => Err(Abend::ironwork(format!("EXEC CICS {}: {name} must name a data item", at.name), at.pos)),
233        _ => Ok(()),
234    }
235}
236
237pub(super) fn store_int<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, value: i64, pos: Pos) -> R<()> {
238    match d {
239        Some(Datum::Place(p)) => host::set_integer(x, *p, value, pos),
240        _ => Ok(()),
241    }
242}
243
244/// Stores an address, or NULL for None, into the POINTER an option names.
245pub(super) fn store_pointer<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, d: Option<&Datum<P, O, S>>, offset: Option<usize>, pos: Pos) -> R<()> {
246    if let Some(Datum::Place(p)) = d {
247        let loc = x.locate(*p, false)?;
248        let address = offset.map_or(0, |o| ADDRESS_BASE + o as u32);
249        x.assign(loc, Val::Address(address), None, pos)?;
250    }
251    Ok(())
252}
253
254pub(super) fn eib_bytes<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, bytes: &[u8]) {
255    let at = unit.eib + offset;
256    unit.mem[at..at + bytes.len()].copy_from_slice(bytes);
257}
258
259pub(super) fn eib_halfword<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i16) {
260    eib_bytes(unit, offset, &value.to_be_bytes());
261}
262
263pub(super) fn eib_fullword<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i32) {
264    eib_bytes(unit, offset, &value.to_be_bytes());
265}
266
267/// A 4-byte packed EIB field: seven digits and a sign.
268pub(super) fn eib_packed<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, offset: usize, value: i64) {
269    let mut field = [0u8; 4];
270    let _ = decimal::encode(&mut field, Decimal { negative: value < 0, magnitude: value.unsigned_abs() as u128 });
271    eib_bytes(unit, offset, &field);
272}
273
274/// An EIB text field, in EBCDIC, padded with spaces or cut to `len`.
275pub(super) fn eib_text<H, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, page: &CodePage, offset: usize, len: usize, text: &str) {
276    let mut bytes = encoded(page, text);
277    bytes.resize(len, ebcdic::SPACE);
278    eib_bytes(unit, offset, &bytes);
279}
280
281pub(super) fn eib_calen<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>) -> i16 {
282    let at = unit.eib + EIBCALEN;
283    i16::from_be_bytes([unit.mem[at], unit.mem[at + 1]])
284}
285
286/// Fills the EXEC interface block for the task's first program: time, date, transaction, task
287/// number, terminal, COMMAREA length and the AID that started it.
288pub fn begin_task<H: Clone, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, page: &CodePage, length: usize) {
289    let (seconds, hundredths) = unit.now();
290    let abstime = super::abstime(seconds, hundredths);
291    let (transid, termid, number) = unit.cics.as_ref().map(|t| (t.transid.clone(), t.termid.clone(), t.number)).unwrap_or_default();
292    eib_packed(unit, EIBTIME, super::eib_time(abstime));
293    eib_packed(unit, EIBDATE, super::eib_date(abstime));
294    eib_text(unit, page, EIBTRNID, 4, &transid);
295    eib_packed(unit, EIBTASKN, i64::from(number));
296    eib_text(unit, page, EIBTRMID, 4, &termid);
297    eib_halfword(unit, EIBCALEN, length as i16);
298    if let Some(aid) = unit.cics.as_ref().and_then(|t| t.initial_aid) {
299        eib_bytes(unit, EIBAID, &[aid]);
300    }
301}
302
303/// Gives a record to INTO or SET and its length to LENGTH. A record longer than LENGTH (or the
304/// INTO item) arrives cut short, with LENGERR.
305pub(super) fn deliver<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, record: &Record<P, O, S>, data: &[u8]) -> R<Flow> {
306    let limit = match int(x, record.length.as_ref(), at.pos)? {
307        Some(n) => n.max(0) as usize,
308        None => match &record.into {
309            Some(Datum::Place(p)) => x.locate(*p, false)?.len,
310            _ => data.len(),
311        },
312    };
313    if record.set.is_some() {
314        let area = x.unit().push_temporary(data);
315        store_pointer(x, record.set.as_ref(), Some(area), at.pos)?;
316    } else {
317        store_bytes(x, at, record.into.as_ref(), "INTO", &data[..data.len().min(limit)])?;
318    }
319    store_int(x, record.length.as_ref(), data.len() as i64, at.pos)?;
320    if data.len() > limit && record.set.is_none() {
321        return raise(x, at, Condition::LENGERR, 0);
322    }
323    ok(x, at)
324}
325
326/// A command that succeeded: RESP and RESP2, when asked for, are zero.
327pub fn ok<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>) -> R<Flow> {
328    store_int(x, at.resp.resp.as_ref(), 0, at.pos)?;
329    store_int(x, at.resp.resp2.as_ref(), 0, at.pos)?;
330    Ok(Flow::Next)
331}
332
333/// Raises a condition. RESP or NOHANDLE take it; otherwise HANDLE CONDITION (the condition's own
334/// entry, else ERROR) or IGNORE CONDITION decides; otherwise HANDLE ABEND, if active, or the task
335/// abends with the condition's AEIx code.
336pub fn raise<'w, P: Copy, O, S>(x: &mut impl CicsHost<'w, P, O, S>, at: &At<P, O, S>, condition: Condition, resp2: i32) -> R<Flow> {
337    let resp = condition.resp();
338    eib_fullword(x.unit(), EIBRESP, resp);
339    eib_fullword(x.unit(), EIBRESP2, resp2);
340    if at.resp.resp.is_some() {
341        store_int(x, at.resp.resp.as_ref(), i64::from(resp), at.pos)?;
342        store_int(x, at.resp.resp2.as_ref(), i64::from(resp2), at.pos)?;
343        return Ok(Flow::Next);
344    }
345    if at.resp.nohandle {
346        return Ok(Flow::Next);
347    }
348    let handlers = x.handlers();
349    match handlers.conditions.get(&condition).or_else(|| handlers.conditions.get(&Condition::ERROR)).copied() {
350        Some(Handler::Ignore) => Ok(Flow::Next),
351        Some(Handler::Label(p)) => Ok(Flow::GoTo(p)),
352        None => match handlers.abend.take() {
353            Some(p) => Ok(Flow::GoTo(p)),
354            None => Err(Abend {
355                code: AbendCode::Cics(condition.default_abend().into()),
356                message: format!("EXEC CICS {}: {} was raised with no RESP, HANDLE CONDITION or IGNORE CONDITION", at.name, condition.name()),
357                pos: at.pos,
358                file: None,
359            }),
360        },
361    }
362}