1use super::{ClassCode, Instance, JAVA_LANG_OBJECT, LoadedClass, MAX_MEMORY, Objects, Part, Referent, Running};
8use crate::abend::{Abend, AbendCode, Ending};
9use crate::display::utf16_text;
10use crate::host::Values;
11use crate::jni;
12use crate::lir::{CallArg, InvokePlan, MethodName, Receiver, Step};
13use crate::storage::{Kind, Loc, Val};
14use crate::store::{self, ProgramFacts};
15use crate::unit::{ADDRESS_BASE, Loaded, Loader, RETURN_CODE, RunUnit};
16use crate::vocab::{Figurative, Pos};
17use numeric::assumptions::{EXPIRED_REFERENCE_ABENDS, LOCAL_FRAMES};
18use numeric::precision::{Fixed, Places};
19use std::cmp::Ordering;
20use std::rc::Rc;
21
22type R<T> = Result<T, Abend>;
23
24pub trait OoHost<'w, P: Copy, O, S>: Values<P, O> {
27 type Program: Clone;
28 type Loader: Loader<Self::Program, Class = Rc<ClassCode<Self::Program>>>;
29 fn unit(&mut self) -> &mut RunUnit<'w, Self::Program, Self::Loader>;
30 fn running(&self) -> Option<Running>;
31 fn program_id(&self) -> String;
32 fn symbol(&mut self, symbol: &S, pos: Pos) -> R<String>;
34 fn place_name(&self, place: P) -> String;
36 fn operand_name(&self, operand: &O) -> Option<String>;
38 fn invoke_argument(&mut self, operand: &O, java: &str, pos: Pos) -> R<Vec<u8>>;
40 fn initialize_data(&mut self, data: Self::Program, index: usize) -> R<()>;
42 fn run_method(&mut self, call: MethodCall<Self::Program>, pos: Pos) -> R<Returned>;
44}
45
46pub struct Returned {
48 pub ending: R<Ending>,
49 pub value: Option<(String, Val)>,
50}
51
52pub struct MethodCall<H> {
56 pub code: H,
57 pub storage: usize,
58 pub records: Vec<(usize, usize)>,
59 pub arguments: Vec<Option<usize>>,
60 pub running: Running,
61}
62
63enum Target {
65 Class(usize),
66 Object(u32),
67 Super { this: u32, start: usize, factory: bool },
68}
69
70enum Found {
72 Cobol { class: usize, method: usize },
73 ObjectEquals,
75 Java(String),
76 Missing,
77}
78
79enum Argument {
82 Bytes(Vec<u8>),
83 Object(Option<u32>),
84}
85
86const JNI_TAG: u32 = 0x7F00_0000;
88
89const OBJECT_METHODS: &[(&str, &[&str], Option<&str>)] = &[
91 ("hashCode", &[], Some("I")),
92 ("toString", &[], Some("Ljava/lang/String;")),
93 ("getClass", &[], Some("Ljava/lang/Class;")),
94 ("notify", &[], None),
95 ("notifyAll", &[], None),
96 ("wait", &[], None),
97 ("wait", &["J"], None),
98 ("wait", &["J", "I"], None),
99 ("clone", &[], Some("Ljava/lang/Object;")),
100 ("finalize", &[], None),
101];
102
103fn java(what: String, class: &str, pos: Pos) -> Abend {
104 Abend {
105 code: AbendCode::Java,
106 message: format!("{what} was reached: {class} is a Java class, and ironwork for COBOL checks Java classes but has no JVM to run them"),
107 pos,
108 file: None,
109 }
110}
111
112fn is_reference(java: &str) -> bool {
114 java.starts_with('L') || java.starts_with('[')
115}
116
117fn int(n: i128) -> Val {
118 Val::Num(Fixed::new(n, Places::new(9, 0)))
119}
120
121pub fn self_reference<H: Clone, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, running: Option<Running>, pos: Pos) -> R<Loc> {
123 let Some(m) = running else { return Err(Abend::ironwork("SELF outside a method", pos)) };
124 if unit.mem[m.cell..m.cell + 4] == [0; 4] {
125 let made = unit.oo.event(format!("SELF of {}", unit.oo.told(m.invoked)));
126 let reference = unit.oo.local_in(m.frame, m.this, made).map_err(|e| Abend::ironwork(e, pos))?;
127 unit.mem[m.cell..m.cell + 4].copy_from_slice(&reference.to_be_bytes());
128 }
129 Ok(Loc { offset: m.cell, len: 4, kind: Kind::ObjectReference, item: usize::MAX })
130}
131
132fn site<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, pos: Pos) -> String {
134 let id = x.program_id();
135 match x.running() {
136 Some(m) => format!("line {} of {}.{}", pos.line, x.unit().oo.classes[m.class].external, id),
137 None => format!("line {} of {}", pos.line, id),
138 }
139}
140
141fn referent<C>(objects: &Objects<C>, value: u32, what: &str, holder: &str, pos: Pos) -> R<Option<u32>> {
144 match objects.referent(value) {
145 Referent::Null => Ok(None),
146 Referent::Object(o) => Ok(Some(o)),
147 Referent::Expired(told) => Err(Abend::ironwork(format!("{what}: {holder} holds {told}, and IBM leaves using it unpredictable (see {EXPIRED_REFERENCE_ABENDS})"), pos)),
148 Referent::Unknown => Err(Abend::ironwork(format!("{what}: {holder} holds X'{value:08X}', which is not an object reference"), pos)),
149 }
150}
151
152fn local_reference<C>(objects: &mut Objects<C>, object: u32, made: String, pos: Pos) -> R<u32> {
154 let made = objects.event(made);
155 objects.local(object, made).map_err(|m| Abend::ironwork(m, pos))
156}
157
158fn self_object<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>, m: Running, what: &str, pos: Pos) -> R<u32> {
160 let value = u32::from_be_bytes(unit.mem[m.cell..m.cell + 4].try_into().unwrap_or_default());
161 Ok(referent(&unit.oo, value, what, "SELF", pos)?.unwrap_or(m.this))
162}
163
164pub fn compare_references<C>(objects: &Objects<C>, names: impl FnOnce() -> (String, String), x: (&Val, Option<Loc>), y: (&Val, Option<Loc>), pos: Pos) -> R<Option<Ordering>> {
168 let reference = |l: Option<Loc>| l.is_some_and(|l| l.kind == Kind::ObjectReference);
169 let (Val::Address(p), Val::Address(q)) = (x.0, y.0) else { return Ok(None) };
170 if !reference(x.1) && !reference(y.1) {
171 return Ok(None);
172 }
173 let (a, b) = names();
174 let what = format!("{a} = {b}");
175 let same = referent(objects, *p, &what, &a, pos)? == referent(objects, *q, &what, &b, pos)?;
176 Ok(Some(if same { Ordering::Equal } else { Ordering::Less }))
177}
178
179fn room<H, L: Loader<H>>(unit: &RunUnit<'_, H, L>, size: usize, pos: Pos) -> R<()> {
180 if unit.mem.len() + size > MAX_MEMORY {
181 return Err(Abend::ironwork(format!("objects and classes take the run unit past ironwork's {MAX_MEMORY} bytes"), pos));
182 }
183 Ok(())
184}
185
186fn keep<H: Clone, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, compiled: Option<H>, bytes: &[u8], pos: Pos) -> R<usize> {
189 room(unit, bytes.len(), pos)?;
190 let base = unit.push_temporary(bytes);
191 let files = compiled.as_ref().map_or(Vec::new(), |c| (0..L::shape(c).0).map(|_| None).collect());
192 let locked = vec![false; files.len()];
193 unit.programs.push(Loaded { compiled, name: String::new(), base, files, locked, initialized: false, active: false, entry: None, altered: Vec::new(), source: None });
194 Ok(unit.programs.len() - 1)
195}
196
197pub fn jni_environment<H: Clone, L: Loader<H>>(unit: &mut RunUnit<'_, H, L>, pos: Pos) -> R<usize> {
199 if let Some(cell) = unit.oo.jni {
200 return Ok(cell);
201 }
202 let slots = jni::RESERVED + jni::FUNCTIONS.len();
203 let loaded = keep(unit, None, &vec![0; 8 + 4 * slots], pos)?;
204 let base = unit.programs[loaded].base;
205 let address = |offset: usize| ADDRESS_BASE + offset as u32;
206 let mut bytes = [address(base + 4).to_be_bytes(), address(base + 8).to_be_bytes()].concat();
207 for slot in 0..slots {
208 let value = if slot < jni::RESERVED { 0 } else { JNI_TAG + slot as u32 };
209 bytes.extend(value.to_be_bytes());
210 }
211 unit.mem[base..base + bytes.len()].copy_from_slice(&bytes);
212 unit.oo.jni = Some(base);
213 Ok(base)
214}
215
216fn part_storage<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, part: &Part<X::Program>, pos: Pos) -> R<usize> {
218 let data = part.data.clone();
219 let size = X::Loader::shape(&data).1;
220 let loaded = keep(x.unit(), Some(data.clone()), &vec![0; size], pos)?;
221 x.initialize_data(data, loaded)?;
222 x.unit().programs[loaded].active = false;
223 Ok(loaded)
224}
225
226fn load_class<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, external: &str, pos: Pos) -> R<usize> {
229 if let Some(c) = x.unit().oo.find(external) {
230 return Ok(c);
231 }
232 let (code, sources) = match x.unit().library.class(external).map_err(|m| Abend::ironwork(m, pos))? {
233 None => (None, Vec::new()),
234 Some(found) => (Some(found.code), found.sources),
235 };
236 let oo = &mut x.unit().oo;
237 let index = oo.classes.len();
238 let methods = code.as_ref().map_or(0, |c| c.methods.len());
239 oo.classes.push(LoadedClass { external: external.to_owned(), code: code.clone(), parent: None, factory_object: 0, factory_data: None, methods: vec![None; methods], sources });
240 let factory_object = oo.add_object(Instance { class: index, factory: true, parts: Vec::new() }).map_err(|m| Abend::ironwork(m, pos))?;
241 oo.classes[index].factory_object = factory_object;
242 let Some(code) = code else { return Ok(index) };
243 let parent = load_class(x, &code.parent, pos)?;
244 let oo = &mut x.unit().oo;
245 let mut at = Some(parent);
246 for _ in 0..=oo.classes.len() {
247 match at {
248 Some(c) if c == index => return Err(Abend::ironwork(format!("class {external} inherits from itself"), pos)),
249 Some(c) => at = oo.classes[c].parent,
250 None => break,
251 }
252 }
253 oo.classes[index].parent = Some(parent);
254 if let Some(part) = &code.factory {
255 let loaded = part_storage(x, part, pos)?;
256 x.unit().oo.classes[index].factory_data = Some(loaded);
257 }
258 Ok(index)
259}
260
261fn chain<C>(objects: &Objects<C>, class: usize) -> Vec<usize> {
263 let mut out = vec![class];
264 while let Some(p) = objects.classes[*out.last().unwrap()].parent {
265 if out.contains(&p) {
266 break;
267 }
268 out.push(p);
269 }
270 out
271}
272
273fn object<C>(objects: &Objects<C>, id: u32, what: &str, pos: Pos) -> R<(usize, bool)> {
274 objects.object(id).map(|o| (o.class, o.factory)).ok_or_else(|| Abend::ironwork(format!("{what}: no object {id}"), pos))
275}
276
277fn target<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, receiver: &Receiver<P, S>, what: &str, pos: Pos) -> R<Target> {
278 match receiver {
279 Receiver::SelfRef | Receiver::Super => {
280 let name = if matches!(receiver, Receiver::SelfRef) { "SELF" } else { "SUPER" };
281 let Some(m) = x.running() else { return Err(Abend::ironwork(format!("INVOKE {name} outside a method"), pos)) };
282 let unit = x.unit();
283 let this = self_object(unit, m, what, pos)?;
284 if matches!(receiver, Receiver::SelfRef) {
285 return Ok(Target::Object(this));
286 }
287 let start = unit.oo.classes[m.class].parent.ok_or_else(|| Abend::ironwork("INVOKE SUPER: the class has no parent", pos))?;
288 Ok(Target::Super { this, start, factory: m.factory })
289 }
290 Receiver::Class { external, .. } => {
291 let external = x.symbol(external, pos)?;
292 Ok(Target::Class(load_class(x, &external, pos)?))
293 }
294 Receiver::Object(place) => {
295 let loc = x.locate(*place, false)?;
296 let name = x.place_name(*place);
297 let value = match <[u8; 4]>::try_from(store::bytes(x.mem(), loc)) {
298 Ok(bytes) if loc.kind == Kind::ObjectReference => u32::from_be_bytes(bytes),
299 _ => return Err(Abend::ironwork(format!("INVOKE {name}: not an object reference"), pos)),
300 };
301 match referent(&x.unit().oo, value, what, &name, pos)? {
302 Some(object) => Ok(Target::Object(object)),
303 None => Err(Abend::ironwork(format!("{what}: the object reference {name} is NULL"), pos)),
304 }
305 }
306 }
307}
308
309fn target_name<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, receiver: &Receiver<P, S>, pos: Pos) -> R<String> {
311 Ok(match receiver {
312 Receiver::SelfRef => "SELF".into(),
313 Receiver::Super => "SUPER".into(),
314 Receiver::Class { name, .. } => x.symbol(name, pos)?,
315 Receiver::Object(place) => x.place_name(*place),
316 })
317}
318
319fn method_name<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, method: &MethodName<P, S>, pos: Pos) -> R<String> {
320 Ok(match method {
321 MethodName::New => "NEW".into(),
322 MethodName::Named(n) => x.symbol(n, pos)?,
323 MethodName::Dynamic(place) => {
324 let loc = x.locate(*place, false)?;
325 let page = x.facts().page();
326 let bytes = store::bytes(x.mem(), loc);
327 let text = if loc.kind == Kind::National { utf16_text(bytes) } else { page.decode(bytes) };
328 let name = text.trim_end_matches(' ').to_owned();
329 if name.is_empty() {
330 return Err(Abend::ironwork(format!("INVOKE: {} holds no method name", x.place_name(*place)), pos));
331 }
332 name
333 }
334 })
335}
336
337fn find<H>(objects: &Objects<Rc<ClassCode<H>>>, start: usize, factory: bool, name: &str, params: &[String], returns: Option<&str>) -> Found {
338 for class in chain(objects, start) {
339 let c = &objects.classes[class];
340 match &c.code {
341 Some(code) => {
342 if let Some(method) = code.methods.iter().position(|m| m.factory == factory && m.name == name && m.params == params && m.returns.as_deref() == returns) {
343 return Found::Cobol { class, method };
344 }
345 }
346 None if c.external == JAVA_LANG_OBJECT => {
347 if factory {
348 return Found::Missing;
349 }
350 if name == "equals" && params == ["Ljava/lang/Object;"] && returns == Some("Z") {
351 return Found::ObjectEquals;
352 }
353 let java = OBJECT_METHODS.iter().any(|(n, p, r)| *n == name && *p == params && *r == returns);
354 return if java { Found::Java(c.external.clone()) } else { Found::Missing };
355 }
356 None => return Found::Java(c.external.clone()),
357 }
358 }
359 Found::Missing
360}
361
362fn no_method<P, O, S>(plan: &InvokePlan<P, O, S>, what: String, pos: Pos) -> R<Step> {
363 if plan.on_exception {
364 return Ok(Step::Arm(1));
365 }
366 Err(Abend {
367 code: AbendCode::user(4038),
368 message: format!("{what}: no method matches it, and the INVOKE has no ON EXCEPTION (a severity-3 Language Environment condition)"),
369 pos,
370 file: None,
371 })
372}
373
374fn succeeded<P, O, S>(plan: &InvokePlan<P, O, S>) -> Step {
375 if plan.on_exception || plan.not_on_exception { Step::Arm(0) } else { Step::Next }
376}
377
378pub fn invoke<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, plan: &InvokePlan<P, O, S>, pos: Pos) -> R<Step> {
381 let name = method_name(x, &plan.method, pos)?;
382 let written = target_name(x, &plan.receiver, pos)?;
383 let what = format!("INVOKE {written} \"{name}\"");
384 let receiver = target(x, &plan.receiver, &what, pos)?;
385 let mut params = Vec::new();
386 let mut arguments = Vec::new();
387 for (n, (op, java)) in plan.args.iter().enumerate() {
388 let java = x.symbol(java, pos)?;
389 let bytes = x.invoke_argument(op, &java, pos)?;
390 arguments.push(if is_reference(&java) {
391 let holder = x.operand_name(op).unwrap_or_else(|| format!("argument {}", n + 1));
392 Argument::Object(referent(&x.unit().oo, u32::from_be_bytes(bytes.as_slice().try_into().unwrap_or_default()), &what, &holder, pos)?)
393 } else {
394 Argument::Bytes(bytes)
395 });
396 params.push(java);
397 }
398 if matches!(plan.method, MethodName::New) {
399 let Target::Class(class) = receiver else { return Err(Abend::ironwork("INVOKE ... NEW takes a class-name", pos)) };
400 return new_object(x, plan, &written, class, ¶ms, pos);
401 }
402 let returns = match &plan.returning {
403 None => None,
404 Some((_, java)) => Some(x.symbol(java, pos)?),
405 };
406 let (this, start, factory) = match receiver {
407 Target::Class(c) => (x.unit().oo.classes[c].factory_object, c, true),
408 Target::Object(o) => {
409 let (class, factory) = object(&x.unit().oo, o, &what, pos)?;
410 (o, class, factory)
411 }
412 Target::Super { this, start, factory } => (this, start, factory),
413 };
414 match find(&x.unit().oo, start, factory, &name, ¶ms, returns.as_deref()) {
415 Found::Missing => no_method(plan, what, pos),
416 Found::Java(class) => Err(java(what, &class, pos)),
417 Found::ObjectEquals => {
418 let same = matches!(arguments.first(), Some(Argument::Object(Some(other))) if *other == this);
419 if let Some((place, _)) = &plan.returning {
420 let dest = x.locate(*place, false)?;
421 x.assign(dest, Val::Bytes(vec![u8::from(same)]), None, pos)?;
422 }
423 Ok(succeeded(plan))
424 }
425 Found::Cobol { class, method } => {
426 x.unit().enter(pos)?;
427 let step = run_method(x, plan, class, method, this, arguments, &what, pos);
428 x.unit().depth -= 1;
429 step
430 }
431 }
432}
433
434fn new_object<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, plan: &InvokePlan<P, O, S>, written: &str, class: usize, params: &[String], pos: Pos) -> R<Step> {
437 let what = format!("INVOKE {written} NEW");
438 let oo = &x.unit().oo;
439 let chain = chain(oo, class);
440 if let Some(&j) = chain.iter().find(|&&c| oo.classes[c].code.is_none() && oo.classes[c].external != JAVA_LANG_OBJECT) {
441 return Err(java(what, &oo.classes[j].external.clone(), pos));
442 }
443 if !params.is_empty() {
444 return no_method(plan, format!("{what} USING {} arguments", params.len()), pos);
445 }
446 let mut parts = Vec::new();
447 for &c in chain.iter().rev() {
448 if let Some(code) = x.unit().oo.classes[c].code.clone()
449 && let Some(part) = &code.object
450 {
451 parts.push((c, part_storage(x, part, pos)?));
452 }
453 }
454 let object = x.unit().oo.add_object(Instance { class, factory: false, parts }).map_err(|m| Abend::ironwork(m, pos))?;
455 let here = site(x, pos);
456 let made = format!("made by INVOKE {} NEW at {here}", x.unit().oo.classes[class].external);
457 let reference = local_reference(&mut x.unit().oo, object, made, pos)?;
458 if let Some((place, _)) = &plan.returning {
459 let dest = x.locate(*place, false)?;
460 x.assign(dest, Val::Address(reference), None, pos)?;
461 }
462 Ok(succeeded(plan))
463}
464
465#[allow(clippy::too_many_arguments)]
471fn run_method<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, plan: &InvokePlan<P, O, S>, class: usize, k: usize, this: u32, arguments: Vec<Argument>, what: &str, pos: Pos) -> R<Step> {
472 let code = x.unit().oo.classes[class].code.clone().ok_or_else(|| Abend::ironwork("not a COBOL class", pos))?;
473 let method = &code.methods[k];
474 let this = if method.factory { x.unit().oo.classes[class].factory_object } else { this };
475 let storage = match x.unit().oo.classes[class].methods[k] {
476 Some(s) => s,
477 None => {
478 let size = X::Loader::shape(&method.code).1;
479 let s = keep(x.unit(), Some(method.code.clone()), &vec![0; size], pos)?;
480 x.unit().oo.classes[class].methods[k] = Some(s);
481 s
482 }
483 };
484 let (part, data) = if method.factory {
485 (code.factory.as_ref(), x.unit().oo.classes[class].factory_data)
486 } else {
487 let data = x.unit().oo.object(this).and_then(|o| o.parts.iter().find(|(c, _)| *c == class)).map(|(_, l)| *l);
488 (code.object.as_ref(), data)
489 };
490 let here = site(x, pos);
491 let unit = x.unit();
492 let base = data.map(|d| unit.programs[d].base);
493 let return_code = [unit.mem[RETURN_CODE], unit.mem[RETURN_CODE + 1]];
494 let mark = unit.mem.len();
495 let invoked_text = format!("method \"{}\" of {}, invoked at {here}", method.name, unit.oo.classes[class].external);
496 let invoked = unit.oo.event(invoked_text.clone());
497 let (depth, frame) = unit.oo.push_frame(false);
498 let mut addresses = Vec::new();
499 for (n, argument) in arguments.into_iter().enumerate() {
500 let bytes = match argument {
501 Argument::Bytes(b) => b,
502 Argument::Object(None) => vec![0; 4],
503 Argument::Object(Some(object)) => {
504 let made = unit.oo.event(format!("received as argument {} by {invoked_text}", n + 1));
505 unit.oo.local_in(frame, object, made).map_err(|m| Abend::ironwork(m, pos))?.to_be_bytes().to_vec()
506 }
507 };
508 addresses.push(Some(unit.push_temporary(&bytes)));
509 }
510 let cell = unit.push_temporary(&[0; 4]);
511 let records = match (part, base) {
512 (Some(part), Some(base)) => part.records.iter().enumerate().map(|(n, offset)| (method.own_records + n, base + *offset as usize)).collect(),
513 _ => Vec::new(),
514 };
515 let running = Running { class, factory: method.factory, this, cell, frame, invoked };
516 let outcome = x.run_method(MethodCall { code: method.code.clone(), storage, records, arguments: addresses, running }, pos)?;
517 let unit = x.unit();
518 unit.programs[storage].active = false;
519 unit.release_temporaries(mark);
520 let Returned { ending, value: returned } = outcome;
521 let ending = ending.map_err(|mut abend| {
522 if abend.file.is_none() {
523 abend.file = Some(unit.oo.classes[class].sources.get(abend.pos.file as usize).cloned().unwrap_or_default());
524 }
525 abend
526 });
527 if ending? == Ending::StopRun {
528 return Ok(Step::End(Ending::StopRun));
529 }
530 let mut returned_object = None;
531 if let Some((item, Val::Address(value))) = &returned
532 && method.returns.as_deref().is_some_and(is_reference)
533 {
534 let holder = format!("{item}, the RETURNING item of method \"{}\",", method.name);
535 returned_object = Some(referent(&unit.oo, *value, what, &holder, pos)?);
536 }
537 let mut returned = returned.map(|(_, value)| value);
538 let expired = unit.oo.event(format!("expired when {invoked_text}, returned"));
539 unit.oo.pop_frames(depth, expired);
540 if let Some(object) = returned_object {
541 let value = match object {
542 None => 0,
543 Some(o) => local_reference(&mut unit.oo, o, format!("returned by {invoked_text}"), pos)?,
544 };
545 returned = Some(Val::Address(value));
546 }
547 unit.mem[RETURN_CODE..RETURN_CODE + 2].copy_from_slice(&return_code);
548 if let (Some((place, _)), Some(val)) = (&plan.returning, returned) {
549 let dest = x.locate(*place, false)?;
550 x.assign(dest, val, None, pos)?;
551 }
552 Ok(succeeded(plan))
553}
554
555pub fn call_through_pointer<'w, P: Copy, O, S, X: OoHost<'w, P, O, S>>(x: &mut X, pointer: P, args: &[CallArg<P, O>], returning: Option<P>, pos: Pos) -> R<()> {
559 let name = x.place_name(pointer);
560 let loc = x.locate(pointer, false)?;
561 let Ok(value) = <[u8; 4]>::try_from(store::bytes(x.mem(), loc)).map(u32::from_be_bytes) else {
562 return Err(Abend::ironwork(format!("CALL {name}: a reference-modified function-pointer"), pos));
563 };
564 let service = value.checked_sub(JNI_TAG).and_then(|slot| jni::function(slot as usize));
565 let Some(service) = service else {
566 return Err(Abend::ironwork(format!("CALL {name}: X'{value:08X}' is not a JNI service, the only entry a function-pointer can hold here"), pos));
567 };
568 let mut values = Vec::new();
569 for arg in args {
570 values.push(match arg {
571 CallArg::Value(op) => x.value(op, pos)?,
572 CallArg::Omitted => Val::Address(0),
573 CallArg::Reference(_) | CallArg::Content(_) => return Err(Abend::ironwork(format!("CALL {service}: a JNI service takes its arguments by value"), pos)),
574 });
575 }
576 let what = format!("CALL {service}");
577 let holder = |x: &X, n: usize| match args.get(n) {
578 Some(CallArg::Value(op)) => x.operand_name(op),
579 _ => None,
580 }
581 .unwrap_or_else(|| format!("argument {n}"));
582 let value = |n: usize| match values.get(n) {
583 Some(Val::Address(a)) => Ok(*a),
584 Some(Val::Fig(Figurative::Null)) => Ok(0),
585 _ => Err(Abend::ironwork(format!("CALL {service}: argument {n} is not an object reference"), pos)),
586 };
587 let referent_of = |x: &mut X, n: usize, value: u32| {
588 let holder = holder(x, n);
589 referent(&x.unit().oo, value, &what, &holder, pos)
590 };
591 let here = site(x, pos);
592 let result = match service {
593 "NewGlobalRef" | "NewLocalRef" => {
594 let object = referent_of(x, 1, value(1)?)?;
595 let reference = match object {
596 None => 0,
597 Some(o) => {
598 let oo = &mut x.unit().oo;
599 let made = oo.event(format!("made by {service} at {here}"));
600 let made = if service == "NewGlobalRef" { oo.global(o, made) } else { oo.local(o, made) };
601 made.map_err(|m| Abend::ironwork(m, pos))?
602 }
603 };
604 Some(Val::Address(reference))
605 }
606 "DeleteGlobalRef" | "DeleteLocalRef" => {
607 let reference = value(1)?;
608 if referent_of(x, 1, reference)?.is_some() {
609 let global = service == "DeleteGlobalRef";
610 if x.unit().oo.is_global(reference) != global {
611 let kind = if global { "local" } else { "global" };
612 return Err(Abend::ironwork(format!("{what}: {} holds a {kind} reference, which {service} does not delete (see {LOCAL_FRAMES})", holder(x, 1)), pos));
613 }
614 let oo = &mut x.unit().oo;
615 let event = oo.event(format!("was deleted by {service} at {here}"));
616 oo.free(reference, event);
617 }
618 None
619 }
620 "IsSameObject" => {
621 let same = referent_of(x, 1, value(1)?)? == referent_of(x, 2, value(2)?)?;
622 Some(Val::Bytes(vec![u8::from(same)]))
623 }
624 "GetObjectRefType" => {
625 let reference = value(1)?;
626 let kind = match referent_of(x, 1, reference)? {
627 None => 0,
628 Some(_) if x.unit().oo.is_global(reference) => 2,
629 Some(_) => 1,
630 };
631 Some(int(kind))
632 }
633 "PushLocalFrame" => {
634 x.unit().oo.push_frame(true);
635 Some(int(0))
636 }
637 "PopLocalFrame" => {
638 let Some(depth) = x.unit().oo.pushed_frame() else {
639 return Err(Abend::ironwork(format!("{what}: no frame PushLocalFrame pushed is open here (see {LOCAL_FRAMES})"), pos));
640 };
641 let object = referent_of(x, 1, value(1)?)?;
642 let oo = &mut x.unit().oo;
643 let expired = oo.event(format!("expired when PopLocalFrame at {here} freed its frame"));
644 oo.pop_frames(depth, expired);
645 let reference = match object {
646 None => 0,
647 Some(o) => local_reference(oo, o, format!("returned by PopLocalFrame at {here}"), pos)?,
648 };
649 Some(Val::Address(reference))
650 }
651 "EnsureLocalCapacity" => Some(int(0)),
652 "ExceptionOccurred" => Some(Val::Address(0)),
653 "ExceptionCheck" => Some(Val::Bytes(vec![0])),
654 "ExceptionClear" => None,
655 _ => {
656 return Err(Abend {
657 code: AbendCode::Java,
658 message: format!("CALL {name} was reached: {service} is a JNI service, and ironwork for COBOL has no JVM to run it"),
659 pos,
660 file: None,
661 });
662 }
663 };
664 if let (Some(target), Some(val)) = (returning, result) {
665 let dest = x.locate(target, false)?;
666 x.assign(dest, val, None, pos)?;
667 }
668 Ok(())
669}