13. I/O, commands and queues


13. I/O, commands and queues

This chapter covers everything the RVM exchanges with the outside world: streams (the stream functions, stream commands, the Stream and File classes, the standard streams), ADDRESS environments and commands with their WITH redirections, the external data queues (RXQUEUE, RexxQueue, sharing with child processes, the rxqueue filter), and the host interface each host implements. It assumes the machine and its contexts (machine), conditions (conditions), and the lazy .local of reflection.

Layers at a glance

Layer ooRexx host JS host
Stream engine (StreamInfo port) RVM.Stream, RVM.StreamTable (../RVM.Stream.cls) Stream, StreamTable (../js/streams.mjs)
Stream BIFs BIF.CHARIN … BIF.STREAM (../RVM.BIFs.cls) ../js/bifs-stream.mjs
Stream, File, RexxQueue classes ../prelude-streams.orx + natives StreamLibrary, FileLibrary, QueueLibrary (../RVM.Objects.cls) the same prelude (../js/rvm-prelude-streams.mjs) + streamLibrary, fileLibrary, queueLibrary (../js/objects.mjs)
Files as bytes RVM.FileSystem, RVM.HostFile (../RVM.Host.cls) files (../js/files.mjs), filled by ../js/hostfile-node.mjs or ../js/host-browser.mjs
Commands, redirections IssueCommand, MakeInput, MakeOutput (../RVM.Machine.cls); connectors in ../RVM.Commands.cls issueCommand, makeInput, makeOutput (../js/machine.mjs)
Launching commands RVM.CommandHost (../RVM.Host.cls) NodeHost.run (../js/host-node.mjs); none in the browser
Queues RVM.Queues (../RVM.BaseContext.cls) Queues (../js/context.mjs)
Process (env, cwd, SETLOCAL) RVM.SystemHost NodeHost / BrowserHost
rxqueue filter ../rxqueue/rxqueue.rex, launchers ../rxqueue/rxqueue, ../js/rxqueue/rxqueue (same program)

RVM.Stream.cls, streams.mjs, hostfile-node.mjs and rxqueue.rex are ports of ooRexx code and are under the CPL (see licensing).

Streams

The stream engine

RVM.Stream (JS Stream) is a port of ooRexx's StreamInfo (StreamNative.cpp) plus a model of SysFile. A stream has:

  • a name (as first used) and a qualified name (resolveStreamName, via FileSystem~qualify);
  • a read and a write position, each a character position and, while known, a line position (charReadPosition, lineReadPosition, ...);
  • an open mode (readOnly, writeOnly, readWrite, append), nobuffer, transient, and for BINARY RECLENGTH n streams recordBased and binaryRecordLength;
  • a state: UNKNOWN, READY, NOTREADY (and internally EOF), ERROR, with errorInfo/errorText for STREAM(name, 'D').

Under it is a HostFile, which only knows bytes at 0-based offsets. On top of it the stream keeps the operating-system file model of SysFile: one current offset (fp) shared by reads and writes, an end-of-file flag (fileeof) that stays set once a read past the end failed, the last system error (sysErrno/sysErrtext), and a read-ahead cache of 4096 bytes (CHUNK, sysPeekChunk) for persistent files. A transient stream (device, pipe, terminal) is never read ahead. The sys* methods (sysOpen, sysRead, sysWrite, sysGets, sysSeek, sysCountLines, ...) are that model; everything above them is StreamInfo.

Opening. A stream not explicitly opened opens on first use (implicitOpen): read-write, creating the file unless the operation reads (NOCREATE); if that fails, write-only (for writes) or read-only. A stream opened for writing positions after the existing data, overwriting a final Ctrl-Z (positionAfterData). STREAM ... OPEN parses its options with parseOptions (a port of StreamCommandParser, with its abbreviation rules).

