/******************************************************************************/ /* */ /* RVM.Host.cls - Launching commands (the RVM's runtime) */ /* ===================================================== */ /* */ /* This file is the platform-specific part of command execution. It knows */ /* which ADDRESS environments exist on the platform and how each one launches */ /* a command; it runs the command with its standard streams either inherited */ /* or captured, and reports the return code. What to feed the command and */ /* where its output goes (ADDRESS ... WITH) is decided elsewhere, by the */ /* machine (IssueCommand in RVM.Machine.cls, with the redirectors of */ /* RVM.Commands.cls), and is the same on every platform. */ /* */ /* Environments (Unix): */ /* */ /* SH, "", COMMAND, SYSTEM /bin/sh -c command (SH is the initial one) */ /* BASH KSH CSH TCSH ZSH BSH /bin/ -c command (lowercased name); the */ /* command fails (RC 127) if that shell is not */ /* installed */ /* PATH no shell: the command is split into words */ /* (blank-delimited, "double quoted" words kept */ /* together) and the first word is searched for */ /* in PATH */ /* */ /* Any other name is not a registered environment (RC 30). Names match */ /* caselessly. When nothing is redirected, "cd", "export", "set" and "unset" */ /* commands without pipes or redirections are carried out by the interpreter */ /* itself, so that they affect the commands that follow. */ /* */ /* Environments (Windows): */ /* */ /* CMD, "", COMMAND, SYSTEM (CMD is the initial one) and PATH: the */ /* command is given to the same environment of */ /* the ooRexx the RVM runs on (NativeRun), with */ /* its own ADDRESS ... WITH for what is fed or */ /* captured. So it is ooRexx's own semantics: */ /* cmd.exe, its return codes (9009, a command */ /* it does not know, is an ERROR, not a */ /* FAILURE), and "cd", "set" and "D:" carried */ /* out by the interpreter, in this process. */ /* */ /* Any other name is not a registered environment (RC 30), as on Unix. Not */ /* yet on Windows: the queues and the macrospace shared with the command */ /* (RVM_QUEUES, RVM_MACROSPACE, the rxqueue of the RVM). */ /* */ /* Windows is told by the file separator (IsWindows): .RexxInfo~platform */ /* says "WindowsNT" there, not "WINDOWS". */ /* */ /* This file is part of the RVM, the Rexx Virtual Machine */ /* [See https://rexx.epbcn.com/rexx-parser/] */ /* */ /* Copyright (c) 2026 Josep Maria Blasco */ /* */ /* License: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0) */ /* */ /******************************************************************************/ ::Class RVM.CommandHost Public ::Attribute queues Class -- RVM.Queues (it sets it), or .Nil ::Attribute macros Class -- RVM.SharedMacros (it sets it), or .Nil ::Constant SHELLPATH "/bin" ::Constant UNKNOWN_COMMAND 127 -- RC when a command cannot be started ::Constant NOT_REGISTERED 30 -- RC for an environment that does not exist ::Method activate Class Expose queues macros If Symbol( "QUEUES" ) \== "VAR" Then queues = .Nil If Symbol( "MACROS" ) \== "VAR" Then macros = .Nil ::Method init Expose windows windows = IsWindows() -- Are we on Windows? (The machine asks: there, a command that cmd.exe does -- not know is an ERROR, and RC 127 means nothing special.) ::Method windows Expose windows Return windows -- The environment a program starts with. ::Method initialAddress Expose windows If windows Then Return "CMD" Return "sh" -- The line-end sequence that ends each line fed to a command. ::Method lineEnd Expose windows If windows Then Return "0d0a"x Return "0a"x /******************************************************************************/ /* strategyFor(env) -- how 'env' launches commands: a Directory with */ /* kind "SHELL" (program = the shell) or "PATH" (no shell) */ /* env the environment name */ /* or .Nil when 'env' is not a registered environment. */ /******************************************************************************/ ::Method strategyFor Expose windows Use Strict Arg env name = Upper(env) strategy = .Directory~new strategy~env = env If windows Then Do If WordPos(name, "CMD COMMAND SYSTEM PATH") == 0, name \== "" Then Return .Nil strategy~kind = "WINDOWS" Return strategy End Select When name == "" | WordPos(name, "SH COMMAND SYSTEM") > 0 Then Do strategy~kind = "SHELL" strategy~program = self~SHELLPATH"/sh" End When WordPos(name, "KSH CSH BSH BASH TCSH ZSH") > 0 Then Do strategy~kind = "SHELL" strategy~program = self~SHELLPATH"/"Lower(env) End When name == "PATH" Then strategy~kind = "PATH" Otherwise Return .Nil End Return strategy /******************************************************************************/ /* run -- launch 'command' with 'strategy' and wait for it. */ /* */ /* input .Nil to inherit standard input, or the exact bytes to feed it */ /* output .True to capture standard output, .False to inherit it */ /* error "INHERIT", "CAPTURE" or "MERGE" (standard error goes wherever */ /* standard output goes) */ /* */ /* Returns a Directory: rc (the exit status, or minus the signal number when */ /* the command was killed), started (.False when it could not be launched at */ /* all; rc is then 127), out and err (the captured bytes, or ""). */ /* */ /* start launches it the same way, but in a thread of the host of its own (an */ /* RVM.CommandJob), and returns at once: the RVM goes on (its other */ /* activities run, see doc/07-concurrency.md), 'sem' (an EventSemaphore) is */ /* posted when the command ends, and then finish gives the result as run. */ /******************************************************************************/ ::Method run Use Strict Arg strategy, command, input, output, error Trace Off -- the launch itself must not trace anything res = self~prepare( strategy, command, input, output, error ) If \ res~started Then Return res If res~native Then res~rc = NativeRun( res ) Else Do Address System res~line res~rc = rc End Return self~finish( res ) ::Method start Use Strict Arg strategy, command, input, output, error, sem Trace Off res = self~prepare( strategy, command, input, output, error ) If \ res~started Then Return res res~job = .RVM.CommandJob~new If res~native Then res~job~go( "", sem, res ) Else res~job~go( res~line, sem ) Return res -- The line /bin/sh runs, with its temporary files (run, start). ::Method prepare Private Expose windows Use Strict Arg strategy, command, input, output, error Trace Off res = .Directory~new res~out = "" res~err = "" res~output = output res~error = error res~native = .False -- Windows: the command goes to ooRexx's own environment (see NativeRun). If windows Then Do res~native = .True res~env = strategy~env res~command = command res~input = input res~temps = .Array~new Call Flush .output Call Flush .error res~started = .True Return res End -- The program and its arguments. If strategy~kind == "PATH" Then Do argv = SplitCommand( command ) If argv~items == 0 Then argv = .Array~of( "" ) program = FindInPath( argv[1] ) End Else Do argv = .Array~of( strategy~program, "-c", command ) program = strategy~program If \ IsExecutable( program ) Then program = .Nil End -- Not found / not executable: the command cannot even start. If program == .Nil Then Do res~rc = self~UNKNOWN_COMMAND res~started = .False Return res End -- Run it through /bin/sh with 'exec', every word single-quoted so the shell -- does no interpretation of its own: the program sees exactly argv. line = "exec" Do word Over argv line = line Quote( word ) End temps = .Array~new If input \== .Nil Then Do inFile = TempFile() temps~append( inFile ) Call CharOut inFile, input Call Stream inFile, "C", "Close" line = line "<"Quote( inFile ) End If output Then Do res~outFile = TempFile() temps~append( res~outFile ) line = line ">"Quote( res~outFile ) End Select When error == "CAPTURE" Then Do res~errFile = TempFile() temps~append( res~errFile ) line = line "2>"Quote( res~errFile ) End When error == "MERGE" Then line = line "2>&1" Otherwise Nop End -- The queues, shared with what the command starts: a file (RVM_QUEUES) -- that an RVM (rxqueue.rex is run by one) reads and writes back; the RVM's -- rxqueue, first in PATH. -- (RVM.Queues is not visible from here: it sets the class's 'queues'.) shared = .RVM.CommandHost~queues res~shared = shared If shared \== .Nil Then Do res~queuesFile = TempFile() temps~append( res~queuesFile ) res~queues = shared~snapshot Call CharOut res~queuesFile, res~queues Call Stream res~queuesFile, "C", "Close" shims = FileSpec( "Location", .context~package~name )"rxqueue" line = "RVM_QUEUES="Quote( res~queuesFile ) - "PATH="Quote( shims )':"${PATH:-/bin:/usr/bin}"' - "export RVM_QUEUES PATH;" line End -- The macrospace, shared in the same way (RVM_MACROSPACE). sharedMacros = .RVM.CommandHost~macros res~sharedMacros = sharedMacros If sharedMacros \== .Nil Then Do res~macrosFile = TempFile() temps~append( res~macrosFile ) res~macros = sharedMacros~snapshot Call CharOut res~macrosFile, res~macros Call Stream res~macrosFile, "C", "Close" line = "RVM_MACROSPACE="Quote( res~macrosFile ) "export RVM_MACROSPACE;" line End -- Anything already written must appear before what the command writes. Call Flush .output Call Flush .error res~line = line res~temps = temps res~started = .True Return res -- A command that ran (res, from prepare; its rc set): what it changed of the -- queues and the macrospace, what it wrote, and its files deleted. ::Method finish Use Strict Arg res Trace Off If res~job \== .Nil Then res~rc = res~job~rc If res~shared \== .Nil Then Do after = ReadAll( res~queuesFile ) If after \== res~queues Then res~shared~restore( after ) End If res~sharedMacros \== .Nil Then Do after = ReadAll( res~macrosFile ) If after \== res~macros Then res~sharedMacros~restore( after ) End -- (Windows: NativeRun has already set out and err.) If \ res~native Then Do If res~output Then res~out = ReadAll( res~outFile ) If res~error == "CAPTURE" Then res~err = ReadAll( res~errFile ) End Do file Over res~temps Call SysFileDelete file End Return res /******************************************************************************/ /* runInternally -- carry out "cd", "export", "set" and "unset" in the */ /* interpreter itself. Only used when nothing is redirected, and only for a */ /* command without unquoted <, >, |, & or ;. Returns .Nil when the command is */ /* not one of those (it must then be launched normally), or a Directory with */ /* rc and condition ("" or "ERROR"). */ /******************************************************************************/ ::Method runInternally Expose windows Use Strict Arg command If windows Then Return .Nil -- Any unquoted redirection or command separator: leave it to the shell. inQuotes = .False escape = .False Do i = 1 To Length(command) c = SubStr(command, i, 1) Select When escape Then escape = .False When c == "\" Then escape = .True When c == '"' Then inQuotes = \ inQuotes When \ inQuotes, Pos(c, "<>|&;") > 0 Then Return .Nil Otherwise Nop End End If command == "cd" | Left(command, 3) == "cd " Then Return ChangeDirectory( command ) If Left(command, 4) == "set " Then Return SetVariable( command, "SET" ) If Left(command, 6) == "unset " Then Return SetVariable( command, "UNSET" ) If Left(command, 7) == "export " Then Return SetVariable( command, "EXPORT" ) Return .Nil /******************************************************************************/ /* Files used as redirection targets and sources */ /******************************************************************************/ -- The whole content of a file, as bytes, or raise error 98.999 when it cannot -- be opened for reading. ::Method readFile Use Strict Arg name s = .Stream~new( name ) r = s~open("READ") If r \== "READY:" Then Raise Syntax 98.999 Array( name, r ) data = s~charIn( 1, s~chars ) s~close Return data -- Open a file for writing lines; raise error 98.920 when it cannot be opened. -- Returns a stream object that understands lineOut and close. ::Method openOutputFile Use Strict Arg name, append s = .Stream~new( name ) If append Then r = s~open("WRITE APPEND") Else r = s~open("WRITE REPLACE") If r \== "READY:" Then Raise Syntax 98.920 Array( name, r ) Return s -- The fully qualified form of a file name (two names for the same file must -- compare equal). ::Method qualifyName Use Strict Arg name Return .File~new( name )~absolutePath /******************************************************************************/ /* Helpers */ /******************************************************************************/ -- Split a command into words the way the PATH environment does: words are -- delimited by blanks and tabs; a word that starts with a double quote runs up -- to the next double quote that is followed by a blank, a tab or the end, and -- both quotes are removed. ::Routine SplitCommand Use Strict Arg command words = .Array~new blank = " "||"09"x n = Length(command) i = 1 Loop Do While i <= n, Pos(SubStr(command, i, 1), blank) > 0 i = i + 1 End If i > n Then Leave If SubStr(command, i, 1) == '"' Then Do i = i + 1 -- skip the opening quote start = i -- Up to a blank or tab that follows a quote (not the opening one), or -- the end of the command. Do While i <= n If i > start, SubStr(command, i - 1, 1) == '"', - Pos(SubStr(command, i, 1), blank) > 0 Then Leave i = i + 1 End last = i - 1 If last >= start, SubStr(command, last, 1) == '"' Then last = last - 1 word = SubStr(command, start, last - start + 1) End Else Do start = i Do While i <= n, Pos(SubStr(command, i, 1), blank) == 0 i = i + 1 End word = SubStr(command, start, i - start) End words~append( word ) i = i + 1 -- step over the delimiter End Return words -- Find a program the way a PATH search does: a name with a slash is used as -- is, otherwise each directory in PATH is tried in order (an empty entry is the -- current directory). Returns the name to launch, or .Nil when nothing -- executable is found. ::Routine FindInPath Use Strict Arg name If name == "" Then Return .Nil If Pos("/", name) > 0 Then Do If IsExecutable( name ) Then Return name Return .Nil End -- As execvp: the default path only when PATH does not exist; an empty one -- is one empty element, the current directory. path = Value( "PATH", , "ENVIRONMENT" ) If path == "", \ .RVM.SystemHost~envExists( "PATH" ) Then path = "/bin:/usr/bin" -- (The command's PATH has the RVM's rxqueue first: see run.) path = FileSpec( "Location", .context~package~name )"rxqueue:"path Do dir Over path~makeArray(":") If dir == "" Then candidate = name Else candidate = dir"/"name If IsExecutable( candidate ) Then Return name End Return .Nil -- Is 'file' an existing regular file with an execute permission bit? ::Routine IsExecutable Use Strict Arg file If \ SysIsFile( file ) Then Return .False Call SysFileTree file, "found.", "FL" If found.0 == 0 Then Return .False perms = Word( found.1, 4 ) -- e.g. -rwxr-xr-x Return Pos( "x", perms ) > 0 -- Single-quote a word for /bin/sh. ::Routine Quote Use Strict Arg word Return "'" || ChangeStr( "'", word, "'\''" ) || "'" /******************************************************************************/ /* NativeRun -- Windows: run res~command in the environment res~env of the */ /* ooRexx the RVM runs on, and return its RC. What is fed (res~input, the */ /* exact bytes: given as lines) and what is captured (res~output, */ /* res~error) go through ooRexx's ADDRESS ... WITH; the captured lines are */ /* given back as bytes (res~out, res~err), each line ended by CR LF. MERGE: */ /* the standard error goes to the same Array as the standard output (when */ /* the output is not captured, it is inherited too). */ /******************************************************************************/ ::Routine NativeRun Use Strict Arg res Trace Off eol = "0d0a"x command = res~command inArr = .Nil outArr = .Array~new errArr = .Array~new with = "" If res~input \== .Nil Then Do text = ChangeStr( eol, res~input, "0a"x ) inArr = text~makeArray( "0a"x ) with = with "Input Using (inArr)" End If res~output Then with = with "Output Using (outArr)" Select When res~error == "CAPTURE" Then with = with "Error Using (errArr)" When res~error == "MERGE", res~output Then with = with "Error Using (outArr)" Otherwise Nop End If with \== "" Then with = "With" with Select Case Upper( res~env ) When "COMMAND" Then env = "Command" When "SYSTEM" Then env = "System" When "PATH" Then env = "Path" Otherwise env = "Cmd" -- CMD and "" End -- No condition of the command may show here: the machine raises its own. -- A FAILURE (the command could not be started: for PATH, a program that -- is not there) is noted: the machine then raises FAILURE, with ooRexx's -- RC (not started). Signal Off Error failed = .False Call On Failure Name NativeFailed Interpret "Address" env "command" with Call Off Failure If failed Then res~started = .False If res~output Then res~out = Captured( outArr, eol ) If res~error == "CAPTURE" Then res~err = Captured( errArr, eol ) Return rc NativeFailed: failed = .True Return -- The lines of an Array as bytes, each one ended by 'eol'. ::Routine Captured Use Strict Arg arr, eol If arr~items == 0 Then Return "" Return arr~makeString( "L", eol ) || eol -- The text of the C library's strerror on Windows (MSVCRT, errno 1-42). ::Routine CRuntimeError Use Strict Arg errno texts = "Operation not permitted|No such file or directory|No such process|" ||, "Interrupted function call|Input/output error|No such device or address|" ||, "Arg list too long|Exec format error|Bad file descriptor|No child processes|" ||, "Resource temporarily unavailable|Not enough space|Permission denied|" ||, "Bad address|Unknown error|Resource device|File exists|Improper link|" ||, "No such device|Not a directory|Is a directory|Invalid argument|" ||, "Too many open files in system|Too many open files|" ||, "Inappropriate I/O control operation|Unknown error|File too large|" ||, "No space left on device|Invalid seek|Read-only file system|Too many links|" ||, "Broken pipe|Domain error|Result too large|Unknown error|" ||, "Resource deadlock avoided|Unknown error|Filename too long|" ||, "No locks available|Function not implemented|Directory not empty|" ||, "Illegal byte sequence" Return texts~makeArray( "|" )[ errno ] -- Are we on Windows? (.RexxInfo~platform is "WindowsNT" there: the file -- separator says it without a name to compare.) ::Routine IsWindows Return .File~separator == "\" ::Routine TempFile dir = Value( "TMPDIR", , "ENVIRONMENT" ) If dir == "" Then dir = Value( "TEMP", , "ENVIRONMENT" ) If dir == "" Then dir = "/tmp" Return SysTempFileName( dir"/rvm-?????????" ) ::Routine ReadAll Use Strict Arg file n = Chars( file ) If n == 0 Then data = "" Else data = CharIn( file, 1, n ) Call Stream file, "C", "Close" Return data ::Routine Flush Use Strict Arg stream Signal On Any Name Done stream~flush Done: Return /******************************************************************************/ /* cd */ /* */ /* "cd" alone (or followed only by blanks) goes to $HOME; "~" and "~/path" */ /* are relative to $HOME, "~user[/path]" to that user's home. Double quotes */ /* are removed and a backslash keeps the next character. A failure is an */ /* ERROR with the system error number as RC (2: no such directory, 20: not a */ /* directory, 13: permission denied). When $HOME (or the user) is unknown the */ /* command is left to the shell. */ /******************************************************************************/ ::Routine ChangeDirectory Use Strict Arg command target = Strip( SubStr( command, 3 ), "L", " " ) home = Value( "HOME", , "ENVIRONMENT" ) Select When target == "" Then Do If home == "" Then Return .Nil dir = home End When Left(target, 1) == "~", - ( Length(target) == 1 | Pos( SubStr(target, 2, 1), "/ " ) > 0 ) Then Do If home == "" Then Return .Nil If SubStr(target, 2, 1) == "/" Then dir = home"/"SubStr(target, 3) Else dir = home"/" End When Left(target, 1) == "~" Then Do Parse Var target "~" user "/" rest userHome = HomeOf( user ) If userHome == "" Then Return .Nil If Pos("/", target) == 0 Then dir = userHome"/" Else dir = userHome"/"rest End Otherwise dir = target End dir = Unquote( dir ) res = .Directory~new res~condition = "" res~rc = 0 If dir \== "", Directory( dir ) \== "" Then Return res -- Failed: give the reason as the system error number. res~condition = "ERROR" Select When dir == "" Then res~rc = 2 When SysIsFileDirectory( dir ) Then res~rc = 13 When SysFileExists( dir ) Then res~rc = 20 Otherwise res~rc = 2 End Return res -- Remove double quotes; a backslash keeps the next character (and is removed). ::Routine Unquote Use Strict Arg s out = "" escape = .False Do i = 1 To Length(s) c = SubStr(s, i, 1) Select When escape Then Do; out = out || c; escape = .False; End When c == "\" Then escape = .True When c == '"' Then Nop Otherwise out = out || c End End Return out -- A user's home directory, from the password file ("" if unknown). ::Routine HomeOf Use Strict Arg user file = "/etc/passwd" If \ SysFileExists( file ) Then Return "" home = "" Do While Lines( file ) > 0 Parse Value LineIn( file ) With name ":" . ":" . ":" . ":" . ":" dir ":" . If name == user Then Do home = dir Leave End End Call Stream file, "C", "Close" Return home /******************************************************************************/ /* export / set / unset */ /* */ /* export NAME=value set NAME=value set the environment variable; */ /* $VAR in the value (the name runs up to "/", ":", */ /* "$" or the end) is replaced by that variable's */ /* value (by nothing when it is not set) */ /* unset NAME remove it */ /* */ /* A NAME=value without "=" does nothing (RC 0) unless it contains "|" or ">", */ /* and an "unset" with "=" is left to the shell, as is an "export" or "set" */ /* with nothing after it. */ /******************************************************************************/ ::Routine SetVariable Use Strict Arg command, kind Select When kind == "EXPORT" Then rest = SubStr( command, 7 ) When kind == "UNSET" Then rest = SubStr( command, 6 ) Otherwise rest = SubStr( command, 4 ) End rest = Strip( rest, "L", " " ) If kind \== "UNSET", rest == "" Then Return .Nil res = .Directory~new res~condition = "" res~rc = 0 hasEquals = Pos( "=", rest ) > 0 If \ hasEquals, kind \== "UNSET" Then Do If Pos("|", rest) > 0 | Pos(">", rest) > 0 Then Return .Nil Return res -- nothing to do End If hasEquals, kind == "UNSET" Then Return .Nil If kind == "UNSET" Then Do If rest \== "" Then .RVM.SystemHost~setEnv( rest, .Nil ) Return res End Parse Var rest name "=" value .RVM.SystemHost~setEnv( name, Expand( value ) ) Return res -- Replace each $NAME in a value by the environment variable's value. ::Routine Expand Use Strict Arg value If Pos( "$", value ) == 0 Then Return value out = "" i = 1 n = Length( value ) Do Forever p = Pos( "$", value, i ) If p == 0 Then Leave out = out || SubStr( value, i, p - i ) j = p + 1 Do While j <= n, Pos( SubStr(value, j, 1), "/:$" ) == 0 j = j + 1 End name = SubStr( value, p + 1, j - p - 1 ) If name \== "" Then out = out || Value( name, , "ENVIRONMENT" ) i = j End Return out || SubStr( value, i ) /******************************************************************************/ /* RVM.CommandJob -- a command run in a thread of the host of its own (see */ /* RVM.CommandHost~start): GO returns at once (REPLY) and runs the line; */ /* DONE and RC are read by the RVM's thread while it runs (unguarded), and */ /* the semaphore is posted when it ends. ooRexx gives up its lock while a */ /* command runs, so the RVM runs meanwhile. The host's HALT (Ctrl-C), which */ /* the RVM's thread takes, does not end it before the command ends. */ /******************************************************************************/ ::Class RVM.CommandJob Public ::Attribute done Unguarded ::Attribute rc Unguarded ::Method init Expose done rc done = .False rc = 0 ::Method go Unguarded Expose done rc Use Strict Arg line, sem, res = .Nil Trace Off Reply Signal On Halt Name Halted -- (Ctrl-C: the RVM's thread takes it) -- Windows: in ooRexx's own environment (see RVM.CommandHost's NativeRun). If res \== .Nil Then Do rc = NativeRun( res ) Signal Halted End Address System line Halted: rc = rc done = .True sem~post /******************************************************************************/ /* RVM.StdinReader -- standard input when it is a terminal or a pipe (see */ /* doc/07-concurrency.md, "Blocking operations"). An activity whose read */ /* would block, while something else may run, waits for it: a job */ /* (RVM.StdinJob, a thread of the host of its own) reads a chunk into */ /* 'buffer' (as many times as it takes), and the RVM goes on meanwhile; the */ /* read then runs again, and takes it from there. 'gate' is set by the */ /* machine: the context whose read may wait (see RVM.Stream~inputNeed). */ /* Every read of standard input goes through here: one that cannot wait */ /* waits for a job that reads first, and takes what it read. An end of file */ /* a job saw is given once, as a read gives it. */ /******************************************************************************/ ::Class RVM.StdinReader Public ::Attribute gate Class ::Attribute sem Class -- Is a job reading, or is something read waiting to be taken (or the end -- it saw)? While not, a read is the stream's own (RVM.HostFile~readAt). ::Attribute busy Class Get ::Method activate Class Expose buffer at eof job gate sem transient busy buffer = ""; at = 1; eof = .False; job = .Nil; gate = .Nil; transient = .Nil busy = .False sem = .EventSemaphore~new -- Is standard input a terminal or a pipe? ::Method transient Class Expose transient If transient == .Nil Then transient = .Input~query( "STREAMTYPE" ) \== "PERSISTENT" Return transient -- Is what a read needs there (kind LINE: a line; CHARS: 'count' bytes; ALL: -- everything), or the end? Or something waiting to be read (ooRexx's -- FIONREAD: see SysFile's hasData), which the read takes now without -- waiting for it. ('buffer' from 'at' on is what has not been taken yet.) ::Method has Class Expose buffer at eof job Use Strict Arg kind, count self~collect If eof Then Return .True Select Case kind When "LINE" Then If Pos( "0a"x, buffer, at ) > 0 Then Return .True When "CHARS" Then If Length( buffer ) - at + 1 >= count Then Return .True Otherwise Nop End If job \== .Nil Then Return .False Return .Input~chars > 0 -- A job reads a chunk (unless one is reading, or the end has come). ::Method fetch Class Expose job eof sem self~collect If job \== .Nil | eof Then Return job = .RVM.StdinJob~new job~go( sem ) self~settle -- Is a job reading? ::Method reading Class Expose job self~collect Return job \== .Nil -- What the job read, once it has ended: .True when it had. ::Method collect Class Expose eof job If job == .Nil Then Return .False If \ job~done Then Return .False self~append( job~data ) If job~eof Then eof = .True job = .Nil self~settle Return .True ::Method settle Class Private Expose buffer at eof job busy busy = job \== .Nil | eof | Length( buffer ) >= at ::Method append Class Private Expose buffer at Use Strict Arg data If at > 1 Then Do buffer = SubStr( buffer, at ) at = 1 End buffer = buffer || data -- Up to 'length' bytes (as the stream's charIn): what was read ahead first. ::Method read Class Expose buffer at eof job sem Use Strict Arg length If job \== .Nil Then Do -- (a read that cannot wait) Do While \ job~done sem~wait( 0.1 ) End self~collect End left = Length( buffer ) - at + 1 If left <= 0 Then Do If eof Then Do eof = .False self~settle Return "" End Return .Input~charIn( , length ) End k = Min( length, left ) data = SubStr( buffer, at, k ) at = at + k If at > Length( buffer ) Then Do buffer = "" at = 1 End self~settle If k < length, \ eof Then data = data || .Input~charIn( , length - k ) Return data -- Is there something to read right now? (Not while a job reads.) ::Method hasData Class Expose buffer at eof job self~collect If Length( buffer ) >= at Then Return .True If eof | job \== .Nil Then Return .False Return .Input~chars > 0 -- The program has ended: a job still reading is stopped (its reader -- killed), so that the host can end, and it is waited for (a second at -- most), so that it removes its files. ::Method stop Class Expose job If job == .Nil Then Return If job~done Then Return job~kill Do 100 While \ job~done Call SysSleep 0.01 End /******************************************************************************/ /* RVM.StdinJob -- a read of standard input in a thread of the host of its */ /* own (see RVM.StdinReader): GO returns at once (REPLY) and runs a command */ /* (dd) that reads a chunk (one read of the system, at most 4096 bytes, as */ /* ooRexx's SysFile reads), with standard input inherited, into a file. A */ /* command can be killed: Ctrl-C kills it too (the terminal's process */ /* group), and then nothing has been read (but it is not the end). DONE, */ /* DATA and EOF are read by the RVM's thread (unguarded), and the semaphore */ /* is posted when it ends. */ /******************************************************************************/ ::Class RVM.StdinJob ::Attribute done Unguarded ::Attribute data Unguarded ::Attribute eof Unguarded ::Method init Expose done data eof pidFile done = .False; data = ""; eof = .False pidFile = TempFile() ::Method go Unguarded Expose done data eof pidFile Use Strict Arg sem Trace Off Reply Signal On Halt Name Halted -- (Ctrl-C: the RVM's thread takes it) out = TempFile() Address System 'echo $$ > "'pidFile'"; exec dd bs=4096 count=1 2>/dev/null > "'out'"' ok = ( rc == 0 ) Finish: Signal Off Halt If Stream( out, "C", "QUERY EXISTS" ) \== "" Then Do data = CharIn( out, 1, Chars( out ) ) Call Stream out, "C", "CLOSE" Call SysFileDelete out End Call SysFileDelete pidFile If ok, data == "" Then eof = .True done = .True sem~post Return Halted: ok = .False Signal Finish -- Kill the reader (see RVM.StdinReader~stop). ::Method kill Unguarded Expose pidFile Do 50 While Stream( pidFile, "C", "QUERY SIZE" ) == 0 -- (it may be starting) Call SysSleep 0.01 End pid = Strip( LineIn( pidFile ) ) Call Stream pidFile, "C", "CLOSE" If pid~dataType( "W" ) Then Address System "kill" pid "2>/dev/null" /******************************************************************************/ /* */ /* Files */ /* */ /* RVM.HostFile is the only thing the stream functions ask of the */ /* platform: a file as a numbered sequence of bytes that can be opened, read */ /* and written at a given (0-based) offset, measured, flushed and closed. */ /* Everything else -- read and write positions, lines, line ends, end of */ /* file, the stream states and the NOTREADY condition -- is done by */ /* RVM.Stream on top of it. */ /* */ /* A failed operation answers .False (or .Nil) and leaves the system error */ /* number in 'errno' and its text in 'errtext'. */ /* */ /* The standard streams are HostFiles too (see HostFile~standard). Each is */ /* transient or persistent as the system says (ooRexx's getStreamTypeInfo: a */ /* terminal, a character device or a pipe is transient; a file redirected to */ /* one is persistent, with a size and positions). A persistent one shares its */ /* offset with the commands the program runs: 'tell' and 'seek' are that */ /* offset, which the stream reads before writing (ooRexx's getPosition). */ /* */ /******************************************************************************/ ::Class RVM.FileSystem Public -- The name a file is known by: absolute, with "~", "." and ".." resolved, -- whether the file exists or not; "" when the name cannot be qualified. ::Method qualify Class Use Strict Arg name If name == "" Then Return "" Return .Stream~new( name )~qualify -- Is there a regular file (not a directory) with this qualified name? ::Method isFile Class Use Strict Arg qname Return .File~new( qname )~isFile -- Is the system Windows? ::Method windows Class Return IsWindows() -- Do two spellings of a name that differ only in case name the same file? ::Method caseless Class Return IsWindows() -- Is hostemu Windows's (its way of opening files, and Microsoft's C library: -- text mode, its FILE's states, atoi)? On Windows, or anywhere with -- RVM_WINDOWS_HOSTEMU=1 (to test it). ::Method hostEmuWindows Class If IsWindows() Then Return .True Return Value( "RVM_WINDOWS_HOSTEMU", , "ENVIRONMENT" ) == "1" -- The characters that separate the directories of a path. ::Method pathSeparators Class If IsWindows() Then Return "\/" Return "/" -- Does a file specification start with a drive ("C:")? ::Method hasDrives Class Return IsWindows() -- The line-end sequence written after each line. ::Method lineEnd Class If IsWindows() Then Return "0d0a"x Return "0a"x -- The text of a system error number ("" for 0). ::Method errorText Class Use Strict Arg errno If errno = 0 Then Return "" -- Windows: ooRexx's streams say what the C library's strerror says (in -- English), not SysGetErrortext (the system's message, in the user's -- language): the C library's texts, for its numbers. If IsWindows(), errno > 0, errno <= 42 Then Return CRuntimeError( errno ) Return SysGetErrortext( errno ) -- The size of whatever has this qualified name: a file's size, 0 for -- anything else (a directory); "" when there is nothing. ::Method size Class Use Strict Arg qname f = .File~new( qname ) If \ f~exists Then Return "" If f~isFile Then Return f~length Return 0 -- The modification time of a file, as "yyyy-mm-dd hh:mm:ss" (local time), -- or "" when there is no such file. ::Method timeStamp Class Use Strict Arg qname f = .File~new( qname ) If \ f~exists Then Return "" Return f~lastModified~string~left( 19 )~translate( " ", "T" ) ::Class RVM.HostFile Public -- The lines SAY has written to standard output straight (ooRexx's SAY is a -- LINEOUT of the STDOUT stream: the stream counts them as its own lines). ::Attribute said Class ::Method init Class Expose said said = 0 ::Attribute name Get ::Attribute errno Get ::Attribute errtext Get ::Attribute transient Get -- a device or a pipe: no positions, no size ::Attribute device Get ::Attribute isOpen Get ::Method init Expose name stream errno errtext transient device isOpen standard Use Strict Arg name stream = .Nil errno = 0 errtext = "" transient = .False device = .False isOpen = .False standard = "" -- A HostFile for STDIN, STDOUT or STDERR, already open. ::Method standard Class Use Strict Arg which f = self~new( which ) f~!standard( which ) Return f ::Method !standard Expose stream transient device isOpen standard Use Strict Arg standard Select Case standard When "STDIN" Then stream = .Input When "STDOUT" Then stream = .Output Otherwise stream = .Error End transient = stream~query( "STREAMTYPE" ) \== "PERSISTENT" device = transient isOpen = .True -- The offset of a persistent standard output or error stream (0-based), -- where the next write goes: commands write there too. ::Method tell Expose stream Return stream~command( "SEEK +0 WRITE CHAR" ) - 1 -- Where the last write to it ended, 1-based (1 before any): SAY writes -- there too. ::Method writePosition Expose stream Return stream~query( "POSITION WRITE CHAR" ) -- The lines SAY has written straight to this stream (standard output) so -- far (see said). ::Method saidLines Expose standard If standard == "STDOUT" Then Return self~class~said Return 0 -- Move it (a positioned CHAROUT or LINEOUT, or SEEK). ::Method seek Expose stream Use Strict Arg offset stream~command( "SEEK" offset + 1 "WRITE CHAR" ) -- The handle of the system (QUERY HANDLE; ooRexx's SysFile::getHandle): the -- descriptor of the file, as the host's stream has it; 0, 1, 2 for the -- standard streams; "" when it is not open. ::Method handle Expose stream isOpen standard If \ isOpen Then Return "" Select Case standard When "STDIN" Then Return 0 When "STDOUT" Then Return 1 When "STDERR" Then Return 2 Otherwise Return stream~query( "HANDLE" ) End -- open(access, create, truncate): access is "READ", "READWRITE" or "WRITE". -- A file that does not exist is created only when 'create' is true (never -- for READ); 'truncate' empties it. ::Method open Expose name stream errno errtext transient device isOpen Use Strict Arg access, create, truncate errno = 0 errtext = "" If access \== "READ", \ create, \ .File~new( name )~exists Then Return self~!fail( 2 ) Select Case access When "READ" Then options = "READ" When "READWRITE" Then options = "BOTH" Otherwise options = "WRITE" End If truncate Then options = options "REPLACE" s = .Stream~new( name ) If s~open( options ) \== "READY:" Then Do Parse Value s~description With "ERROR:" n . If \ n~dataType( "W" ) Then n = 2 Return self~!fail( n ) End stream = s transient = s~query( "STREAMTYPE" ) == "TRANSIENT" device = transient isOpen = .True Return .True ::Method !fail Private Expose errno errtext Use Strict Arg errno errtext = .RVM.FileSystem~errorText( errno ) Return .False ::Method close Expose stream isOpen standard If \ isOpen Then Return .True isOpen = .False If standard \== "" Then Return .True stream~close stream = .Nil Return .True -- Write what the host's stream still holds: .False when it cannot (ooRexx -- keeps it, and a later FLUSH tries again). ::Method flush Expose stream standard If standard \== "" Then Return .True r = stream~command( "FLUSH" ) If r~left( 6 ) == "ERROR:" Then Return self~!fail( r~substr( 7 ) ) Return .True -- The size in bytes (0 for a transient stream). ::Method size Expose stream transient If transient Then Return 0 Return stream~query( "SIZE" ) -- Is there something to read right now? (A transient stream: data waiting; -- a file: always, the caller knows its size.) ::Method hasData Expose stream standard transient If \ transient Then Return .True If standard == "STDIN" Then Do If \ .RVM.StdinReader~busy Then Return stream~chars > 0 Return .RVM.StdinReader~hasData End If standard == "" Then Return stream~chars > 0 Return .False -- Up to 'length' bytes starting at 'offset' ("" at or past the end), or .Nil -- when the file cannot be read. ::Method readAt Expose stream transient standard Use Strict Arg offset, length If length == 0 Then Return "" If transient Then Do If standard == "STDIN" Then Do If \ .RVM.StdinReader~busy Then Return stream~charIn( , length ) Return .RVM.StdinReader~read( length ) End If standard == "" Then Return stream~charIn( , length ) Return self~!failNil( 9 ) -- EBADF: an output stream End size = stream~query( "SIZE" ) If offset >= size Then Return "" data = stream~charIn( offset + 1, Min( length, size - offset ) ) If data == "" Then Return self~!failNil( self~!errnoOf( stream ) ) Return data -- Write 'data' at 'offset' (a transient stream just appends): .True, or -- .False when it could not be written. ::Method writeAt Expose stream transient standard Use Strict Arg offset, data If data == "" Then Return .True If standard == "STDIN" Then Return self~!fail( 9 ) If transient Then left = stream~charOut( data ) Else left = stream~charOut( data, offset + 1 ) If left \= 0 Then Return self~!fail( self~!errnoOf( stream ) ) Return .True ::Method !failNil Private Use Strict Arg n self~!fail( n ) Return .Nil ::Method !errnoOf Private Use Strict Arg s Parse Value s~description With ":" n . If \ n~dataType( "W" ) Then n = 5 -- EIO Return n /******************************************************************************/ /* */ /* The process: environment variables, current directory, user, speaker, */ /* memory. Every change the interpreter makes to an environment variable */ /* goes through setEnv, so that SETLOCAL / ENDLOCAL can undo it. */ /* */ /* SETLOCAL takes a snapshot: the current directory, and (a journal) the old */ /* value of each environment variable changed while the snapshot is active. */ /* ENDLOCAL goes back to the latest snapshot: the directory, and every */ /* variable that EXISTED when it was taken gets its old value back; variables */ /* created since then are left alone. When the program ends, the oldest */ /* snapshot still active is restored. */ /* */ /******************************************************************************/ ::Class RVM.SystemHost Public ::Constant ABSENT "00FF00"x -- journal mark: did not exist ::Method activate Class Expose snapshots sharedFile sharedText macrosFile macrosText snapshots = .Array~new sharedFile = .Nil sharedText = "" macrosFile = .Nil macrosText = "" -- The name of the system, as PARSE SOURCE gives it. ::Method systemName Class Parse Source system . Return system ::Method getEnv Class Use Strict Arg name Return Value( name, , "ENVIRONMENT" ) -- Set (or, with .Nil, remove) an environment variable. ::Method setEnv Class Expose snapshots Use Strict Arg name, value If snapshots~items > 0 Then Do old = Value( name, , "ENVIRONMENT" ) If old == "", \ self~envExists( name ) Then old = self~ABSENT Do snap Over snapshots If \ snap~saved~hasIndex( name ) Then snap~saved[ name ] = old End End Return Value( name, value, "ENVIRONMENT" ) -- Does an environment variable exist? (Asked only for a null value, which -- VALUE cannot tell from no variable: a child process can.) ::Method envExists Class Use Strict Arg name If Value( name, , "ENVIRONMENT" ) \== "" Then Return .True If IsWindows() Then Return .False -- A name the shell can expand: its own test (a builtin, so that an empty -- PATH does not hide it); any other, printenv. shellName = Verify( name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_" ) == 0 If shellName, name \== "" Then shellName = Verify( Left( name, 1 ), "0123456789" ) > 0 If shellName, name \== "" Then Address System '[ -n "${'name'+x}" ]' Else Address System "printenv '"ChangeStr( "'", name, "'\''" )"' >/dev/null 2>&1" Return rc == 0 ::Method currentDirectory Class Return Directory() -- Make 'dir' the current directory: .True, or .False when it cannot be. ::Method changeDirectory Class Use Strict Arg dir Return Directory( dir ) \== "" ::Method userid Class Return Userid() ::Method beep Class Use Strict Arg frequency, duration Call Beep frequency, duration -- Collect garbage when forced: .True when it ran. ::Method gc Class Use Strict Arg force If \ force Then Return .False Return GC( "F" ) -- Can environments be saved and restored (SETLOCAL / ENDLOCAL)? ::Method hasLocalEnvironments Class Return \ IsWindows() ::Method pushLocal Class Expose snapshots snap = .Directory~new snap~directory = Directory() snap~saved = .StringTable~new snapshots~append( snap ) -- Back to the latest snapshot: .False when there is none. ::Method popLocal Class Expose snapshots If snapshots~items == 0 Then Return .False snap = snapshots~lastItem snapshots~delete( snapshots~last ) self~restore( snap ) Return .True -- In an RVM that a command started (RVM_QUEUES: see RVM.CommandHost~run), -- the queues of the RVM that started it; endProgram writes them back if -- they changed. ::Method shareQueues Class Expose sharedFile sharedText macrosFile macrosText -- The macrospace too (RVM_MACROSPACE), in the same way. macrosFile = .Nil file = Value( "RVM_MACROSPACE", , "ENVIRONMENT" ) store = .RVM.CommandHost~macros If file \== "", store \== .Nil Then If SysIsFile( file ) Then Do text = ReadAll( file ) If store~restore( text ) Then Do macrosFile = file macrosText = text End End file = Value( "RVM_QUEUES", , "ENVIRONMENT" ) If file == "" Then Return queues = .RVM.CommandHost~queues If queues == .Nil Then Return If \ SysIsFile( file ) Then Return text = ReadAll( file ) If \ queues~restore( text ) Then Return sharedFile = file sharedText = text -- At the end of the program: the shared queues and macrospace are written -- back when they changed, and then back to the oldest snapshot, if any. ::Method endProgram Class Expose snapshots sharedFile sharedText macrosFile macrosText .RVM.StdinReader~stop -- (a read for an activity that waited) If sharedFile \== .Nil Then Do now = .RVM.CommandHost~queues~snapshot If now \== sharedText Then Do Call Stream sharedFile, "C", "Open Write Replace" Call CharOut sharedFile, now Call Stream sharedFile, "C", "Close" End sharedFile = .Nil End If macrosFile \== .Nil Then Do now = .RVM.CommandHost~macros~snapshot If now \== macrosText Then Do Call Stream macrosFile, "C", "Open Write Replace" Call CharOut macrosFile, now Call Stream macrosFile, "C", "Close" End macrosFile = .Nil End If snapshots~items == 0 Then Return snap = snapshots[ 1 ] snapshots = .Array~new self~restore( snap ) ::Method restore Class Private Expose snapshots Use Strict Arg snap If Directory( snap~directory ) == "" Then Raise Syntax 48.1 Array( "Error restoring current directory:" snap~directory ) Do name Over snap~saved~allIndexes old = snap~saved[ name ] If old == self~ABSENT Then Iterate self~setEnv( name, old ) End