/
ShellLauncher.java
1638 lines (1453 loc) · 63.7 KB
/
ShellLauncher.java
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***** BEGIN LICENSE BLOCK *****
* Version: EPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2007-2011 JRuby Team <team@jruby.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.util;
import static java.lang.System.out;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jruby.Main;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyInstanceConfig;
import org.jruby.RubyModule;
import org.jruby.RubyString;
import jnr.posix.util.FieldAccess;
import jnr.posix.util.Platform;
import org.jruby.runtime.Helpers;
import org.jruby.ext.rbconfig.RbConfigLibrary;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.util.cli.Options;
import org.jruby.util.io.IOOptions;
import org.jruby.util.io.ModeFlags;
/**
* This mess of a class is what happens when all Java gives you is
* Runtime.getRuntime().exec(). Thanks dude, that really helped.
* @author nicksieger
*/
@SuppressWarnings("deprecation")
public class ShellLauncher {
private static final boolean DEBUG = false;
private static final String PATH_ENV = "PATH";
// from MRI -- note the unixy file separators
private static final String[] DEFAULT_PATH =
{ "/usr/local/bin", "/usr/ucb", "/usr/bin", "/bin" };
private static final String[] WINDOWS_EXE_SUFFIXES =
{ ".exe", ".com", ".bat", ".cmd" }; // the order is important
private static final String[] WINDOWS_INTERNAL_CMDS = {
"assoc", "break", "call", "cd", "chcp",
"chdir", "cls", "color", "copy", "ctty", "date", "del", "dir", "echo", "endlocal",
"erase", "exit", "for", "ftype", "goto", "if", "lfnfor", "lh", "lock", "md", "mkdir",
"move", "path", "pause", "popd", "prompt", "pushd", "rd", "rem", "ren", "rename",
"rmdir", "set", "setlocal", "shift", "start", "time", "title", "truename", "type",
"unlock", "ver", "verify", "vol", };
// TODO: better check is needed, with quoting/escaping
private static final Pattern SHELL_METACHARACTER_PATTERN =
Pattern.compile("[*?{}\\[\\]<>()~&|$;'`\\\\\"\\n]");
private static final Pattern WIN_ENVVAR_PATTERN = Pattern.compile("%\\w+%");
private static class ScriptThreadProcess extends Process implements Runnable {
private final String[] argArray;
private final String[] env;
private final File pwd;
private final boolean pipedStreams;
private final PipedInputStream processOutput;
private final PipedInputStream processError;
private final PipedOutputStream processInput;
private RubyInstanceConfig config;
private Thread processThread;
private int result;
private Ruby parentRuntime;
public ScriptThreadProcess(Ruby parentRuntime, final String[] argArray, final String[] env, final File dir) {
this(parentRuntime, argArray, env, dir, true);
}
public ScriptThreadProcess(Ruby parentRuntime, final String[] argArray, final String[] env, final File dir, final boolean pipedStreams) {
this.parentRuntime = parentRuntime;
this.argArray = argArray;
this.env = env;
this.pwd = dir;
this.pipedStreams = pipedStreams;
if (pipedStreams) {
processOutput = new PipedInputStream();
processError = new PipedInputStream();
processInput = new PipedOutputStream();
} else {
processOutput = processError = null;
processInput = null;
}
}
public void run() {
try {
this.result = (new Main(config).run(argArray)).getStatus();
} catch (Throwable throwable) {
throwable.printStackTrace(this.config.getError());
this.result = -1;
} finally {
this.config.getOutput().close();
this.config.getError().close();
try {this.config.getInput().close();} catch (IOException ioe) {}
}
}
private Map<String, String> environmentMap(String[] env) {
Map<String, String> m = new HashMap<String, String>();
for (int i = 0; i < env.length; i++) {
String[] kv = env[i].split("=", 2);
m.put(kv[0], kv[1]);
}
return m;
}
public void start() throws IOException {
config = new RubyInstanceConfig(parentRuntime.getInstanceConfig());
config.setEnvironment(environmentMap(env));
config.setCurrentDirectory(pwd.toString());
if (pipedStreams) {
config.setInput(new PipedInputStream(processInput));
config.setOutput(new PrintStream(new PipedOutputStream(processOutput)));
config.setError(new PrintStream(new PipedOutputStream(processError)));
}
String procName = "piped";
if (argArray.length > 0) {
procName = argArray[0];
}
processThread = new Thread(this, "ScriptThreadProcess: " + procName);
processThread.setDaemon(true);
processThread.start();
}
public OutputStream getOutputStream() {
return processInput;
}
public InputStream getInputStream() {
return processOutput;
}
public InputStream getErrorStream() {
return processError;
}
public int waitFor() throws InterruptedException {
processThread.join();
return result;
}
public int exitValue() {
return result;
}
public void destroy() {
if (pipedStreams) {
closeStreams();
}
processThread.interrupt();
}
private void closeStreams() {
try { processInput.close(); } catch (IOException io) {}
try { processOutput.close(); } catch (IOException io) {}
try { processError.close(); } catch (IOException io) {}
}
}
public static String[] getCurrentEnv(Ruby runtime) {
return getCurrentEnv(runtime, null);
}
private static String[] getCurrentEnv(Ruby runtime, Map mergeEnv) {
ThreadContext context = runtime.getCurrentContext();
// disable tracing for the dup call below
boolean traceEnabled = context.isEventHooksEnabled();
context.setEventHooksEnabled(false);
try {
// dup for JRUBY-6603 (avoid concurrent modification while we walk it)
RubyHash hash = (RubyHash)runtime.getObject().getConstant("ENV").dup();
String[] ret, ary;
if (mergeEnv != null && !mergeEnv.isEmpty()) {
ret = new String[hash.size() + mergeEnv.size()];
} else {
ret = new String[hash.size()];
}
int i=0;
for(Map.Entry e : (Set<Map.Entry>)hash.directEntrySet()) {
// if the key is nil, raise TypeError
if (e.getKey() == null) {
throw runtime.newTypeError(runtime.getNil(), runtime.getStructClass());
}
// ignore if the value is nil
if (e.getValue() == null) {
continue;
}
ret[i] = e.getKey().toString() + "=" + e.getValue().toString();
i++;
}
if (mergeEnv != null) {
for (Map.Entry e : (Set<Map.Entry>) mergeEnv.entrySet()) {
// if the key is nil, raise TypeError
if (e.getKey() == null) {
throw runtime.newTypeError(runtime.getNil(), runtime.getStructClass());
}
// ignore if the value is nil
if (e.getValue() == null) {
continue;
}
ret[i] = e.getKey().toString() + "=" + e.getValue().toString();
i++;
}
}
ary = new String[i];
System.arraycopy(ret, 0, ary, 0, i);
return ary;
} finally {
context.setEventHooksEnabled(traceEnabled);
}
}
private static boolean filenameIsPathSearchable(String fname, boolean forExec) {
boolean isSearchable = true;
if (fname.startsWith("/") ||
fname.startsWith("./") ||
fname.startsWith("../") ||
(forExec && (fname.indexOf("/") != -1))) {
isSearchable = false;
}
if (Platform.IS_WINDOWS) {
if (fname.startsWith("\\") ||
fname.startsWith(".\\") ||
fname.startsWith("..\\") ||
((fname.length() > 2) && fname.startsWith(":",1)) ||
(forExec && (fname.indexOf("\\") != -1))) {
isSearchable = false;
}
}
return isSearchable;
}
private static File tryFile(Ruby runtime, String fdir, String fname) {
File pathFile;
if (fdir == null) {
pathFile = new File(fname);
} else {
pathFile = new File(fdir, fname);
}
if (!pathFile.isAbsolute()) {
pathFile = new File(runtime.getCurrentDirectory(), pathFile.getPath());
}
log(runtime, "Trying file " + pathFile);
if (pathFile.exists()) {
return pathFile;
} else {
return null;
}
}
private static boolean withExeSuffix(String fname) {
String lowerCaseFname = fname.toLowerCase();
for (String suffix : WINDOWS_EXE_SUFFIXES) {
if (lowerCaseFname.endsWith(suffix)) {
return true;
}
}
return false;
}
private static File isValidFile(Ruby runtime, String fdir, String fname, boolean isExec) {
File validFile = null;
if (isExec && Platform.IS_WINDOWS) {
if (withExeSuffix(fname)) {
validFile = tryFile(runtime, fdir, fname);
} else {
for (String suffix: WINDOWS_EXE_SUFFIXES) {
validFile = tryFile(runtime, fdir, fname + suffix);
if (validFile != null) {
// found a valid file, no need to search further
break;
}
}
}
} else {
validFile = tryFile(runtime, fdir, fname);
if (validFile != null) {
if (validFile.isDirectory()) {
return null;
}
if (isExec && !runtime.getPosix().stat(validFile.getAbsolutePath()).isExecutable()) {
throw runtime.newErrnoEACCESError(validFile.getAbsolutePath());
}
}
}
return validFile;
}
private static File isValidFile(Ruby runtime, String fname, boolean isExec) {
String fdir = null;
return isValidFile(runtime, fdir, fname, isExec);
}
private static File findPathFile(Ruby runtime, String fname, String[] path, boolean isExec) {
File pathFile = null;
boolean doPathSearch = filenameIsPathSearchable(fname, isExec);
if (doPathSearch) {
for (String fdir: path) {
// NOTE: Jruby's handling of tildes is more complete than
// MRI's, which can't handle user names after the tilde
// when searching the executable path
pathFile = isValidFile(runtime, fdir, fname, isExec);
if (pathFile != null) {
break;
}
}
} else {
pathFile = isValidFile(runtime, fname, isExec);
}
return pathFile;
}
private static File findPathExecutable(Ruby runtime, String fname) {
RubyHash env = (RubyHash) runtime.getObject().getConstant("ENV");
IRubyObject pathObject = env.op_aref(runtime.getCurrentContext(), RubyString.newString(runtime, PATH_ENV));
String[] pathNodes = null;
if (pathObject == null) {
pathNodes = DEFAULT_PATH; // ASSUME: not modified by callee
}
else {
String pathSeparator = System.getProperty("path.separator");
String path = pathObject.toString();
if (Platform.IS_WINDOWS) {
// Windows-specific behavior
path = "." + pathSeparator + path;
}
pathNodes = path.split(pathSeparator);
}
return findPathFile(runtime, fname, pathNodes, true);
}
public static int runAndWait(Ruby runtime, IRubyObject[] rawArgs) {
return runAndWait(runtime, rawArgs, runtime.getOutputStream());
}
public static long[] runAndWaitPid(Ruby runtime, IRubyObject[] rawArgs) {
return runAndWaitPid(runtime, rawArgs, runtime.getOutputStream(), true);
}
public static long runWithoutWait(Ruby runtime, IRubyObject[] rawArgs) {
return runWithoutWait(runtime, rawArgs, runtime.getOutputStream());
}
public static int runExternalAndWait(Ruby runtime, IRubyObject[] rawArgs, Map mergeEnv) {
OutputStream output = runtime.getOutputStream();
OutputStream error = runtime.getErrorStream();
InputStream input = runtime.getInputStream();
Process aProcess = null;
File pwd = new File(runtime.getCurrentDirectory());
LaunchConfig cfg = new LaunchConfig(runtime, rawArgs, true);
try {
try {
if (cfg.shouldRunInShell()) {
log(runtime, "Launching with shell");
// execute command with sh -c
// this does shell expansion of wildcards
cfg.verifyExecutableForShell();
aProcess = buildProcess(runtime, cfg.getExecArgs(), getCurrentEnv(runtime, mergeEnv), pwd);
} else {
log(runtime, "Launching directly (no shell)");
cfg.verifyExecutableForDirect();
aProcess = buildProcess(runtime, cfg.getExecArgs(), getCurrentEnv(runtime, mergeEnv), pwd);
}
} catch (SecurityException se) {
throw runtime.newSecurityError(se.getLocalizedMessage());
}
handleStreams(runtime, aProcess, input, output, error);
return aProcess.waitFor();
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
} catch (InterruptedException e) {
throw runtime.newThreadError("unexpected interrupt");
}
}
public static long runExternalWithoutWait(Ruby runtime, IRubyObject env, IRubyObject prog, IRubyObject options, IRubyObject args) {
return runExternal(runtime, env, prog, options, args, false);
}
public static long runExternal(Ruby runtime, IRubyObject env, IRubyObject prog, IRubyObject options, IRubyObject args, boolean wait) {
if (env.isNil() || !(env instanceof Map)) {
env = null;
}
IRubyObject[] rawArgs = args.convertToArray().toJavaArray();
OutputStream output = runtime.getOutputStream();
OutputStream error = runtime.getErrorStream();
InputStream input = runtime.getInputStream();
try {
Process aProcess = null;
File pwd = new File(runtime.getCurrentDirectory());
LaunchConfig cfg = new LaunchConfig(runtime, rawArgs, true);
try {
if (cfg.shouldRunInShell()) {
log(runtime, "Launching with shell");
// execute command with sh -c
// this does shell expansion of wildcards
cfg.verifyExecutableForShell();
aProcess = buildProcess(runtime, cfg.getExecArgs(), getCurrentEnv(runtime, (Map)env), pwd);
} else {
log(runtime, "Launching directly (no shell)");
cfg.verifyExecutableForDirect();
aProcess = buildProcess(runtime, cfg.getExecArgs(), getCurrentEnv(runtime, (Map)env), pwd);
}
} catch (SecurityException se) {
throw runtime.newSecurityError(se.getLocalizedMessage());
}
if (wait) {
handleStreams(runtime, aProcess, input, output, error);
try {
return aProcess.waitFor();
} catch (InterruptedException e) {
throw runtime.newThreadError("unexpected interrupt");
}
} else {
handleStreamsNonblocking(runtime, aProcess, runtime.getOutputStream(), error);
return getPidFromProcess(aProcess);
}
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
}
}
public static Process buildProcess(Ruby runtime, String[] args, String[] env, File pwd) throws IOException {
return runtime.getPosix().newProcessMaker(args)
.environment(env)
.directory(pwd)
.start();
}
public static long runExternalWithoutWait(Ruby runtime, IRubyObject[] rawArgs) {
return runWithoutWait(runtime, rawArgs, runtime.getOutputStream());
}
public static int execAndWait(Ruby runtime, IRubyObject[] rawArgs) {
return execAndWait(runtime, rawArgs, Collections.EMPTY_MAP);
}
public static int execAndWait(Ruby runtime, IRubyObject[] rawArgs, Map mergeEnv) {
File pwd = new File(runtime.getCurrentDirectory());
LaunchConfig cfg = new LaunchConfig(runtime, rawArgs, true);
if (cfg.shouldRunInProcess()) {
log(runtime, "ExecAndWait in-process");
try {
// exec needs to behave differently in-process, because it's technically
// supposed to replace the calling process. So if we're supposed to run
// in-process, we allow it to use the default streams and not use
// pumpers at all. See JRUBY-2156 and JRUBY-2154.
ScriptThreadProcess ipScript = new ScriptThreadProcess(
runtime, cfg.getExecArgs(), getCurrentEnv(runtime, mergeEnv), pwd, false);
ipScript.start();
return ipScript.waitFor();
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
} catch (InterruptedException e) {
throw runtime.newThreadError("unexpected interrupt");
}
} else {
return runExternalAndWait(runtime, rawArgs, mergeEnv);
}
}
public static int runAndWait(Ruby runtime, IRubyObject[] rawArgs, OutputStream output) {
return runAndWait(runtime, rawArgs, output, true);
}
public static int runAndWait(Ruby runtime, IRubyObject[] rawArgs, OutputStream output, boolean doExecutableSearch) {
return (int)runAndWaitPid(runtime, rawArgs, output, doExecutableSearch)[0];
}
public static long[] runAndWaitPid(Ruby runtime, IRubyObject[] rawArgs, OutputStream output, boolean doExecutableSearch) {
OutputStream error = runtime.getErrorStream();
InputStream input = runtime.getInputStream();
try {
Process aProcess = run(runtime, rawArgs, doExecutableSearch);
handleStreams(runtime, aProcess, input, output, error);
return new long[] {aProcess.waitFor(), getPidFromProcess(aProcess)};
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
} catch (InterruptedException e) {
throw runtime.newThreadError("unexpected interrupt");
}
}
private static long runWithoutWait(Ruby runtime, IRubyObject[] rawArgs, OutputStream output) {
OutputStream error = runtime.getErrorStream();
try {
Process aProcess = run(runtime, rawArgs, true);
handleStreamsNonblocking(runtime, aProcess, output, error);
return getPidFromProcess(aProcess);
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
}
}
private static long runExternalWithoutWait(Ruby runtime, IRubyObject[] rawArgs, OutputStream output) {
OutputStream error = runtime.getErrorStream();
try {
Process aProcess = run(runtime, rawArgs, true, true);
handleStreamsNonblocking(runtime, aProcess, output, error);
return getPidFromProcess(aProcess);
} catch (IOException e) {
throw runtime.newIOErrorFromException(e);
}
}
public static long getPidFromProcess(Process process) {
if (process instanceof ScriptThreadProcess) {
return process.hashCode();
} else if (process instanceof POpenProcess) {
return reflectPidFromProcess(((POpenProcess)process).getChild());
} else {
return reflectPidFromProcess(process);
}
}
private static final Class UNIXProcess;
private static final Field UNIXProcess_pid;
private static final Class ProcessImpl;
private static final Field ProcessImpl_handle;
private interface PidGetter { public long getPid(Process process); }
private static final PidGetter PID_GETTER;
static {
// default PidGetter
PidGetter pg = new PidGetter() {
public long getPid(Process process) {
return process.hashCode();
}
};
Class up = null;
Field pid = null;
try {
up = Class.forName("java.lang.UNIXProcess");
pid = up.getDeclaredField("pid");
pid.setAccessible(true);
} catch (Exception e) {
// ignore and try windows version
}
UNIXProcess = up;
UNIXProcess_pid = pid;
Class pi = null;
Field handle = null;
try {
pi = Class.forName("java.lang.ProcessImpl");
handle = pi.getDeclaredField("handle");
handle.setAccessible(true);
} catch (Exception e) {
// ignore and use hashcode
}
ProcessImpl = pi;
ProcessImpl_handle = handle;
if (UNIXProcess_pid != null) {
if (ProcessImpl_handle != null) {
// try both
pg = new PidGetter() {
public long getPid(Process process) {
try {
if (UNIXProcess.isInstance(process)) {
return (Integer)UNIXProcess_pid.get(process);
} else if (ProcessImpl.isInstance(process)) {
Long hproc = (Long) ProcessImpl_handle.get(process);
return WindowsFFI.getKernel32().GetProcessId(hproc);
}
} catch (Exception e) {
// ignore and use hashcode
}
return process.hashCode();
}
};
} else {
// just unix
pg = new PidGetter() {
public long getPid(Process process) {
try {
if (UNIXProcess.isInstance(process)) {
return (Integer)UNIXProcess_pid.get(process);
}
} catch (Exception e) {
// ignore and use hashcode
}
return process.hashCode();
}
};
}
} else if (ProcessImpl_handle != null) {
// just windows
pg = new PidGetter() {
public long getPid(Process process) {
try {
if (ProcessImpl.isInstance(process)) {
Long hproc = (Long) ProcessImpl_handle.get(process);
return WindowsFFI.getKernel32().GetProcessId(hproc);
}
} catch (Exception e) {
// ignore and use hashcode
}
return process.hashCode();
}
};
} else {
// neither
pg = new PidGetter() {
public long getPid(Process process) {
return process.hashCode();
}
};
}
PID_GETTER = pg;
}
public static long reflectPidFromProcess(Process process) {
return PID_GETTER.getPid(process);
}
public static Process run(Ruby runtime, IRubyObject string) throws IOException {
return run(runtime, new IRubyObject[] {string}, false);
}
public static POpenProcess popen(Ruby runtime, IRubyObject string, ModeFlags modes) throws IOException {
return new POpenProcess(popenShared(runtime, new IRubyObject[] {string}, null, true), runtime, modes);
}
public static POpenProcess popen(Ruby runtime, IRubyObject[] strings, Map env, ModeFlags modes) throws IOException {
return new POpenProcess(popenShared(runtime, strings, env), runtime, modes);
}
@Deprecated
public static POpenProcess popen(Ruby runtime, IRubyObject string, IOOptions modes) throws IOException {
return new POpenProcess(popenShared(runtime, new IRubyObject[] {string}, null, true), runtime, modes);
}
@Deprecated
public static POpenProcess popen(Ruby runtime, IRubyObject[] strings, Map env, IOOptions modes) throws IOException {
return new POpenProcess(popenShared(runtime, strings, env), runtime, modes);
}
public static POpenProcess popen3(Ruby runtime, IRubyObject[] strings) throws IOException {
return new POpenProcess(popenShared(runtime, strings));
}
public static POpenProcess popen3(Ruby runtime, IRubyObject[] strings, boolean addShell) throws IOException {
return new POpenProcess(popenShared(runtime, strings, null, addShell));
}
private static Process popenShared(Ruby runtime, IRubyObject[] strings) throws IOException {
return popenShared(runtime, strings, null);
}
private static Process popenShared(Ruby runtime, IRubyObject[] strings, Map env) throws IOException {
return popenShared(runtime, strings, env, false);
}
private static Process popenShared(Ruby runtime, IRubyObject[] strings, Map env, boolean addShell) throws IOException {
String shell = getShell(runtime);
Process childProcess = null;
File pwd = new File(runtime.getCurrentDirectory());
try {
// Peel off env hash, if given
IRubyObject envHash = null;
if (env == null && strings.length > 0 && !(envHash = TypeConverter.checkHashType(runtime, strings[0])).isNil()) {
strings = Arrays.copyOfRange(strings, 1, strings.length);
env = (Map)envHash;
}
// Peel off options hash and warn that we don't support them
if (strings.length > 1 && !(envHash = TypeConverter.checkHashType(runtime, strings[strings.length - 1])).isNil()) {
if (!((RubyHash)envHash).isEmpty()) {
runtime.getWarnings().warn("popen3 does not support spawn options in JRuby 1.7");
}
strings = Arrays.copyOfRange(strings, 0, strings.length - 1);
}
String[] args = parseCommandLine(runtime.getCurrentContext(), runtime, strings);
LaunchConfig lc = new LaunchConfig(runtime, strings, false);
boolean useShell = lc.shouldRunInShell();
if (addShell) for (String arg : args) useShell |= shouldUseShell(arg);
// CON: popen is a case where I think we should just always shell out.
if (strings.length == 1) {
if (useShell) {
// single string command, pass to sh to expand wildcards
String[] argArray = new String[3];
argArray[0] = shell;
argArray[1] = shell.endsWith("sh") ? "-c" : "/c";
argArray[2] = strings[0].asJavaString();
childProcess = buildProcess(runtime, argArray, getCurrentEnv(runtime, env), pwd);
} else {
childProcess = buildProcess(runtime, args, getCurrentEnv(runtime, env), pwd);
}
} else {
if (useShell) {
String[] argArray = new String[args.length + 2];
argArray[0] = shell;
argArray[1] = shell.endsWith("sh") ? "-c" : "/c";
System.arraycopy(args, 0, argArray, 2, args.length);
childProcess = buildProcess(runtime, argArray, getCurrentEnv(runtime, env), pwd);
} else {
// direct invocation of the command
childProcess = buildProcess(runtime, args, getCurrentEnv(runtime, env), pwd);
}
}
} catch (SecurityException se) {
throw runtime.newSecurityError(se.getLocalizedMessage());
}
return childProcess;
}
/**
* Unwrap all filtering streams between the given stream and its actual
* unfiltered stream. This is primarily to unwrap streams that have
* buffers that would interfere with interactivity.
*
* @param filteredStream The stream to unwrap
* @return An unwrapped stream, presumably unbuffered
*/
public static OutputStream unwrapBufferedStream(OutputStream filteredStream) {
if (RubyInstanceConfig.NO_UNWRAP_PROCESS_STREAMS) return filteredStream;
while (filteredStream instanceof FilterOutputStream) {
try {
filteredStream = (OutputStream)
FieldAccess.getProtectedFieldValue(FilterOutputStream.class,
"out", filteredStream);
} catch (Exception e) {
break; // break out if we've dug as deep as we can
}
}
return filteredStream;
}
/**
* Unwrap all filtering streams between the given stream and its actual
* unfiltered stream. This is primarily to unwrap streams that have
* buffers that would interfere with interactivity.
*
* @param filteredStream The stream to unwrap
* @return An unwrapped stream, presumably unbuffered
*/
public static InputStream unwrapBufferedStream(InputStream filteredStream) {
if (RubyInstanceConfig.NO_UNWRAP_PROCESS_STREAMS) return filteredStream;
// Java 7+ uses a stream that drains the child on exit, which when
// unwrapped breaks because the channel gets drained prematurely.
// System.out.println("class is :" + filteredStream.getClass().getName());
if (filteredStream.getClass().getName().indexOf("ProcessPipeInputStream") != 1) {
return filteredStream;
}
while (filteredStream instanceof FilterInputStream) {
try {
filteredStream = (InputStream)
FieldAccess.getProtectedFieldValue(FilterInputStream.class,
"in", filteredStream);
} catch (Exception e) {
break; // break out if we've dug as deep as we can
}
}
return filteredStream;
}
public static class POpenProcess extends Process {
private final Process child;
private final boolean waitForChild;
// real stream references, to keep them from being GCed prematurely
private InputStream realInput;
private OutputStream realOutput;
private InputStream realInerr;
private InputStream input;
private OutputStream output;
private InputStream inerr;
private FileChannel inputChannel;
private FileChannel outputChannel;
private FileChannel inerrChannel;
private Pumper inputPumper;
private Pumper inerrPumper;
@Deprecated
public POpenProcess(Process child, Ruby runtime, IOOptions modes) {
this(child, runtime, modes.getModeFlags());
}
public POpenProcess(Process child, Ruby runtime, ModeFlags modes) {
this.child = child;
if (modes.isWritable()) {
this.waitForChild = true;
prepareOutput(child);
} else {
this.waitForChild = false;
// close process output
// See JRUBY-3405; hooking up to parent process stdin caused
// problems for IRB etc using stdin.
try {child.getOutputStream().close();} catch (IOException ioe) {}
}
if (modes.isReadable()) {
prepareInput(child);
} else {
pumpInput(child, runtime);
}
pumpInerr(child, runtime);
}
public POpenProcess(Process child) {
this.child = child;
this.waitForChild = false;
prepareOutput(child);
prepareInput(child);
prepareInerr(child);
}
@Override
public OutputStream getOutputStream() {
return output;
}
@Override
public InputStream getInputStream() {
return input;
}
@Override
public InputStream getErrorStream() {
return inerr;
}
public FileChannel getInput() {
return inputChannel;
}
public FileChannel getOutput() {
return outputChannel;
}
public FileChannel getError() {
return inerrChannel;
}
public boolean hasOutput() {
return output != null || outputChannel != null;
}
public Process getChild() {
return child;
}
@Override
public int waitFor() throws InterruptedException {
return child.waitFor();
}
@Override
public int exitValue() {
return child.exitValue();
}
@Override
public void destroy() {
try {
// We try to safely close all streams and channels to the greatest
// extent possible.
try {if (input != null) input.close();} catch (Exception e) {}
try {if (inerr != null) inerr.close();} catch (Exception e) {}
try {if (output != null) output.close();} catch (Exception e) {}
try {if (inputChannel != null) inputChannel.close();} catch (Exception e) {}
try {if (inerrChannel != null) inerrChannel.close();} catch (Exception e) {}
try {if (outputChannel != null) outputChannel.close();} catch (Exception e) {}
// processes seem to have some peculiar locking sequences, so we
// need to ensure nobody is trying to close/destroy while we are
synchronized (this) {
if (inputPumper != null) synchronized(inputPumper) {inputPumper.quit();}
if (inerrPumper != null) synchronized(inerrPumper) {inerrPumper.quit();}
if (waitForChild) {
waitFor();
} else {
RubyIO.obliterateProcess(child);
}
}
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
private void prepareInput(Process child) {
// popen callers wants to be able to read, provide subprocess in directly
realInput = child.getInputStream();
input = unwrapBufferedStream(realInput);
if (input instanceof FileInputStream) {
// inputChannel = ((FileInputStream) input).getChannel();
} else {
inputChannel = null;
}
inputPumper = null;
}
private void prepareInerr(Process child) {
// popen callers wants to be able to read, provide subprocess in directly
realInerr = child.getErrorStream();
inerr = unwrapBufferedStream(realInerr);
if (inerr instanceof FileInputStream) {
inerrChannel = ((FileInputStream) inerr).getChannel();
} else {
inerrChannel = null;
}
inerrPumper = null;
}
private void prepareOutput(Process child) {
// popen caller wants to be able to write, provide subprocess out directly
realOutput = child.getOutputStream();
output = unwrapBufferedStream(realOutput);
if (output instanceof FileOutputStream) {
outputChannel = ((FileOutputStream) output).getChannel();
} else {
outputChannel = null;
}
}