Windows. Names are qualified as GetFullPathName does (JS: qualifyWindows: absolute with its drive, / as \, a final separator kept, the dots and blanks ending the last component dropped, ~ a name like any other) and then getLongName (JS: longNameWindows): the drive letter in upper case and the last component in the case it has on the disk (of a name that does not exist, the last of its leading components that does; the rest as given), so that call PO2A.REX runs po2a.rex and its package is named so; names are caseless, \ and / separate directories, and lines end with CR LF (.endOfLine too). The number of a stream's error is the C library's errno (JS: crtErrnoOf in hostfile-node.mjs, from Node's error code, as Microsoft's _dosmaperr maps the system's: a sharing violation, a denied access or a directory is 13), and the text of a system error is the C library's strerror for errno 1–42 (ooRexx host: CRuntimeError, the MSVCRT table), not the system's translated message. ooRexx opens a file sharing nothing unless OPEN says SHARED, SHAREREAD or SHAREWRITE, so a second open of the same file, even for reading, is ERROR:13, and an open file cannot be deleted (File~delete 0, SysFileDelete 32). The ooRexx host gets this from the ooRexx it runs on; the JS host keeps a table of the open files by name and applies CreateFile's rules (shareClash, openHere in hostfile-node.mjs). RVM_WINDOWS_SHARING=1 turns those rules on anywhere, to test them on Unix. SAY and trace lines end with CR LF too. A redirected standard output has one pointer, which a SEEK moves (_lseeki64) and the commands write at; the JS host keeps it itself, as on Unix (its writes after a SEEK go where it says; Node cannot ask a handle for its pointer: after a command, the size of the file; 18).

NOTREADY. An operation that cannot complete calls eof or notreadyError, which end in raiseNotready: it builds an RVM.ConditionInfo (DESCRIPTION the stream name, RESULT the operation's early-return value, ADDITIONAL the stream, whose Stream object is made when asked for: conditions), attaches the native traceback lines ooRexx would show (nativeStack: Compiled method "LINEIN" with scope "Stream", the COMMAND method line for a STREAM command, the Monitor UNKNOWN line for a standard stream) and their frames (nativeFrames), raises the condition in the context, and then unwinds the stream operation with a private 98.900 whose description is RVM.StreamThrow (JS: a StreamThrow exception). Each *Op entry point catches that unwind (IsThrow; JS guarded) and returns thrownResult. With ::OPTIONS NOTREADY SYNTAX a NOTREADY from an operation (not from a STREAM command, whose ooRexx COMMAND method RAISEs it) is 98.974. Conditions are described in conditions.

The stream table and stream scope

RVM.StreamTable maps names to streams. The null name is the default input (resolve(name, input=.True)) or output stream; STDIN, STDOUT, STDERR (with or without a trailing colon, any case) are the three standard streams, open from the start (openStandard: HostFile~standard); every other name is qualified and the qualified name (uppercased on caseless file systems) is the key. LINEOUT(name) with no data and no position closes the stream and removes it from the table.

As in native ooRexx (RexxActivation::getStreams), the program and each method activation have a table of their own; every other activation (an internal routine, an external program, a Routine object, a ::REQUIRES prolog, INTERPRET) uses its caller's. A method that reads a file its caller also reads opens it again and starts at line 1; a stream it opens is UNKNOWN to its caller. A method's streams are not closed when it returns (as native); what they wrote reaches the file when the process ends at the latest (the host's files are flushed then). Two tables that write the same file write independently, as in native.

The program's table is a global (RVM.BaseContext~streams / streams, made by the first stream function or by activityContext); every table of a run shares its three standard streams (RVM.StreamTable~new(from)), and when .LOCAL is made (RVM.World~ensureLocal) the prelude's .STDIN, .STDOUT and .STDERR take them as their streams (native): native resolveStream sends the functions' messages for those names to .INPUT, .OUTPUT and .ERROR, so LINEIN, PULL and .INPUT~LINEIN share one read position, and so on. Each activation records its table (localStreams) and whether it owns one (streamsOwn, set by newStreamScope for a method); both are saved and restored with the activation (pushActivation / popActivation) and travel with a REPLY (activationState). activeStreams gives the table of the current activation, made when first needed: a method's own, or the caller's found down the saved activations — made there if the caller is a method that has none yet, and recorded in each activation in between, so that a table a routine makes belongs to the method that called it. An activity started by START runs a method, so it gets a table of its own.

What is modelled per activation is the security manager's view (streamScope): when the activation has a security manager, a file name not yet asked about in its scope is sent to the manager (STREAM event, SecureStream); the stream object it returns is kept for the name and the function sends its message to it. The scope is new for a program and for a method (newStreamScope), the caller's for a routine, as native. See objects.

Character and line functions

BIF.CHARIN, CHAROUT, CHARS, LINEIN, LINEOUT, LINES, STREAM resolve their target in this order:

  1. QUEUE: (any case) is the external data queue for the line functions: LINEIN pulls, LINEOUT queues, LINES counts; the character functions give 40.915.
  2. The null name and STDIN/STDOUT/STDERR map to .local's INPUT, OUTPUT, ERROR (LocalStream, ooRexx's resolveStream). When World~localTarget answers an object, the function returns an RVM.BifSend and the machine sends the message (CHARIN, LINEOUT, STATE, COMMAND, ...) from the instruction; otherwise (.local not mounted, or still the original monitor and destination) the stream table's standard stream is used directly. The mechanism is in reflection.
  3. A file stream under a security manager may be redirected to the object it gave (above).
  4. Otherwise the stream table: stream~charinOp(context, bif, ...) etc.

On NOTREADY the functions return: "" (CHARIN, LINEIN), the characters not written (CHAROUT), 1 (LINEOUT), 0 (CHARS, LINES). LINES(name) defaults to option N and gives 1 or 0; C counts.

Stream commands

STREAM(name, 'C', command) is commandOp: the first word, abbreviated, is one of CLOSE FLUSH OPEN POSITION QUERY SEEK; anything else is 93.914, as Stream's COMMAND method gives (ooRexx's function sends the stream that method). The other errors are the methods' too (RVM.Stream~error): a malformed command or option is 93.0 (the engine says why in its code, which is not shown), positioning a transient stream 93.958, SEEK without an offset 93.903. QUERY covers DATETIME, TIMESTAMP, EXISTS, SIZE, STREAMTYPE, HANDLE, POSITION/SEEK ... (a QUERY with options other than for POSITION/SEEK is 93.0); QUERY HANDLE is the OS descriptor (HostFile~handle: 0/1/2 for the standard streams, "" when not open). RECLENGTH accepts up to 2**64-1 with ooRexx's own overflow check (RecLength). OPEN BINARY without RECLENGTH on an empty file is 93.0 and the stream is closed again (native leaves records of length 0 and crashes on the next write; the RVM does not emulate that). FLUSH writes what the file layer still holds (HostFile~flush): when it cannot (a full disk, /dev/full) it is an error NOTREADY with ERROR:n as its result, each time, since the data stays in the buffer; CLOSE says READY: all the same (and the data is lost), as native.

say stream('f.txt', 'C', 'OPEN READ')     -- READY:
say stream('f.txt', 'C', 'QUERY SIZE')    -- 9
say stream('nope.txt', 'C', 'OPEN READ') stream('nope.txt', 'D')
                                           -- ERROR:2 UNKNOWN:

Stream objects: the StreamClasses prelude

The classes Stream (with its mixins InputStream, OutputStream, InputOutputStream), StreamSupplier, RexxQueue and File are ooRexx's own StreamClasses.orx, cut by makeprelude.rex (rexx makeprelude.rex StreamClasses.orx streams > prelude-streams.orx, line numbers preserved). The RVM loads it right after the main prelude (PreludeLoader~loadStreams, then MergeRequired and installNow); its classes are marked as system classes and its public classes become the REXX package's and are put in .environment, as its prolog does natively. See prelude.

Its native methods are EXTERNAL 'LIBRARY REXX stream_*' (and qualify, query_*, handle_set, std_set). LibraryNative sends them to StreamLibrary (JS streamLibrary), which:

  • checks arguments as the C API does (StreamNative.cpp's RexxMethodN): too many 88.922, a required one missing 88.901; integers through Int64Arg/SizeArg (88.907 with the native ranges);
  • STREAM_INIT creates the object's own RVM.Stream as its native value (ooRexx's CSELF); a method on an object whose INIT did not run is 93.900, except CLOSE and UNINIT, which do nothing;
  • runs RVM.Stream~methodOp, the same engine as the functions, with the same errors (the methods'): 93.958, 93.000, 93.903 (SEEK without offset), 93.907 (non-positive positions);
  • QUERY_TIME returns ctime format (Sun Sep 27 13:00:00 2026), which the Rexx code of Stream takes apart; STREAM_ARRAYIN is a port of StreamInfo::arrayin (fixed records via readBuffer, last short record included).

A Stream object's RVM.Stream is independent of the stream table, as natively a Stream object is independent of the activation's table.

.File

File is Rexx code from StreamClasses.orx with LIBRARY REXX file_* natives (FileLibrary / fileLibrary), arguments checked as FileNative.cpp does (all required; 0 arguments for SEPARATOR, PATH_SEPARATOR, CASE_SENSITIVE, LIST_ROOTS, TEMPORARY_PATH; 2 for SET_LAST_MODIFIED/ACCESSED, RENAME, SEARCH_PATH_IMPL; 1 otherwise).

  • ooRexx host: each native delegates to the host ooRexx's own .File on the same file system (TEMPORARY_PATH is TMPDIR or /tmp).
  • Node: files.FileOps from hostfile-node.mjs, a port of SysFileSystem for Unix: existence, type, permissions, length, delete, mkdir, rename, times in local microseconds and their setters (Node treats a negative number as "now" and truncates to µs, so times are passed as strings rounded half away from zero), list in readdir order, roots, temp path, searchPath (only ~, /, ./, ../ skip the path search), links, and the errno-returning operations REXXUTIL uses.
  • Browser: FileOps over the in-memory files of host-browser.mjs. It must exist even without file access, because the stream prelude evaluates File constants (getSeparator, ...) when it loads.

Standard streams and output

The standard streams are HostFile~standard("STDIN"|"STDOUT"|"STDERR"). In the ooRexx host they wrap the host's .Input, .Output, .Error; in Node, STDOUT writes through host.writeOut (the same buffer as SAY, so the two interleave correctly), STDERR through host.writeErr (which flushes stdout first), and STDIN reads host.stdinBuffer, the buffer PULL also reads. SAY and the standard streams go through .local's monitors only when that is observable (reflection); trace and error lines go to standard error, or to .TRACEOUTPUT as TraceObjects when it is observable (machine).

Each standard stream is transient or persistent as the system says (native SysFile::getStreamTypeInfo): a terminal, a character device (/dev/null) or a pipe is transient; anything else (a file redirected to it) is persistent, with a size, CHARS/LINES that count, and positions (LINEIN(, n), CHARIN(, n), SEEK, a positioned CHAROUT/LINEOUT). Native tests the mode with & S_IFCHR and & S_IFIFO, so a block device is transient and a socket persistent; both hosts test the same bits (the ooRexx host asks its own .Stream, Node fstats the descriptor).

A persistent standard output or error shares its offset with the commands the program runs and with the other standard stream when both are the same file (2>&1): native writes where the descriptor is (writeSetup does not seek an append stream, getPosition reads the offset). The stream reads it before each write and before a relative seek (sysTell: fp = file~tell), and a seek moves it (file~seek); a file opened to append (>>) gets every write at its end. Standard input does not follow the descriptor: the stream reads ahead (in 4096-byte blocks in Node, as SysFile; a whole chunk when a reader read it for an activity that waited), as native's does, and a command that reads standard input gets what is left after that.

A read of standard input that is a terminal or a pipe may make only its activity wait while the others run: a reader process reads for it, and the read runs again when what it needs is there (concurrency).

SAY writes to standard output straight, not through the stream, which native's SAY is (a LINEOUT of .OUTPUT). What that changes is made up where it shows: QUERY POSITION WRITE answers where the last write ended (file~writePosition: the ooRexx host asks its .Output, which SAY writes to; Node keeps it, StdFile.mark), and the lines SAY wrote since the stream last looked are added to its line write position when it is next used (absorbSaid, from HostFile~saidLines; only the stream table's standard output, the one .OUTPUT sends to, counts them).

ADDRESS and commands

Environments and ADDRESS settings

Each activation has address, alternateAddress and ioConfigs (environment name, uppercased → the WITH configuration of an ADDRESS env WITH ... instruction). The instructions compile to ADDRT (swap), ADDRS/ADDRV (set; setAddress), CMD (command to the current environment) and CMDTO (ADDRESS env command [WITH ...]); see R-code. Names longer than 250 characters are 29.1; symbol names are uppercased by the compiler, strings kept as written, and lookup is caseless. ADDRESS env WITH ... replaces that environment's default configuration. ADDRESS() takes no arguments (40.4).

The initial environment is the host's initialAddress (sh; CMD on Windows). An internal routine inherits the caller's settings (with its own copy of ioConfigs, so changes do not leak back); an external program file keeps the caller's ADDRESS; a ::ROUTINE, a Routine object or a ::REQUIRES prolog starts with the default (defaultAddress), and so does a method activation (EnterMethod), as native (RexxActivation.cpp: every method activation starts with the instance's default environment, current and alternate). When the callee returns, the caller's ADDRESS comes back.

