-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathIPCOpen3.java
More file actions
445 lines (385 loc) · 16.2 KB
/
IPCOpen3.java
File metadata and controls
445 lines (385 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.io.ProcessInputHandle;
import org.perlonjava.runtime.io.ProcessOutputHandle;
import org.perlonjava.runtime.nativ.NativeUtils;
import org.perlonjava.runtime.operators.WaitpidOperator;
import org.perlonjava.runtime.runtimetypes.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.perlonjava.runtime.runtimetypes.GlobalVariable.getGlobalVariable;
/**
* IPC::Open3 - open a process for reading, writing, and error handling
* <p>
* This class provides the XS portion of IPC::Open3 using Java's ProcessBuilder
* instead of fork(), which is not available on the JVM.
* <p>
* Loaded via XSLoader from Open3.pm
*/
public class IPCOpen3 extends PerlModuleBase {
private static final boolean IS_WINDOWS = NativeUtils.IS_WINDOWS;
/**
* Constructor for IPCOpen3.
*/
public IPCOpen3() {
super("IPC::Open3");
}
/**
* Static initializer called by XSLoader::load().
*/
public static void initialize() {
IPCOpen3 module = new IPCOpen3();
try {
// Register _open3 and _open2 as the XS implementations
module.registerMethod("_open3", null);
module.registerMethod("_open2", null);
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing IPC::Open3 method: " + e.getMessage());
}
}
/**
* Copies the Perl %ENV hash to the ProcessBuilder environment.
*/
private static void copyPerlEnvToProcessBuilder(ProcessBuilder processBuilder) {
Map<String, String> env = processBuilder.environment();
RuntimeHash perlEnv = GlobalVariable.getGlobalHash("main::ENV");
for (Map.Entry<String, RuntimeScalar> entry : perlEnv.elements.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
env.put(key, value);
}
}
/**
* Register child process for waitpid() - handles both Windows and POSIX.
*/
private static void registerChildProcess(Process process) {
long pid = process.pid();
if (IS_WINDOWS) {
WaitpidOperator.registerChildProcess(pid, process);
} else {
RuntimeIO.registerChildProcess(process);
}
}
/**
* XS implementation of open3.
* <p>
* Arguments: ($wtr, $rdr, $err, @cmd)
* - $wtr: handle for writing to child's stdin (output parameter)
* - $rdr: handle for reading from child's stdout (output parameter)
* - $err: handle for reading from child's stderr (output parameter, can be undef)
* - @cmd: command and arguments to execute
* <p>
* Returns: PID of the child process
*/
public static RuntimeList _open3(RuntimeArray args, int ctx) {
if (args.size() < 4) {
throw new RuntimeException("Not enough arguments for open3");
}
// Extract handles (these are references we need to modify)
RuntimeScalar wtrRef = args.get(0);
RuntimeScalar rdrRef = args.get(1);
RuntimeScalar errRef = args.get(2);
// Extract command - remaining arguments
List<String> commandList = new ArrayList<>();
for (int i = 3; i < args.size(); i++) {
commandList.add(args.get(i).toString());
}
if (commandList.isEmpty()) {
throw new RuntimeException("open3: no command specified");
}
try {
// Build the command
String[] command;
if (commandList.size() == 1) {
// Single string - use shell
String cmd = commandList.get(0);
if (IS_WINDOWS) {
command = new String[]{"cmd.exe", "/c", cmd};
} else {
command = new String[]{"/bin/sh", "-c", cmd};
}
} else {
// Multiple arguments - direct execution
command = commandList.toArray(new String[0]);
}
ProcessBuilder processBuilder = new ProcessBuilder(command);
String userDir = System.getProperty("user.dir");
processBuilder.directory(new File(userDir));
// Copy %ENV to the subprocess
copyPerlEnvToProcessBuilder(processBuilder);
// Check if stderr should be merged with stdout
// errRef is "usable" if it's defined AND (if it's a reference) the inner value is also defined
boolean errIsUsable = isUsableHandle(errRef);
boolean mergeStderr = !errIsUsable ||
(rdrRef.type == RuntimeScalarType.REFERENCE &&
errRef.type == RuntimeScalarType.REFERENCE &&
rdrRef.value == errRef.value);
if (mergeStderr) {
processBuilder.redirectErrorStream(true);
}
// Start the process
Process process = processBuilder.start();
long pid = process.pid();
// Register the process for waitpid() - works on both Windows and POSIX
registerChildProcess(process);
// Set up the write handle (to child's stdin)
// Check for redirection directive like "<&STDIN"
if (isInputRedirection(wtrRef)) {
// Input redirection - just close the process stdin
process.getOutputStream().close();
} else {
setupWriteHandle(wtrRef, process.getOutputStream());
}
// Set up the read handle (from child's stdout)
// Check for redirection directive like ">&STDERR"
boolean rdrIsRedirection = isOutputRedirection(rdrRef);
if (rdrIsRedirection) {
// Output redirection - pipe stdout to the named handle
handleOutputRedirection(rdrRef, process.getInputStream());
} else {
setupReadHandle(rdrRef, process.getInputStream(), process);
}
// Set up the error handle (from child's stderr) if not merged
if (!mergeStderr && errIsUsable) {
if (isOutputRedirection(errRef)) {
handleOutputRedirection(errRef, process.getErrorStream());
} else {
setupReadHandle(errRef, process.getErrorStream(), process);
}
}
return new RuntimeScalar(pid).getList();
} catch (Exception e) {
getGlobalVariable("main::!").set(e.getMessage());
throw new RuntimeException("open3: " + e.getMessage());
}
}
/**
* Check if the handle is an output redirection directive like ">&STDERR"
*/
private static boolean isOutputRedirection(RuntimeScalar handleRef) {
// Get the actual string value (may need to dereference)
String str = getStringValue(handleRef);
return str != null && str.startsWith(">&");
}
/**
* Check if the handle is an input redirection directive like "<&STDIN"
*/
private static boolean isInputRedirection(RuntimeScalar handleRef) {
// Get the actual string value (may need to dereference)
String str = getStringValue(handleRef);
return str != null && str.startsWith("<&");
}
/**
* Check if a handle parameter is usable (not false or a reference to a false value).
* Per IPC::Open3 docs: "If CHLD_ERR is false, or the same file descriptor as
* CHLD_OUT, then STDOUT and STDERR of the child are on the same filehandle."
* A false value includes undef, "", and 0.
*/
private static boolean isUsableHandle(RuntimeScalar handleRef) {
if (!handleRef.getDefinedBoolean()) {
return false;
}
// If it's a reference, check if the inner value is true (not just defined)
if (handleRef.type == RuntimeScalarType.REFERENCE && handleRef.value instanceof RuntimeScalar) {
RuntimeScalar inner = (RuntimeScalar) handleRef.value;
return inner.getBoolean();
}
return true;
}
/**
* Get the string value from a scalar, dereferencing if needed
*/
private static String getStringValue(RuntimeScalar scalar) {
if (scalar == null) return null;
// If it's a reference, dereference it
if (scalar.type == RuntimeScalarType.REFERENCE) {
if (scalar.value instanceof RuntimeScalar) {
RuntimeScalar inner = (RuntimeScalar) scalar.value;
// Check if the inner value is a string
if (inner.type == RuntimeScalarType.STRING) {
return inner.toString();
}
// Also try getting the string directly
return inner.toString();
}
}
// Direct string type
if (scalar.type == RuntimeScalarType.STRING) {
return scalar.toString();
}
// Try toString and check if it looks like a redirect
String str = scalar.toString();
if (str.startsWith(">&") || str.startsWith("<&")) {
return str;
}
return null;
}
/**
* Handle output redirection like ">&STDERR" - pipe input stream to the named handle
*/
private static void handleOutputRedirection(RuntimeScalar handleRef, InputStream in) {
String directive = handleRef.toString();
String handleName = directive.substring(2); // Remove ">&"
// Get the named handle
RuntimeIO targetIO = null;
if (handleName.equals("STDERR")) {
targetIO = getGlobalVariable("main::STDERR").getRuntimeIO();
} else if (handleName.equals("STDOUT")) {
targetIO = getGlobalVariable("main::STDOUT").getRuntimeIO();
}
if (targetIO != null && targetIO.ioHandle != null) {
final RuntimeIO finalTargetIO = targetIO;
// Start a thread to copy data from process to target handle
Thread copier = new Thread(() -> {
try {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
String str = new String(buffer, 0, bytesRead);
finalTargetIO.ioHandle.write(str);
finalTargetIO.ioHandle.flush();
}
} catch (Exception e) {
// Ignore - process may have terminated
}
});
copier.setDaemon(true);
copier.start();
} else {
// Fallback: just discard the stream
Thread discarder = new Thread(() -> {
try {
byte[] buffer = new byte[4096];
while (in.read(buffer) != -1) {
// discard
}
} catch (Exception e) {
// Ignore
}
});
discarder.setDaemon(true);
discarder.start();
}
}
/**
* XS implementation of open2.
* <p>
* Arguments: ($rdr, $wtr, @cmd)
* - $rdr: handle for reading from child's stdout (output parameter)
* - $wtr: handle for writing to child's stdin (output parameter)
* - @cmd: command and arguments to execute
* <p>
* Returns: PID of the child process
* <p>
* Note: stderr goes to parent's stderr (inherited)
*/
public static RuntimeList _open2(RuntimeArray args, int ctx) {
if (args.size() < 3) {
throw new RuntimeException("Not enough arguments for open2");
}
// Extract handles (these are references we need to modify)
RuntimeScalar rdrRef = args.get(0);
RuntimeScalar wtrRef = args.get(1);
// Extract command - remaining arguments
List<String> commandList = new ArrayList<>();
for (int i = 2; i < args.size(); i++) {
commandList.add(args.get(i).toString());
}
if (commandList.isEmpty()) {
throw new RuntimeException("open2: no command specified");
}
try {
// Build the command
String[] command;
if (commandList.size() == 1) {
// Single string - use shell
String cmd = commandList.get(0);
if (IS_WINDOWS) {
command = new String[]{"cmd.exe", "/c", cmd};
} else {
command = new String[]{"/bin/sh", "-c", cmd};
}
} else {
// Multiple arguments - direct execution
command = commandList.toArray(new String[0]);
}
ProcessBuilder processBuilder = new ProcessBuilder(command);
String userDir = System.getProperty("user.dir");
processBuilder.directory(new File(userDir));
// Copy %ENV to the subprocess
copyPerlEnvToProcessBuilder(processBuilder);
// Inherit stderr (goes to parent's stderr)
processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
// Start the process
Process process = processBuilder.start();
long pid = process.pid();
// Register the process for waitpid() - works on both Windows and POSIX
registerChildProcess(process);
// Set up the write handle (to child's stdin)
setupWriteHandle(wtrRef, process.getOutputStream());
// Set up the read handle (from child's stdout)
setupReadHandle(rdrRef, process.getInputStream(), process);
return new RuntimeScalar(pid).getList();
} catch (Exception e) {
getGlobalVariable("main::!").set(e.getMessage());
throw new RuntimeException("open2: " + e.getMessage());
}
}
/**
* Sets up a write handle from an OutputStream.
*/
private static void setupWriteHandle(RuntimeScalar handleRef, OutputStream out) {
RuntimeIO io = new RuntimeIO();
io.ioHandle = new ProcessOutputHandle(out);
// Dereference to get the inner value
RuntimeScalar inner;
if (handleRef.type == RuntimeScalarType.REFERENCE && handleRef.value instanceof RuntimeScalar) {
inner = (RuntimeScalar) handleRef.value;
} else {
inner = handleRef;
}
// If the inner value is already a GLOBREFERENCE (e.g., \*FOO typeglob),
// set the IO slot on the existing glob so the bareword handle works
if (inner.type == RuntimeScalarType.GLOBREFERENCE && inner.value instanceof RuntimeGlob) {
((RuntimeGlob) inner.value).setIO(io);
} else {
// Create a new GLOB reference for the handle
RuntimeGlob glob = new RuntimeGlob(null);
glob.setIO(io);
RuntimeScalar newHandle = new RuntimeScalar();
newHandle.type = RuntimeScalarType.GLOBREFERENCE;
newHandle.value = glob;
inner.set(newHandle);
}
}
/**
* Sets up a read handle from an InputStream.
*/
private static void setupReadHandle(RuntimeScalar handleRef, InputStream in, Process process) {
RuntimeIO io = new RuntimeIO();
io.ioHandle = new ProcessInputHandle(in, process);
// Dereference to get the inner value
RuntimeScalar inner;
if (handleRef.type == RuntimeScalarType.REFERENCE && handleRef.value instanceof RuntimeScalar) {
inner = (RuntimeScalar) handleRef.value;
} else {
inner = handleRef;
}
// If the inner value is already a GLOBREFERENCE (e.g., \*FOO typeglob),
// set the IO slot on the existing glob so the bareword handle works
if (inner.type == RuntimeScalarType.GLOBREFERENCE && inner.value instanceof RuntimeGlob) {
((RuntimeGlob) inner.value).setIO(io);
} else {
// Create a new GLOB reference for the handle
RuntimeGlob glob = new RuntimeGlob(null);
glob.setIO(io);
RuntimeScalar newHandle = new RuntimeScalar();
newHandle.type = RuntimeScalarType.GLOBREFERENCE;
newHandle.value = glob;
inner.set(newHandle);
}
}
}