12. Libraries: registry, EXTERNAL, REXXUTIL, rxmath, rxregexp, rxsock, hostemu


12. Libraries: registry, EXTERNAL, REXXUTIL, rxmath, rxregexp, rxsock, hostemu

This chapter covers the native libraries of the RVM: the closed library registry and how ::REQUIRES ... LIBRARY, ::ROUTINE ... EXTERNAL, ::METHOD/::ATTRIBUTE ... EXTERNAL and the reflective loaders resolve against it; RXFUNCADD, RXFUNCDROP and RXFUNCQUERY; REXXUTIL (always loaded); the four optional libraries rxmath, rxregexp, rxsock and hostemu (with its HOSTEMU ADDRESS environment); and the REXXUTIL macrospace and its sharing with child processes (RVM_MACROSPACE). It assumes the call machinery of chapter 5, the object core of chapter 8 and the scheduler of chapter 7.

12.1 The library registry

A library in the RVM is only one the RVM implements itself, in both hosts. The registry is closed: any other name is error 98.903 ("Unable to load library"), which is what native ooRexx says when it cannot load a shared library.

Name Routines Methods ADDRESS env. ooRexx host JS host
rexxutil REXXUTIL (always loaded, 12.3) — — ../RVM.RexxUtil.cls ../js/rexxutil.mjs
REXX none LIBRARY REXX f: the RVM's own natives — compiler (IsRexxLibrary) ../js/libraries.mjs (registry), ../js/objects.mjs (the natives, libraryNative)
rxmath 18 — — ../RVM.RxMath.cls (calls the host's rxmath) ../js/rxmath.mjs (computes)
rxregexp none 5 (RegExp_*) — ../RVM.RxRegExp.cls (calls the host's rxregexp) ../js/rxregexp.mjs (port)
rxsock 28 — — ../RVM.RxSock.cls (host's sockets) ../js/rxsock.mjs + sockets-node.mjs
hostemu none — HOSTEMU ../RVM.HostEmu.cls ../js/hostemu.mjs

The registry routines live in ../RVM.BIFs.cls (they are needed by RXFUNCQUERY, and putting them there avoids a ::REQUIRES cycle) and are mirrored in ../js/libraries.mjs:

ooRexx host JS host Purpose
RVMLibrary(name) rvmLibrary The routine table (Directory/Map NAME -> entry) of a library, or .Nil/null.
OoRexxLibrary(name) ooRexxLibrary What the RVM knows of a library of native ooRexx that it does not have: "NONE" (no methods: rxunixsys), "METHODS" (orxncurses rxregexp orexxole oodialog rxwinsys), or "".
LibraryMethods(name) libraryMethods The method table of a library (only rxregexp).
LibraryEnvironments(name) libraryEnvironments ADDRESS environments the library registers when loaded (only hostemu → HOSTEMU).
ExternalSpec externalSpec Parses an EXTERNAL specification.
ExternalRoutine / ExternalMethod externalRoutine / externalMethod Resolve one routine / method.
RxMathRoutines, RxSockRoutines, RxRegExpMethods, RexxUtilRoutines RXMATH_ROUTINES, RXSOCK_ROUTINES, RXREGEXP_METHODS, ROUTINES The tables (built once; in the ooRexx host cached in class attributes of RVM.RexxUtil).

The library name is matched verbatim (case-sensitive): native ooRexx on Unix loads lib<name>.so with the exact name, so ::REQUIRES rxmath LIBRARY (an unquoted symbol, i.e. RXMATH) is 98.903 natively and in the RVM. On Windows a library that is a file (a DLL) is found in any case, as LoadLibrary finds rxmath.dll for RXMATH: LibraryName / libraryName lowers the name of those (rxmath, rxsock, rxregexp, hostemu and the ooRexx libraries of OoRexxLibrary) when the file system is caseless, and every function of the table above starts with it. REXX and rexxutil are inside ooRexx and are matched as they are on every system.

In the ooRexx host, rxmath, rxsock and rxregexp exist only if the host interpreter can load its own copy: RxMathRoutines and RxSockRoutines call .context~package~loadLibrary(...) on the host, and RVMLibrary("rxregexp") checks RxRegExpHost(); otherwise RVMLibrary answers .Nil and the library is 98.903.

Entries

A routine entry has the REXXUTIL shape: name (upper case), minimum and maximum argument count, the dispatch key, the library, and optionally a signature (below). ooRexx host: an Array (name, min, max, key, library, sig); JS: { name, min, max, key, library, sig }. A method entry (rxregexp) is (NAME, key, library, args) where args is a list of o (optional) / r (required), all strings.

NativeRoutine (../RVM.Machine.cls; nativeRoutine in ../js/libraries.mjs) dispatches a routine entry by its library: RxMathNative, RxSockNative, otherwise RexxUtilNative.

Argument conversion

Native ooRexx converts the arguments of a typed native routine in order (processArguments): a missing required argument is 88.901 when reached, each present one is converted to its type, and too many arguments is 88.922 only at the end. An entry with a signature reproduces this (NativeArgs in ../RVM.RexxUtil.cls, nativeArgs in ../js/rexxutil.mjs). Each word is r or o plus a type:

Type Native C type Conversion / error
ANY RexxObjectPtr as is
STR CSTRING, RexxStringObject string value (88.909)
POSW positive_wholenumber_t 1..999999999999999999 (88.905)
NNEGW nonnegative_wholenumber_t 0.. (88.904)
INT32 int32_t −2147483648..2147483647 (88.907)
ARRAY RexxArrayObject an Array or what makes one (98.913)
STEM RexxStemObject a Stem, or the name of a caller's stem variable with or without the period (40.919)
FLOAT float/double a number, nan, +infinity, -infinity (88.921)
* ARGLIST the rest of the arguments as they are; never 88.922

The whole number types convert as native's Numerics::objectToSignedInteger (nativeWhole in ../RVM.Number.cls and ../js/number.mjs): at 20 digits (SIZE_DIGITS) with no rounding ('3.000000000000000001' is not whole; a digit past the 20th is truncated with its carry), within 18 nines.

Entries without a signature (SysSleep, SysVersion, SysLinVer, the rxmath routines) are checked by CheckRoutineArgs / checkRoutineArgs first: 88.922 for too many, then 88.901 for a missing required one; rxmath then validates its own arguments (12.5). In JS, whole-number results of the conversion are BigInt.

12.2 Loading a library and resolving EXTERNAL

Loading

A loaded library belongs to the whole process (as in native ooRexx's PackageManager): RVM.World~loadLibrary(name, table) (../RVM.Objects.cls; World.loadLibrary in ../js/objects.mjs) records it once, in load order, and registers its ADDRESS environments (addressEnvironment(name), any case). World~libraryRoutine(name) then finds its routines from any program (any case, first library in load order wins). A library is loaded by:

  • ::REQUIRES "lib" LIBRARY — at package start, in ::REQUIRES order, with the directive's clause current (StartPackage in the machine): RVMLibrary or 98.903.
  • An EXTERNAL 'LIBRARY lib ...' that resolves (below).
  • Package~loadLibrary(name) — returns 1 (loaded) or 0 (not a library of the RVM); on the REXX package itself, 98.984.
  • Routine~loadExternalRoutine and Method~loadExternalMethod.
  • RXFUNCADD(name, lib) when lib is a library of the RVM (12.4).

EXTERNAL specifications

ExternalSpec(spec, name, registered) splits the specification into words: LIBRARY lib [entry] (first word in any case) and, for a ::ROUTINE only, REGISTERED lib [entry]; anything else (wrong keyword, fewer than 2 or more than 3 words) is 99.917. The entry defaults to the directive's name. For an attribute the entry is prefixed GET/SET as native does (GETname, SETname), unless an explicit entry is given.

The compiler emits the specification and the directive's clause into the R-code (routine entries - EXTERNAL clause "spec"; method kind LIBRARY, key L; 04-rcode.md). EXTERNAL 'LIBRARY REXX f' with f one of the interpreter's own natives (Alarm/Ticker timers, Stream, File, RexxQueue: the list in IsRexxLibrary, ../RVM.Compiler.cls) is compiled as an RVM native method X.f instead and never reaches the registry. The parser already raises 99.917 for malformed specifications at translation; the RVM's check is a guard.

When errors are raised

Native ooRexx resolves EXTERNAL routines and methods when it translates the package. The RVM resolves them when the package starts, before its ::REQUIRES (CheckExternals in ../RVM.Machine.cls, checkExternals in ../js/machine.mjs), each error reported at its directive's clause, so the observable result is the same: no clause of the program has run.

Directive Condition Error When
::ROUTINE ... EXTERNAL bad specification 99.917 start
library not in the registry 98.903 start
entry not in the library 90.999 start
REGISTERED ... (any) 90.999 start
::METHOD/::ATTRIBUTE ... EXTERNAL bad specification 99.917 start
library of the RVM, method missing 90.998 start
ooRexx library without methods (OoRexxLibrary = NONE, e.g. rxunixsys), or rxsock 90.998 start
ooRexx library with methods the RVM lacks (METHODS: orxncurses, oodialog, ...) 98.903 when the method runs
not a library of ooRexx at all 98.903 start

A resolved routine becomes the library's: RVM.Routine~lib (JS lib) holds the entry, the routine has no code address, and calls to it go straight to the native (12.3). Its traceback line uses its own name (Compiled routine "FOO"). A method of key L is resolved again each time it runs (CallNative in ../RVM.Objects.cls, callNative in ../js/objects.mjs): ExternalMethod(..., strict), then LibraryMethod / libraryMethod checks the arguments as the native does (each present argument converted to a string, 88.909; a missing required one 88.901; too many 88.922 at the end) and runs it with the receiver's object variables in the method's scope.

say "start"                       -- never runs in any of the three
::routine foo external "LIBRARY rxmath nofunc"   -- 90.999 at this line

Reflective loaders

  • Routine~loadExternalRoutine(name, spec): the Routine of the library entry (99.917 for a bad spec, .nil if the library or the entry is not there): one Routine object per library entry (RVM.World~libraryRoutineObject / World.libraryRoutineObject, keyed by the entry), as ooRexx's package manager keeps them: loadExternalRoutine (by any name), a ::ROUTINE ... EXTERNAL (made when its package is installed, CheckExternals) and the StackFrame of the native routine running give the same object. Its source is empty, its name is the entry as first written, and its package is REXX for REXXUTIL's routines (ooRexx has them inside), otherwise that of the ::ROUTINE that made it first, or .nil (made by loadExternalRoutine or by a call by name) (09).
  • Method~loadExternalMethod(name, spec): a Method of key L for an rxregexp method, .nil if absent. Its package is its code's: that of the first ::METHOD ... EXTERNAL that resolved the entry, or .nil (RVM.World~libraryHome), as native's.

12.3 REXXUTIL

Always loaded, found as an external

Native REXXUTIL is an internal package of native routines (PackageManager::loadInternalPackage); its routines are not built-in functions but external routines found by RexxActivation::externalCall / SystemInterpreter::invokeExternalFunction after the program's routines and before programs in files. The RVM reproduces this order in CallRoutine (../RVM.Machine.cls; callRoutine in ../js/machine.mjs) for a name that is neither an internal label nor a BIF:

  1. a ::ROUTINE of the program or a public routine of a required package (FindRoutine);
  2. the activation's security manager (CALL);
  3. a macrospace macro with order B (before) (12.9);
  4. a REXXUTIL routine (RexxUtilRoutine, any case: call "sysSleep" works);
  5. a routine of a loaded library (World~libraryRoutine);
  6. a program in a file (LoadExternal; 05-machine.md);
  7. a macro with order A (after);
  8. else 43.1.

Calling a native routine

CallRexxUtil (label in the machine's CallRoutine; JS equivalent in callRoutine) pushes a native traceback line *-* Compiled routine "NAME". (context~nativeLines), checks the arguments (RoutineArgs: CheckRoutineArgs, then NativeArgs), and calls NativeRoutine. REXXUTIL's routines belong to the REXX package (ooRexx's image has them), so an error in their arguments — ooRexx's processArguments, raised with the native's frame on top — is reported there, with no line: PROGRAM is REXX, PACKAGE the REXX package, no POSITION, and the report says Error 88 running REXX:. RoutineArgs sets the context's nativeArgs flag for them, and RexxUtilNative clears it once NativeArgs has converted the arguments; an error with the flag on is located so (Failed). An error the routine's own code raises is the caller's line (ooRexx raises it again in the caller: reraiseException), and so is any error of rxmath's and rxsock's routines, which have no package. A routine that must wait (only SysSleep, and blocking rxsock calls) returns an RVM.Wait: the activity suspends and the result is the activity's waitResult when it resumes (RexxUtilResumed; JS suspend + rexxUtilDone). A function call with no result is 44.1. Routine~call of an EXTERNAL routine runs the native at once (EnterRoutineCall).

The routines (Unix)

Both hosts implement the same 39 of native's 55 Unix REXXUTIL routines. The ooRexx host often delegates to the host interpreter's own REXXUTIL (HostRexxUtil: .Routine~loadExternalRoutine(name, "LIBRARY rexxutil" name)~callWith(args)), which runs in the same process, file system, current directory and environment and therefore gives native results by construction; the JS host ports the C code.

Routine ooRexx host JS host
SysSleep own: timer wait on an RVM.EventSem nobody posts (other activities run; 88.902, 88.907 0..2147483; μs resolution; 0 = no wait; follows RVM_CLOCK) same
SysFileExists, SysIsFile, SysIsFileDirectory, SysIsFileLink, SysFileDelete, SysRmDir, SysMkDir host's, on the qualified name files.FileOps
On Windows, SysMkDir(dir) takes no mode (its REXXUTIL's: one argument, 88.922 before anything else), and there is no SysGetMessage nor SysGetMessageX same
SysVersion; SysLinVer, SysWinVer host's (SysLinVer, SysWinVer only if the host has them) host.sysVersion() (Node: os.type() + " " + os.release(), on Windows Windows <release>; browser: BROWSER); SysLinVer on non-Windows, SysWinVer on Windows
SysStemSort own port of StemClass::sort (RVM.StemSorter) port
SysStemDelete, SysStemInsert, SysStemCopy own line-by-line ports ports
SysUtilVersion 5.3.0 5.3.0
SysLoadFuncs, SysDropFuncs 0 0
SysCls host's (it runs clear; result: system()'s wait status), after flushing the standard output and error host.clearScreen() (Node: /bin/sh -c clear, the exit code × 256; browser: 0, nothing to clear)
SysQueryProcess host's (the same process), after checking the selector (any other than PID PPID PGID PPRIO PTIME PMEM PSWAPS PRCVDSIG, on Windows PID TID PPRIO TPRIO PTIME TTIME, "" included, is 40.1, as native) host.queryProcess() (Node: process.pid/ppid, PGID from /proc, os.getPriority, process.resourceUsage() with SysRexxUtil.cpp's formats; browser: 40.1, there is no process)
SysSetPriority([class], priority) host's (Unix: setpriority of the process, nice −priority, clamped; the class is ignored): 0 or the errno host.setPriority() (Node: os.setPriority, clamped to −20..19; the errno of a failure; browser: 38, ENOSYS)
Windows: SysSetPriority(class, level) host's; both required (rANY rANY: 88.901 from REXXUTIL) port: the class 0–3 or IDLE NORMAL HIGH REALTIME, the level −15..15 or Windows's names, else 40.1; host.setPriorityClass() (os.setPriority 19, 0, −14, −20 are those classes); a level SetThreadPriority would not take is 87
SysGetKey([echo]) host's, after flushing the standard output and error: one key from the terminal with no line editing (NOECHO: no echo; another option, 40.920); "" when the standard input is not a terminal host.getKey() (Node: stty -icanon [-echo] min 1 time 0 on /dev/tty, one byte read from the standard input, the settings back; browser: "")
SysDumpVariables own own
SysFormatMessage own (FormatMessage) own
SysGetErrorText host's strerror (Windows: FormatMessage) glibc's table, 0–133; on Windows, host.systemMessage(): FormatMessage from the system, in its language (PowerShell runs it, once for each number; the bytes of the system's ANSI code page, which may be UTF-8), "" when there is none
SysFileTree, SysFileSearch host's, into a host Stem copied back (ResultStem, HostResults) ports (TreeFinder, fnmatch, line reader)
SysSearchPath, SysFileCopy, SysFileMove, SysTempFileName, SysGetFileDateTime, SysSetFileDateTime host's ports
Windows: the file routines' results host's GetLastError() as Windows gives it (winErrorOf in hostfile-node.mjs: Node's error code, and whether the directory is there, for 2 or 3): 183, 145, 267, 5, 32...; SysFileCopy overwrites, SysFileMove never does (183); SysGetFileDateTime takes C (creation); SysSetFileDateTime takes a year from 1800 and only a real date and time (else −1)
SysGetMessage, SysGetMessageX host's MESSAGES (from ../js/rvm-data.mjs, generated by gendata.rex) for set 1 of rexx.cat; other catalogs: glibc gencat files read directly (names with a slash only; no NLSPATH)
SysAddRexxMacro, SysDropRexxMacro, SysQueryRexxMacro, SysReorderRexxMacro, SysClearRexxMacroSpace, SysSaveRexxMacroSpace, SysLoadRexxMacroSpace own (12.9) own

Not implemented (both hosts): the named semaphores (SysCreateEventSem, SysOpenEventSem, SysCloseEventSem, SysPostEventSem, SysResetEventSem, SysWaitEventSem, SysCreateMutexSem, SysOpenMutexSem, SysCloseMutexSem, SysRequestMutexSem, SysReleaseMutexSem), SysFork, SysWait and SysCreatePipe. A call to one is an ordinary external call (a program file of that name, or 43.1), and RXFUNCQUERY answers 1 for it (native 0): an accepted divergence (17).

In the browser, the file routines work on the host's in-memory file system (FileOps of ../js/host-browser.mjs); a host with no FileOps raises 93.900.

Semantics worth knowing

  • Stem elements. An element is a tail with its own value: the stem's default value does not count and a dropped tail is absent (native GetStemArrayElement); deleting only drops an element that exists.
  • SysStemSort. The stem argument is a Stem, a name, or a name with a tail (s.foo sorts s.FOO.1...). Errors 40.920–40.924 (element 0: a non-negative integer of up to 9 digits). The order is native's: stable merge sort; case-sensitive compare is memcmp + length; caseless uppercases ASCII and compares signed chars (bytes 80–FF sort before 00–7F); with columns, native compares one byte past the end of the shorter string (its NUL), and so does the RVM. Values are written back as strings.
  • SysStemCopy. Its 40.924 uses the relative index, and its bad-option message says "sort type", as native.
  • Result stems (SysFileTree, SysFileSearch; native StemHandler): an Array is emptied and refilled; a stem gets 1..n and n in .0 (.0 is set even on failure, as native's destructor does); anything else 40.925.
  • SysDumpVariables. Name=N, Value='v' per caller variable in native's order; a stem prints its value, then its elements, whose lines end CR LF (simple variables, LF). Appends to a file (40.1 if it cannot be opened) or writes to the process's standard output.
  • SysFormatMessage. &1..&9; omitted or missing substitutions are ""; more than 9 substitutions is 40.1; a NUL truncates (C strings).
  • SysFileTree (JS). A port of Unix TreeFinder: pattern adjustment (* → ./*, ~), options (40.21, 40.900), attribute masks validated but without effect (as on Unix), fnmatch with FNM_NOESCAPE|FNM_PATHNAME (I adds FNM_CASEFOLD), stat following links, local-time dates, size width 10/20, permission letters, subdirectories in a second pass.
  • SysSetFileDateTime. Fields parsed as sscanf("%4d-%2d-%2d") / ("%2d:%2d:%2d"), unspecified ones kept, normalised as mktime does (2021-13-40 25:61:61 → 2022-02-10 02:02:01).

12.4 RXFUNCADD, RXFUNCDROP, RXFUNCQUERY

The RVM has no rxapi daemon and cannot load classic (registered) function libraries. The three BIFs (BIF.RXFUNCADD, BIF.RXFUNCDROP, BIF.RXFUNCQUERY in ../RVM.BIFs.cls; register("RXFUNC...") in ../js/bifs-stream.mjs) work over the libraries of the RVM plus a process-wide table of names (RVM.RexxUtil~registered; JS registered):

Call Result
RXFUNCQUERY(name) 0 if name (any case) is a REXXUTIL routine, a routine of a loaded library, or registered by RXFUNCADD; else 1. BIFs do not count.
RXFUNCADD(name, module [, proc]) 0 if the routine is already callable (REXXUTIL, loaded library). If module is a library of the RVM: it is loaded (as ::REQUIRES ... LIBRARY), 0 if it has name, else 1 (proc unused, as native for a library package). Any other module: name is registered (counted, as rxapi does) and the result is 1.
RXFUNCDROP(name) 0 if registered by RXFUNCADD (one registration removed), else 1. A library's routines are never "registered".

A call to a name that is registered but not loadable finds nothing: 43.1, as native when it cannot resolve the function.

say rxfuncadd("RxCalcSqrt", "rxmath") RxCalcSqrt(2, 8)   -- 0 1.4142136
say rxfuncadd("Foo", "libfoo") rxfuncquery("Foo")        -- 1 0

12.5 rxmath

Routines: MathLoadFuncs, MathDropFuncs, RxCalcPi, RxCalcSqrt, RxCalcExp, RxCalcLog, RxCalcLog10, RxCalcSinH, RxCalcCosH, RxCalcTanH, RxCalcPower, RxCalcSin, RxCalcCos, RxCalcTan, RxCalcCotan, RxCalcArcSin, RxCalcArcCos, RxCalcArcTan.

Arguments (as native's typed routines, in order): the double(s) — strtod semantics on the value as given, a number or nan, +infinity, -infinity (88.921; ' - 4 ' is 0); the precision — a positive whole number (as POSW, nativeWhole: 88.905), default NUMERIC DIGITS, capped at 16 by the library; the units of the trigonometric functions — first letter D, R or G, any case (88.916; "" is an error). MathLoadFuncs(x) with an argument writes its banner (three lines and a blank one) to the process's standard output, not to .OUTPUT; MathDropFuncs does nothing.

Result format (native DoubleToObjectWithPrecision): %.*g with precision + 2, then Rexx rounding to the precision. %g strips trailing fraction zeros but not integer ones: RxCalcPower(6e3,2,7) = 3.600000E+7, RxCalcSqrt(0.01) = 0.1, RxCalcPower(0.12999999999,1) = 0.130000000.

Per host. The ooRexx host (RxMathNative) validates the arguments and then calls the host's rxmath with the precision always explicit: results are exact by construction. The JS host computes with Math.*; conversions from degrees and grades emulate the x87 long double arithmetic of rxmath.cpp (angle * pi / 180., product and quotient rounded to 64 and then 53 bits, longMulDiv with BigInt), checked bit-for-bit against C on 20,000 cases (plain doubles get a third of them wrong). Function constants and quadrant folding follow rxmath.cpp (SINE 0, TANGENT 1, COTANGENT 2, COSINE 3; MAXTRIG - f).

12.6 rxregexp

Native rxregexp is a library of native methods: those of RegularExpression, which ooRexx's own rxregexp.cls declares as EXTERNAL "LIBRARY rxregexp RegExp_xxx". The RVM compiles that .cls as is (found like any ::REQUIRES file, 03-compiler.md) and supplies the methods REGEXP_INIT (o o), REGEXP_UNINIT, REGEXP_PARSE (r o), REGEXP_MATCH (r), REGEXP_POS (r). The automaton is the object variable CSELF (native's pointer); each method sets !POS (the POSITION attribute of rxregexp.cls).

  • ooRexx host (../RVM.RxRegExp.cls): RxRegExpHost() builds, once, a host class RVM.HostRegExp whose INIT PARSE MATCH POS are the host's methods (.Method~loadExternalMethod), plus POSITION. CSELF is an instance of it. The errors native raises (93.0 for a bad match type, 38.0 for a bad expression in INIT) are raised by the RVM before calling the host, so the host never raises. INIT without an expression does parse("") on the host: native leaves the automaton as uninitialised malloc memory (in practice matching everything); a cleared one behaves the same and is deterministic. No host rxregexp → the library is 98.903.
  • JS host (../js/rxregexp.mjs): a port of rxregexp.cpp, automaton.cpp and dblqueue.cpp (Automaton). C semantics are kept: the expression ends at its first 00x, characters are signed chars (set ranges go by signed value), and the matched string ends in a NUL the automaton may read.

12.7 rxsock

The 28 routines of native rxsock (SockSocket, SockBind, SockListen, SockAccept, SockConnect, SockSend, SockRecv, SockSelect, SockGetHostByName, ...; table RxSockRoutines with signatures) are implemented as rxsockfn.cpp does them: argument conversion, stems (a Stem or a name; with a prefix after its first period, "a.p." sets A.P.NAME), the variables set in the caller (ERRNO, H_ERRNO, the variable of SockRecv, SockGetSockOpt, SockIoctl FIONREAD) and SockSelect's arrays. ooRexx's socket.cls and streamsocket.cls (classes Socket, InetAddress, HostInfo, StreamSocket) are Rexx and run unchanged on top.

Blocking. The RVM runs its activities one at a time (RVM.Scheduler), so a blocking kernel call would block all of them (a server in SockAccept while its client, another activity, is to connect). Therefore the host sockets are always non-blocking, and the RVM keeps what the program asked for (FIONBIO, SO_RCVTIMEO, SO_SNDTIMEO: RVM.SockState; JS state(fd)). A call that would block on a socket the program considers blocking (SockAccept, SockRecv, SockRecvFrom, SockSend, SockSendTo, SockConnect, and SockSelect with a non-zero timeout) makes its activity wait (RVM.SockWait; JS SockWait): other activities run, and when none is ready the scheduler waits on the pending sockets and the timers (RVM.SockPoller; see 07-concurrency.md); then the call is retried. A socket timeout ends the wait as the kernel would (-1, EWOULDBLOCK; SockConnect: EINPROGRESS); SockSelect's timeout gives 0. SockSend sends everything, as a blocking send does.

Per host.

  • ooRexx host (../RVM.RxSock.cls): the socket calls are the host's own rxsock (same kernel calls, errno names, hostent). No host rxsock → the library is 98.903.
  • JS under Node: host.sockets is a NodeSockets (../js/sockets-node.mjs) that forwards each call synchronously to a worker (../js/sockets-worker.mjs): request posted on a MessageChannel, main thread blocked on a shared flag with Atomics.wait, answer taken with receiveMessageOnPort. The worker is started on first use and does not keep the process alive. Node offers only asynchronous streams (net), datagrams (dgram) and names (dns), so the worker emulates the kernel: a descriptor table (lowest free from 3), per-socket state (bound, listening, connecting, connected, received data, pending connections, pending error, options with Linux values), Linux errno numbers and names. Differences from a kernel: a bound stream socket is already listening (Node binds and listens at once); sent data is buffered without limit (a send never waits); servers always have SO_REUSEADDR.
  • JS in the browser: there is no host.sockets. ::REQUIRES "rxsock" LIBRARY succeeds (the table exists), but the first call of any rxsock routine raises 98.903.

12.8 hostemu and library ADDRESS environments

A library may register ADDRESS environments when it is loaded (LibraryEnvironments). The machine's IssueCommand (../RVM.Machine.cls; issueCommand in ../js/machine.mjs) consults them, after the security manager's COMMAND check and before the host's environments: context~registeredEnvironment(env) → World~addressEnvironment; the handler EnvironmentCommand(lib, env, command, context) (../RVM.HostEmu.cls, ../js/hostemu.mjs) returns [RC, condition] ("", ERROR, FAILURE). Such a handler does not redirect, as native's registered by name (CommandHandler::call): with any WITH, the instruction's or the environment's default (even all NORMAL), the command is 98.921 "Address environment ... does not support input/output redirection", raised after the targets are evaluated and the security manager asked. Without ::REQUIRES "hostemu" LIBRARY, ADDRESS HOSTEMU is an unknown environment (RC 30, FAILURE), as natively.

hostemu is a port of native's command handler (GrxHost, platform/unix/hostemu.cpp; on Windows, platform/windows/hostemu.cpp: see below) and of its parser (the Bison LALR tables of cmdparse.cpp and the skeleton), so what parses, what does not, and the order of the actions are native's.

Command Behaviour
EXECIO n\|* DISKW file [( [FINIS] [STEM name] [)]] write records (value up to its first 00x, plus 0ax)
EXECIO n\|* DISKR file [start] [( [FINIS] [FIFO\|LIFO\|STEM name] [SKIP] [)]] read records into a stem or the queue (options in any order)
HI HALT at the next clause boundary (as RexxSetHalt; context~halt("")), RC 0
TE, TS TRACE O / TRACE ?R for the activation running, at its next clause boundary (RVM.Context~externalTrace, applied by RunTraps after a pending HALT, as native's externalTraceOn/Off; on the first instruction of a method or routine its entry is traced); RC 0

Details, as native:

  • Files stay open by their name as given until FINIS, with one position for reading and writing; DISKW opens a new file "w+" (emptied), DISKR "r+" (must exist and be writable).
  • A record is what fgets reads into a 100000-byte buffer (≤ 99999 bytes, up to 0ax), cut at its first 00x, without the 0ax (a CR stays).
  • The queue is always SESSION, not the current queue.
  • Stem variables are set and fetched as symbolic names (RXSHV_SYSET, RXSHV_SYFET: upper case, tails substituted).
  • Counts and starts are C atoi (an overflowing count may become −1, i.e. *).
  • Return codes: unparseable command → hostemu: bad PLIST, token "syntax error" on stderr, RC 24, ERROR; a count or start that is not all digits → RC 24, ERROR, no message; a file that cannot be opened → RC 24, FAILURE; EOF before the count → RC 2; an invalid variable name or a variable to write that has no value → RC 2008, no condition.

On Windows the hostemu is Windows's, with Microsoft's C library, and the RVM does as it does (Windows() in ../RVM.HostEmu.cls, windows() in ../js/hostemu.mjs; RVM_WINDOWS_HOSTEMU=1 turns it on anywhere, to test it):

  • A file is opened "r+" (an existing one, not emptied: DISKW too), else "r" for DISKR (one that cannot be written), else "w+" (a new one: a DISKR of a file that does not exist creates it, empty, and reads nothing: RC 0, or RC 2 with a count). Only a file that cannot be made is RC 24, FAILURE.
  • Text mode: a 0d0ax of the file is read as 0ax (so a record has no CR before its end), a 1ax (Ctrl-Z) is the end of the file; a 0ax written is 0d0ax (in the value too).
  • The states of Microsoft's FILE (_IOREAD, _IOWRITE, _IOEOF): a file that has been read takes no writes until a read met its end (_fwrite_nolock and _flsbuf write nothing, and hostemu does not look: RC 0, the file as it was, the next read goes on where it was); the fflush after a DISKW leaves it neither reading nor writing; a read while it is writing (a DISKW that ended with RC 2008, with no fflush) gives nothing.
  • atoi saturates to 32 bits (a long is 32 bits there): a count or start of more than 2147483647 is 2147483647. Native then reads up to two thousand million times past the end to reach such a start (it does not look for the end: it seems to hang); the RVM stops at the end, with the same result. In the browser, EXECIO works on the in-memory files.

12.9 The macrospace

Native's macrospace belongs to rxapi and is system-wide; the RVM's belongs to the process (RVM.RexxUtil~macros; JS MACROS in ../js/rexxutil.mjs): NAME -> (order, program), names in any case.

  • Add. SysAddRexxMacro(name, file [, order]) compiles the file when added (MacroCompile, through the machine's loader); a missing or non-regular file, or one that does not compile, is 7 (RXMACRO_SOURCE_NOT_FOUND) and the context's interpretError is restored. order is B (default) or A, first letter, any case (else 40.920).
  • Search. A B macro is found before REXXUTIL, an A macro after the programs in files (12.3; MacroProgram in CallRoutine and LoadExternal). Each call gets a fresh package from the macro's program (FreshProgram), as native's getMacroCode; unlike a file program, .Package~defaultOptions does not override a macro's options.
  • Return codes (the API's): 0 done, 2 not found, 5 file error (also: saving an empty macrospace), 6 not a macrospace image, 7 no such program. SysQueryRexxMacro returns the order or "".
  • Image format (SysSaveRexxMacroSpace, SysLoadRexxMacroSpace; MacroImage, MacrosOfImage): the RVM's own text format, identical in both hosts — a line RVM-MACROSPACE 1, then per macro MACRO order name-in-hex n followed by the program's n lines of R-code (RVM.Program~rcode, read back with ProgramOfRCode). Native images are not readable (6). Loading replaces macros of the same names (native answers 0 as well).

Sharing with child processes. As with queues (13-io-and-commands.md), a command started by the RVM receives the macrospace through the environment variable RVM_MACROSPACE, naming a temporary file with the image: the parent writes it before running the command (RVM.CommandHost~run in ../RVM.Host.cls via RVM.SharedMacros~snapshot; run in ../js/host-node.mjs via SharedMacros.snapshot) and reloads it afterwards if it changed (restore, which replaces the whole macrospace). An RVM started with RVM_MACROSPACE loads it at start (SystemHost~shareQueues; NodeHost.shareQueues) and writes it back at the end if it changed. This works across the two RVMs (an ooRexx-host parent and a JS child, or the reverse), because the image format is shared.

12.10 Host differences (summary)

Topic ooRexx host JS host
rxmath host's rxmath (exact) Math.* + x87 emulation; last-bit libm differences at precision 16
rxregexp host's methods via loadExternalMethod port of the C automaton
rxsock host's rxsock Node: worker emulating the kernel; browser: 98.903 on first call
REXXUTIL files, messages, errno mostly delegated to the host's REXXUTIL ports; glibc tables; FileOps (in memory in the browser)
SysWinVer Windows hosts Node on Windows
Missing host library rxmath/rxregexp/rxsock are 98.903 always present (rxsock: see above)

Design notes

  • The registry is closed. Libraries are not the language: portability and tests are measured on the language, and every library the RVM offers must exist identically in both hosts (and the browser). REXXUTIL is required by too many programs to omit; rxmath was cheap; rxregexp and rxsock are required by ooRexx's own Rexx packages (rxregexp.cls, socket.cls) and the test framework; hostemu supplies EXECIO. Anything else is 98.903, the same error native gives for a library it cannot load.
  • EXTERNAL routines are resolved at package start, before ::REQUIRES, with each error at its directive: native resolves them at translation, and this is the earliest point the RVM has with a context to report in; no clause of the program runs first in either.
  • A method of an ooRexx library the RVM lacks fails only when it runs (17). Otherwise a package that wraps such a library (and the test framework that requires it) could not even be loaded; failing at translation would make the whole package unusable for one missing native.
  • REGISTERED is always 90.999 and RXFUNCADD of an unknown module only records the name. The RVM has no rxapi and loads no classic libraries; keeping the registration (with rxapi's counting) keeps RXFUNCQUERY and RXFUNCDROP consistent with native.
  • REXXUTIL is "always loaded" and behaves as externals, with native's search order and native's argument checking and traceback line, because that is what native does (loadInternalPackage, callNativeRoutine); it is not a set of BIFs.
  • The ooRexx host delegates to the host's libraries (rxmath, rxregexp, rxsock, many REXXUTIL routines): the results are native's by construction (same C doubles, same file system, cwd and environment). It does its own argument validation first so that errors are raised by the RVM, in the RVM's context, and the host never raises.
  • JS rxmath emulates long double for angle conversion because plain doubles gave a different last digit in a third of the cases; the remaining libm differences are accepted.
  • Sockets never block the host. Activities share one host thread; a blocking call would freeze them all. The JS worker with Atomics.wait only makes each non-blocking call synchronous; a design where the worker itself blocked would deadlock a server and its client running as two activities.
  • Library environments are a registry consulted before the host's: a library registers an environment name when loaded, instead of the machine knowing about hostemu.
  • The macrospace is per process, shared with children by file (like the queues), because there is no rxapi daemon; its image is R-code, so it is host-independent and needs no recompilation.
  • The REXXUTIL table lives in RVM.BIFs.cls (and the library registry with it) because RXFUNCQUERY needs it and RVM.RexxUtil.cls requires RVM.BIFs.cls.

Known gaps

  • rxunixsys is not a library of the RVM (its EXTERNAL methods are 90.998).
  • SysWinVer exists in the JS host only under Node on Windows.
  • On Windows, the JS host's SysQueryProcess('TID') is the process id (Node has no thread id), TPRIO is the level SysSetPriority last set (Node cannot read or set a thread's priority: the level is checked and kept, not applied), and TTIME is the process's times; SysGetErrorText runs PowerShell once for each number (Node cannot call FormatMessage).
  • JS rxmath: last-bit differences from glibc's sin/exp/log visible at precision 16.
  • JS rxsock: no sockets in the browser; the Node worker differs from a kernel (bound stream sockets already listen, unlimited send buffer, SO_REUSEADDR always).
  • JS SysFileTree: a broken symbolic link is a file of size 0, attributes ---------- and time 0 (native reuses stale or uninitialized stat data: accepted, 17).
  • The macrospace is not system-wide: a process not started by the RVM does not see it.