Issuing a command

IssueCommand(context, env, command, local) (JS issueCommand), called by CMD/CMDTO after tracing >>> under TRACE C:

  1. Redirections are evaluated, INPUT then OUTPUT then ERROR, each with PickSpec: the command's own WITH wins; its NORMAL means "not redirected" even if the default redirects; otherwise the environment's default. Targets are evaluated (and traced) at this point, every time the command runs (see below). If OUTPUT and ERROR resolve to the same target (sameTarget) they are merged.
  2. Security manager. If the activation has one, it is sent COMMAND (COMMAND, ADDRESS entries; ooRexx's callCommandExit). If it handles it, its RC (default 0) is the command's and FAILURE/ERROR entries select the condition.
  3. Library environments. An environment registered by a library (registeredEnvironment; JS world.addressEnvironment; e.g. hostemu) runs the command through its handler; it does not redirect, so a WITH (local or the environment's) is 98.921. See libraries.
  4. Host strategy. host~strategyFor(env); .Nil means not registered: RC 30 and FAILURE (the WITH targets were still evaluated).
  5. Input is read in full (bytes, each line followed by the host's lineEnd) before any output target is opened, so a command may read from and write to the same stem or file. If an InputStream fails during its LINEIN, the command runs with what was read and the error is raised afterwards (ooRexx reads input while the command runs).
  6. In-process commands. With no redirection at all (local and the default both .Nil), runInternally handles cd, export, set, unset (only without unquoted < > | & ;), so they affect later commands. cd failures are ERROR with RC = errno (2, 13 for an unreadable directory, 20 for a non-directory); ~ and ~user are expanded; $VAR is expanded in exported values. This mirrors ooRexx's Unix SystemCommands.cpp.
  7. Run (host~run(strategy, command, inputBytes, captureOutput, errorMode)), errorMode being INHERIT, CAPTURE or MERGE. Captured text is written to the targets (writeText), split by SplitOutput (a port of OutputRedirector::scanLine: lines end at LF or CR LF, a final unterminated line is kept, a trailing CR dropped). When the activity may wait for it (another activity or a timer could run meanwhile, see concurrency), host~start launches it instead and IssueCommand returns an RVM.CommandWait; the rest of this step and the next (CommandFinish) run when it has ended, in its activity. An input that failed makes it run waited for.
  8. RC and condition. RC is set (not at an interactive pause): the exit status, minus the signal number for a killed command, 127 if it could not start. Not started or 127 → FAILURE; other non-zero → ERROR. .RS becomes 1, -1 or 0. CommandTrace adds the +++ RC(n) lines, CommandCondition raises ERROR/FAILURE (an untrapped FAILURE is raised again as ERROR; ::OPTIONS ERROR|FAILURE SYNTAX gives 98.970/98.971); see conditions.

../RVM.Commands.cls holds the connectors the machine uses (RVM.StreamInput, RVM.LinesInput, RVM.StreamOutput, SplitOutput, SplitFileLines, JoinLines) and a good prose description of the redirection rules. The redirectors of stem and stream objects (RVM.StemObjInput, RVM.StemObjOutput, RVM.ObjectOutput, RVM.StreamObjInput) are in ../RVM.Machine.cls, with IssueCommand, PickSpec, MakeInput and MakeOutput.

WITH redirection

Targets follow ooRexx's CommandIOConfiguration. Each target is evaluated when the command runs and traced: a string >L>, a stem >V>, an expression with its own trace, then >K> "OUTPUT" => value. An expression target is compiled as a thunk (separate code ending in YIELD, run in a nested machine by TargetValue, as part of the ADDRESS's activation: its errors, traps, EXIT and frames are that activation's; see machine); a wait inside it runs the other activities in place (07). String conversions of objects during a command use SyncString, which sends STRING at once, because a command cannot be re-executed the way other instructions resume after a Rexx STRING method.

INPUT OUTPUT / ERROR
STEM s. s.1…s.n, n = s.0 (no s.0: 98.998; bad: 26.904); unset tails read as the stem's default REPLACE (default) empties the stem keeping its default value and sets s.0 = 0; APPEND continues after s.0 (no s.0: as REPLACE)
STREAM name the file's lines (LF, CR stripped); unreadable 98.999 the file replaced or appended; not openable 98.920
USING string one line 98.996
USING stem as STEM as STEM
USING InputStream / Monitor LINEIN until NOTREADY (sendSyncWatch) —
USING OutputStream / Monitor — LINEOUT per line; REPLACE/APPEND given: 98.997
USING RexxQueue — QUEUE per line; option given: 98.922
USING File its lines (ABSOLUTEPATH, then as STREAM) as STREAM on its path
USING OrderedCollection — APPEND per line; EMPTY first unless APPEND (even with no output)
USING other MAKEARRAY (Array) or REQUEST('ARRAY'), items as strings; not an Array: 98.924 98.996

INPUT USING a File hangs natively (Interrupted system call after a signal); the RVM reads the file and does not emulate the hang.

address sh 'sort' with input stem in. output using (q)   -- q an Array
address path 'echo two words' with output stem p. error stem e.

How commands run in each host

ooRexx host (RVM.CommandHost~run). Strategies (strategyFor): SH, "", COMMAND, SYSTEM → /bin/sh -c command; KSH CSH BSH BASH TCSH ZSH → /bin/<lowercase name> -c command (RC 127 if not installed); PATH → no shell: the command is split into words (SplitCommand: blanks/tabs; a word starting with " runs to a " followed by a blank or the end) and the first word searched in PATH (FindInPath). The program and its arguments are single-quoted into one exec ... line, so the outer shell interprets nothing, with <file, >file, 2>file or 2>&1 for the redirected streams (temporary files, TempFile), prefixed by the queue and macrospace sharing variables (below), and run with the host's Address System. .output and .error are flushed first so earlier output precedes the command's. Uncaptured streams are inherited.

Node (NodeHost.run). The same strategies and the same exec line, run with spawnSync("/bin/sh", ["-c", line], {stdio: "inherit"}); the environment gets RVM_QUEUES, RVM_MACROSPACE and the PATH with the js/rxqueue directory first. The output buffer is flushed first. Killed commands give -signal number.

Browser (BrowserHost). There are no commands: strategyFor answers null for every environment, so every command is RC 30, FAILURE (library environments such as hostemu still work). readFile / openOutputFile work on the in-memory files.

Windows . Both hosts follow ooRexx for Windows: CMD is the initial environment; CMD, "", COMMAND and SYSTEM run the command through cmd.exe, PATH runs the program itself, and any other name is RC 30, as on Unix. A command cmd.exe does not know is RC 9009 and an ERROR; RC 127 means nothing special there (CommandFinish / commandFinish ask the host's windows). Windows is told by the file separator (IsWindows, .File~separator == "\"): .RexxInfo~platform says WindowsNT there.

  • ooRexx host. prepare marks the command native, and NativeRun gives it to the same environment of the ooRexx the RVM runs on (Address Cmd, Command, System or Path), with an ADDRESS ... WITH of Arrays for what is fed or captured: the input is given as lines, the captured lines come back as bytes ended by CR LF, and with MERGE the standard error goes to the output's Array. So it is ooRexx's own semantics, cmd.exe and its return codes included, and cd, set and D: are carried out by the interpreter, in this process (runInternally leaves them to it). A FAILURE of the native ADDRESS (for PATH, a program that cannot be started: RC 1) is trapped, and the machine raises its own FAILURE. A command started by start runs NativeRun in the RVM.CommandJob's thread.
  • Node. prepareWindows builds ooRexx's line: %ComSpec% /c command (given as it is, windowsVerbatimArguments; as ooRexx's, without a leading @, between two more double quotes when it has more than two, since cmd.exe takes off the first and the last, and with no /c when it starts with /k) for the cmd.exe environments, the program and its words (splitCommand) for PATH. What is fed or captured goes through temporary files given to the command as its standard streams, so the bytes are exact; startWindows runs it from a small Node process that writes its status to a file. A PATH program that cannot be started (an empty command, a missing file) is RC 1 and a FAILURE. runInternallyWindows carries out, with the cmd.exe environments only, cd and chdir (with /d), a drive (D:) and set NAME=VALUE; a failing cd has SetCurrentDirectory's error (2: the last component is missing; 3: one above it; 267: not a directory).
  • Not yet: the queues and the macrospace are not shared with the command (RVM_QUEUES, RVM_MACROSPACE and the RVM's rxqueue, which is a shell script).

The launchers for Windows are rvm.cmd and js/rvm.cmd: as rvm and js/rvm, they set RVM_EXECUTABLE and put the package's bin first in REXX_PATH.

Blocking. run is synchronous; when another activity could run meanwhile, start runs the command instead and only its activity waits (concurrency).

Queues

RVM.Queues

The external data queues are local to the RVM process: RVM.Queues (class methods; JS Queues) holds SESSION and the named queues, each an Array of lines (index 1 = head). ooRexx's queues live in the rxapi daemon and are shared by every process on the machine; the RVM does not use rxapi (accepted: 17).

  • Names: 1–250 characters of A-Z a-z 0-9 . ! ? _, stored uppercased. SESSION always exists and cannot be created or deleted.
  • Return codes are rxapi's: 0, 5 RXQUEUE_BADQNAME, 9 RXQUEUE_NOTREG, 10 RXQUEUE_ACCESS (DELETE while a LINEIN waits on it).
  • create(name): the name as given if it is free; otherwise, or with no name, a unique S000Q + 12 hex digits (natively S + pid + Q + address). open creates if absent; exists, delete, add (addOrFail: failure is 48.1 SYSTEM QUEUE (RXQUEUE_NOTREG)), pull, count, clear.
  • LINEIN waits: waitFor(name) gives the queue's RVM.EventSem, posted (and reset) by every add and by restore (concurrency).

The current queue; PUSH, QUEUE, PULL, QUEUED

The current queue (RVM.Queues~current) is the NAMED_QUEUE of .STDQUE (the RexxQueue instance .local holds; stdque and scope are set when .local is mounted, World~ensureLocal), or SESSION before that.

Natively every queue instruction and function is a message to .STDQUE: PUSH and QUEUE send PUSH and QUEUE; PULL / PARSE PULL sends PULL, and on .nil (an empty queue) reads a line as PARSE LINEIN does; QUEUED() and LINES('QUEUE:') send QUEUED (LINES makes it 1 or 0 with N); LINEOUT('QUEUE:', line) sends QUEUE; LINEIN('QUEUE:') sends LINEIN (its other arguments are only checked), which waits on an empty queue for another activity to queue a line (RexxQueue) and gives .nil if the queue has been deleted. The RVM sends the same messages only when someone could tell (queueTarget, on the context and RVM.World): .local is mounted and its STDQUE is not the RexxQueue it was made with (any object: its methods run), or RVM_LOCAL=eager, or, for PUSH, QUEUE and LINEOUT, the current queue has been deleted (the 48.1 comes from RexxQueue's method, with its Compiled method "PUSH" with scope "RexxQueue" traceback line). Otherwise it works on the queue straight: queueLine, pushLine, pullLine, queued (LINEIN('QUEUE:') always sends). The instructions send from the machine (SENDA; PULL with sendSync), the functions through an RVM.BifSend. Removing STDQUE from .local makes the target .nil (native dereferences a null pointer).

RXQUEUE and RexxQueue

BIF.RXQUEUE(option [, name]) does what ooRexx's function does: it sends messages, returned as an RVM.BifSend for the instruction to send. G and S go to .STDQUE (GET, SET); C, O, E, D go to the RexxQueue class (CREATE, OPEN, EXISTS, DELETE). Errors: bad option 40.904, missing name 40.3, extra argument 40.4, a name that is not a symbol or is longer than 250 characters 40.26 (text 40.26/2).

n = rxqueue('Create')                 -- S000Q000000000001
old = rxqueue('Set', 'mine')          -- SESSION; QUEUE/PULL now use MINE

RexxQueue is the class from StreamClasses.orx; its natives LIBRARY REXX rexx_*_queue go to QueueLibrary (JS queueLibrary) with API argument checks (88.922, 88.901) and 98.901 for an instance without NAMED_QUEUE. LINEIN is UNGUARDED (ooRexx's SetGuardOff) and really waits on an empty existing queue: the native returns an RVM.Wait on the queue's event semaphore and the activity is resumed when a line arrives; a missing queue gives .nil.

Sharing queues with commands: RVM_QUEUES

Before every command it launches, the RVM writes its queues to a temporary file (RVM.Queues~snapshot) and exports its path as RVM_QUEUES; it also puts its own rxqueue directory first in the command's PATH (rvm/rxqueue for the ooRexx host, rvm/js/rxqueue for Node; FindInPath searches it first for ADDRESS PATH too). The file format:

RVMQUEUES 1 <counter>
SESSION <n>
<length> <line>          (n such lines; the line is raw bytes)
OTHERNAME <m>
...

SESSION comes first, then the other queues sorted by name; counter keeps generated names unique across processes. After the command, if the file changed, restore replaces the queues with its contents (queues absent from it disappear; waiting LINEINs on queues that have lines are posted).

An RVM started with RVM_QUEUES set loads the file at start (RVM.SystemHost~shareQueues from rvm.rex; NodeHost.shareQueues from rvm.mjs) and writes it back at the end only if its queues changed (endProgram; JS process.on("exit")), so rvmprog | rxqueue does not have one side clobber the other unnecessarily. Each nesting level has its own file. The REXXUTIL macrospace is shared the same way through RVM_MACROSPACE (RVM.SharedMacros; see libraries).

RVM.Host.cls cannot refer to RVM.Queues (RVM.BaseContext.cls requires it), so RVM.Queues~activate registers itself as RVM.CommandHost~queues; run shares queues only when that is set (it always is in a run).

The rxqueue filter

../rxqueue/rxqueue.rex is a Rexx port of ooRexx's rxqueue.cpp (Unix). The launchers rxqueue/rxqueue (runs ../rvm) and js/rxqueue/rxqueue (runs js/rvm) run it on the same RVM as the parent, so it reads and rewrites RVM_QUEUES.

  • Usage: rxqueue [name] [/FIFO | /LIFO | /CLEAR]; options start with / or -, caseless, at most one; the queue is the one named, else the RXQUEUE environment variable, else SESSION.
  • Lines are cut as get_line does: at LF, at CR (and a following LF; any other character after a CR is data), at end of input; Ctrl-Z ends the input (the line before it is lost unless empty); lines are truncated to 65472 characters.
  • Errors go to standard output with the exit code: 0 bad invocation, 5 bad queue name, 9 queue does not exist.
  • The arguments are the words of the argument string, not shell words ('a b' is two arguments).
'printf "a\nb\n" | rxqueue'      -- the RVM's rxqueue, via PATH
say queued()                     -- 2

The host interface

Everything platform-dependent is behind a small interface; the machine, streams, commands and queues above are the same code on every platform.

ooRexx host: RVM.Host.cls

Class Role
RVM.CommandHost environments and launching: initialAddress, lineEnd, strategyFor, run, runInternally, readFile (98.999), openOutputFile (98.920), qualifyName; constants UNKNOWN_COMMAND 127, NOT_REGISTERED 30; class attributes queues, macros
RVM.FileSystem qualify, isFile, caseless, pathSeparators, hasDrives, lineEnd, errorText (SysGetErrortext), size, timeStamp
RVM.HostFile a file as bytes: open(access, create, truncate) with access READ/READWRITE/WRITE, readAt(offset, length), writeAt(offset, data), size, hasData, flush, close, handle; attributes errno, errtext, transient, device, isOpen; HostFile~standard(which), and for a persistent standard output or error tell, seek(offset), writePosition, saidLines (class attribute said: the lines SAY wrote). Built on a host .Stream, whose SysFile buffering the RVM inherits
RVM.SystemHost the process: systemName, getEnv/setEnv/envExists, currentDirectory/changeDirectory, userid, beep, gc, SETLOCAL/ENDLOCAL (hasLocalEnvironments, pushLocal, popLocal: a snapshot of the directory plus a journal of changed variables; the oldest open snapshot is restored at endProgram), shareQueues, endProgram

JS host object

A JS host is an object passed to the runner (NodeHost, BrowserHost) plus the file layer it installs with installFiles (FileSystem, HostFile, FileOps, toBytes, fromBytes; see ../js/files.mjs). Strings are binary (one character per byte); Node converts names and environment values between latin1 and UTF-8.

The members of the host object that the machine and the runtime call are listed, authoritatively, in 14 — The host interface. Both hosts also have envExists, which the runtime does not call, and the Node host two members used only by its launcher rvm.mjs: writeCache (-w) and shareQueues (loading RVM_QUEUES, above).

Node (host-node.mjs) Browser (host-browser.mjs)
stdout / stderr fds 1/2, stdout buffered (64 KB) and flushed before stderr, commands, compiler calls and the end; to a terminal also at each line end, otherwise also when it has waited 250 ms (idleFlush, also at the end of each time slice), so that a run killed by a signal loses little onOut / onErr callbacks
stdin fd 0, read in 4096-byte blocks (as SysFile); a file redirected to it is read by position once a position was asked for or a command ran (StdFile); for an activity that waits, by the main thread (stdinFetch: 07) a text given to the constructor
files real files (hostfile-node.mjs, a port of SysFile/SysFileSystem) an in-memory file system with /, /home, /home/rexx (HOME, initial cwd), /tmp; a read-only library (addLibrary) whose roots go into REXX_PATH
environment process.env a Map (HOME, USER, PATH, REXX_PATH)
commands /bin/sh via spawnSync none (RC 30)
compiler the ooRexx RVM in a subprocess (rexx rvm.rex -f/-s/-p) compiler.mjs when enableCompiler was called

hostfile-node.mjs reproduces SysFile's write buffering: the last write to a persistent file (up to 4096 bytes) stays pending until the next write, read, size, flush, close or process exit, so a command started in between sees the file as it would under ooRexx. QUERY HANDLE there is Node's descriptor, which differs from native's numbers (Node has more files open). See JavaScript for the module map.

Host differences

  • .File and the file layer: host ooRexx's .File/.Stream (ooRexx host) vs ports of SysFileSystem/SysFile (Node) vs memory (browser).
  • Node writes the queue and macrospace files for every command; the ooRexx host does so when RVM.CommandHost~queues/macros are set (always, once their classes are activated).
  • The browser has no commands and no queue sharing.
  • QUERY HANDLE values differ in Node.

Design notes

  • Port the stream engine, keep only bytes in the host. Stream behaviour (positions, line counting, NOTREADY, the command parser, the quirks of seeking past the end and of LINES) is ooRexx's StreamInfo code ported to both hosts, so both RVMs behave the same and match native; the host supplies only "bytes at offsets". The SysFile model (one shared offset, sticky EOF) is reproduced because programs observe it.
  • Stream objects reuse the same engine. Stream is ooRexx's own Rexx code with LIBRARY REXX natives mapped onto RVM.Stream~methodOp, the same structure native has (StreamClasses.orx over StreamNative.cpp); the functions, which send the stream its method in ooRexx, get the methods' errors too (93.x).
  • Stream tables follow native (P1). A program written for ooRexx sees each method's streams as its own, and a portable program may depend on it (a method that reads a file from line 1 while its caller is half-way through). The tables are made when first needed, so a method that does no I/O costs nothing; the lookup down the saved activations happens only when a routine uses a stream before its method has a table.
  • Commands go through /bin/sh exec with every word quoted. One code path launches both shell and PATH strategies with the exact argv, temporary files carry input and captured output, and the host language needs no process API beyond "run a shell line" (Address System in ooRexx, spawnSync in Node).
  • Input before output. Reading the whole input before opening output targets lets a command read and write the same stem or file, and keeps redirection independent of the command's timing.
  • Queues are the RVM's own. A local implementation keeps the RVM free of the rxapi daemon and identical in both hosts and the browser. Sharing with child processes is done by snapshot files plus an RVM-run rxqueue rather than by talking to rxapi (rejected: it would tie the RVM to the native daemon and its protocol). Writing back only on change avoids clobbering in pipelines.
  • No emulation of native crashes and hangs (OPEN BINARY on an empty file, INPUT USING a File): the RVM gives the error or the result instead.

Divergences from native

  • A new Stream object for a standard input redirected to a file (.stream~new('STDIN')) reads it from the start; native's believes it is at position 1 but reads where the descriptor is (after what .INPUT read ahead: usually nothing). Accepted: two stream objects on one descriptor are undefined behaviour (17).
  • Queues are per process (accepted): shared only with processes the RVM launches, only between commands (not live), with the last writer winning when several RVMs in a pipeline change them; a native rexx started by the RVM does not see them; commands get the RVM's rxqueue first in PATH; rxqueue arguments are words of the argument string.
  • Generated queue names are S000Q + hex counter.
  • Captured command output reaches its targets after the command ends.
  • QUERY HANDLE numbers differ in the JS host.

Known gaps

  • No command execution in the browser (RC 30); on Windows, no queues or macrospace shared with the command (above).