1 package io.jawk.jrt;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 import java.io.File;
26 import java.io.FileOutputStream;
27 import java.io.FileInputStream;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
31 import java.io.PrintStream;
32 import java.nio.charset.StandardCharsets;
33 import java.text.DecimalFormatSymbols;
34 import java.util.ArrayList;
35 import java.util.Date;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.IdentityHashMap;
39 import java.util.HashSet;
40 import java.util.IllegalFormatException;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.Map;
44 import java.util.Objects;
45 import java.util.Set;
46 import java.util.StringTokenizer;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49 import io.jawk.Awk;
50 import io.jawk.intermediate.UninitializedObject;
51 import io.jawk.intermediate.UntypedObject;
52 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
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 public class JRT {
89
90 private static final boolean IS_WINDOWS = System.getProperty("os.name").indexOf("Windows") >= 0;
91
92
93
94
95
96
97
98
99 private static final int DYNAMIC_PATTERN_CACHE_LIMIT = 256;
100
101
102 private static final String DEV_STDIN = "/dev/stdin";
103
104 private static final String DEV_STDOUT = "/dev/stdout";
105
106 private static final String DEV_STDERR = "/dev/stderr";
107
108 private static final String DEV_FD_0 = "/dev/fd/0";
109
110 private static final String DEV_FD_1 = "/dev/fd/1";
111
112 private static final String DEV_FD_2 = "/dev/fd/2";
113
114 private static final String DEV_NULL = "/dev/null";
115
116 private static final String WINDOWS_NULL_DEVICE = "NUL";
117
118 private final VariableManager vm;
119
120 private IoState ioState;
121
122 private AwkSink awkSink;
123
124 private PrintStream error;
125
126 private PrintStream warning = System.err;
127
128
129
130
131
132
133 private InputStream standardInput = System.in;
134
135 private boolean spawnedProcessesInheritStandardInput;
136
137
138
139
140
141 private AwkSink standardErrorSink;
142
143 private Object ignorecase = Long.valueOf(0L);
144
145 private boolean ignoreCase;
146
147 private Map<Pattern, Pattern> caseInsensitivePatterns;
148
149 private Map<String, Pattern> dynamicPatterns;
150
151 private Map<String, Pattern> dynamicPatternsIgnoreCase;
152
153 private final StringBuffer replaceResult = new StringBuffer();
154
155 private Object inputLine = null;
156
157 private RecordState recordState;
158
159 private InputSource activeSource;
160 private static final UninitializedObject BLANK = new UninitializedObject();
161
162 private static final Integer ONE = Integer.valueOf(1);
163 private static final Integer ZERO = Integer.valueOf(0);
164 private static final Integer MINUS_ONE = Integer.valueOf(-1);
165 private String jrtInputString;
166
167
168 private long nr;
169 private long fnr;
170 private int rstart;
171 private int rlength;
172 private Object filename;
173 private Object errno;
174 private Object argind;
175 private boolean syntheticFilePresented;
176 private String fs;
177 private String rs;
178 private String ofs;
179 private String ors;
180 private String convfmt;
181 private String ofmt;
182 private String subsep;
183 private final Locale locale;
184 private final char decimalSeparator;
185
186 private static final class FileOutputState {
187
188 private final AwkSink sink;
189
190 private FileOutputState(AwkSink sinkParam) {
191 this.sink = Objects.requireNonNull(sinkParam, "sink");
192 }
193 }
194
195 private static final class CommandInputState {
196
197 private final Process process;
198 private final PartitioningReader reader;
199 private final Thread errorPump;
200
201 private CommandInputState(Process processParam, PartitioningReader readerParam, Thread errorPumpParam) {
202 this.process = Objects.requireNonNull(processParam, "process");
203 this.reader = Objects.requireNonNull(readerParam, "reader");
204 this.errorPump = errorPumpParam;
205 }
206 }
207
208 private static final class ProcessOutputState {
209
210 private final Process process;
211 private final AwkSink sink;
212 private final PrintStream processOutput;
213 private final Thread stdoutPump;
214 private final Thread stderrPump;
215
216 private ProcessOutputState(
217 Process processParam,
218 AwkSink sinkParam,
219 PrintStream processOutputParam,
220 Thread stdoutPumpParam,
221 Thread stderrPumpParam) {
222 this.process = Objects.requireNonNull(processParam, "process");
223 this.sink = Objects.requireNonNull(sinkParam, "sink");
224 this.processOutput = Objects.requireNonNull(processOutputParam, "processOutput");
225 this.stdoutPump = stdoutPumpParam;
226 this.stderrPump = stderrPumpParam;
227 }
228 }
229
230
231
232
233
234
235 private static final class FlushingAwkSink extends OutputStreamAwkSink {
236
237 private FlushingAwkSink(PrintStream printStream, Locale locale) {
238 super(printStream, locale);
239 }
240
241 @Override
242 public void print(String ofs, String ors, String ofmt, Object... values) {
243 super.print(ofs, ors, ofmt, values);
244 flush();
245 }
246
247 @Override
248 public void printf(String ofs, String ors, String ofmt, String convfmt, String format, Object... values) {
249 super.printf(ofs, ors, ofmt, convfmt, format, values);
250 flush();
251 }
252 }
253
254 private static final class IoState {
255
256 private final Map<String, PartitioningReader> fileReaders = new HashMap<String, PartitioningReader>();
257 private final Map<String, CommandInputState> commandInputs = new HashMap<String, CommandInputState>();
258 private final Map<String, FileOutputState> fileOutputs = new HashMap<String, FileOutputState>();
259 private final Map<String, ProcessOutputState> processOutputs = new HashMap<String, ProcessOutputState>();
260
261
262
263
264
265
266
267 private final Map<String, AwkSink> specialOutputs = new HashMap<String, AwkSink>();
268 }
269
270
271
272
273
274
275
276
277
278 @SuppressFBWarnings(value = {
279 "EI_EXPOSE_REP2",
280 "CT_CONSTRUCTOR_THROW" }, justification = "JRT must hold the provided runtime collaborators for later use;"
281 + " fail-fast argument validation with no security-sensitive state to protect from finalizer attacks")
282 public JRT(VariableManager vm, Locale locale, AwkSink awkSink, PrintStream error) {
283 this.vm = vm;
284 this.locale = locale == null ? Locale.US : locale;
285 this.decimalSeparator = DecimalFormatSymbols.getInstance(this.locale).getDecimalSeparator();
286 this.awkSink = Objects.requireNonNull(awkSink, "awkSink");
287 this.error = error == null ? System.err : error;
288 this.nr = 0L;
289 this.fnr = 0L;
290 this.rstart = 0;
291 this.rlength = 0;
292 this.filename = "";
293 this.fs = Awk.DEFAULT_FS;
294 this.rs = Awk.DEFAULT_RS;
295 this.ofs = Awk.DEFAULT_OFS;
296 this.ors = Awk.DEFAULT_ORS;
297 this.convfmt = Awk.DEFAULT_CONVFMT;
298 this.ofmt = Awk.DEFAULT_OFMT;
299 this.subsep = Awk.DEFAULT_SUBSEP;
300 }
301
302
303
304
305
306
307
308 public void setAwkSink(AwkSink sink) {
309 awkSink = Objects.requireNonNull(sink, "awkSink");
310 }
311
312
313
314
315
316
317
318 public void setErrorStream(PrintStream errorStream) {
319 this.error = Objects.requireNonNull(errorStream, "errorStream");
320 }
321
322
323
324
325
326
327
328
329
330 public void setWarningStream(PrintStream warningStream) {
331 this.warning = Objects.requireNonNull(warningStream, "warningStream");
332
333
334 this.standardErrorSink = null;
335 }
336
337
338
339
340
341
342
343
344
345
346
347 public void bindStandardInput(InputSource inputSource) {
348 this.standardInput = inputSource instanceof StreamInputSource ?
349 ((StreamInputSource) inputSource).getDefaultInput() : System.in;
350 }
351
352
353
354
355
356
357
358 public void printWarning(String message) {
359 warning.println(message);
360 warning.flush();
361 }
362
363
364
365
366
367
368 public AwkSink getAwkSink() {
369 return awkSink;
370 }
371
372
373
374
375
376
377 public Locale getLocale() {
378 return locale;
379 }
380
381 private IoState getIoState() {
382 if (ioState == null) {
383 ioState = new IoState();
384 }
385 return ioState;
386 }
387
388
389
390
391
392
393
394
395 public static boolean isJrtManagedSpecialVariable(String name) {
396 switch (name) {
397 case "FS":
398 case "RS":
399 case "OFS":
400 case "ORS":
401 case "CONVFMT":
402 case "OFMT":
403 case "SUBSEP":
404 case "FILENAME":
405 case "NF":
406 case "NR":
407 case "FNR":
408 case "ARGC":
409 case "IGNORECASE":
410 case "ERRNO":
411 case "ARGIND":
412 return true;
413 default:
414 return false;
415 }
416 }
417
418
419
420
421
422
423
424
425
426 public static boolean isGawkOnlySpecialVariable(String name) {
427 return "ERRNO".equals(name) || "ARGIND".equals(name);
428 }
429
430
431
432
433
434
435
436 public static Map<String, Object> copySpecialVariables(Map<String, Object> variableMap) {
437 Map<String, Object> specialVariables = new HashMap<String, Object>();
438 if (variableMap == null || variableMap.isEmpty()) {
439 return specialVariables;
440 }
441 for (Map.Entry<String, Object> entry : variableMap.entrySet()) {
442 if (isJrtManagedSpecialVariable(entry.getKey())) {
443 specialVariables.put(entry.getKey(), entry.getValue());
444 }
445 }
446 return specialVariables;
447 }
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464 public void prepareForExecution(String defaultFs, String defaultRs) {
465
466 jrtCloseAll();
467
468
469 ioState = null;
470 inputLine = null;
471 recordState = null;
472 activeSource = null;
473 jrtInputString = null;
474 nr = 0L;
475 fnr = 0L;
476 rstart = 0;
477 rlength = 0;
478 filename = "";
479 errno = "";
480 argind = ZERO;
481 syntheticFilePresented = false;
482
483
484 setFS(defaultFs == null ? Awk.DEFAULT_FS : defaultFs);
485 setRS(defaultRs);
486 setOFS(Awk.DEFAULT_OFS);
487 setORS(Awk.DEFAULT_ORS);
488 setCONVFMT(Awk.DEFAULT_CONVFMT);
489 setOFMT(Awk.DEFAULT_OFMT);
490 setSUBSEP(Awk.DEFAULT_SUBSEP);
491 setFILENAMEViaJrt("");
492 setNR(0);
493 setFNR(0);
494 setRSTART(0);
495 setRLENGTH(0);
496 setIGNORECASE(Long.valueOf(0L));
497 }
498
499
500
501
502
503
504
505 public final void assignInitialVariables(Map<String, Object> initialVarMap) {
506 for (Map.Entry<String, Object> var : initialVarMap.entrySet()) {
507 String name = var.getKey();
508 Object value = var.getValue();
509 if (!applySpecialVariable(name, value)) {
510 vm.assignVariable(name, value);
511 }
512 }
513 }
514
515
516
517
518
519
520
521
522
523 public boolean applySpecialVariable(String name, Object value) {
524 switch (name) {
525 case "FS":
526 setFS(value);
527 return true;
528 case "RS":
529 setRS(value);
530 return true;
531 case "OFS":
532 setOFS(value);
533 return true;
534 case "ORS":
535 setORS(value);
536 return true;
537 case "CONVFMT":
538 setCONVFMT(value);
539 return true;
540 case "OFMT":
541 setOFMT(value);
542 return true;
543 case "SUBSEP":
544 setSUBSEP(value);
545 return true;
546 case "FILENAME":
547 setFILENAMEViaJrt(value);
548 return true;
549 case "NF":
550 setNF(value);
551 return true;
552 case "NR":
553 setNR(value);
554 return true;
555 case "FNR":
556 setFNR(value);
557 return true;
558 case "ARGC":
559 setARGC(value);
560 return true;
561 case "IGNORECASE":
562 setIGNORECASE(value);
563 return true;
564 case "ERRNO":
565 setERRNO(value);
566 return true;
567 case "ARGIND":
568 setARGIND(value);
569 return true;
570 default:
571 return false;
572 }
573 }
574
575
576
577
578
579
580
581
582
583
584 public final void applySpecialVariables(Map<String, Object> variableMap) {
585 if (variableMap == null || variableMap.isEmpty()) {
586 return;
587 }
588 for (Map.Entry<String, Object> var : variableMap.entrySet()) {
589
590
591 applySpecialVariable(var.getKey(), var.getValue());
592 }
593 }
594
595
596
597
598
599
600
601
602
603
604 public static void assignEnvironmentVariables(AssocArray aa) {
605 Map<String, String> env = System.getenv();
606 for (Map.Entry<String, String> var : env.entrySet()) {
607 aa.put(var.getKey(), new StrNum(var.getValue()));
608 }
609 }
610
611
612
613
614
615
616
617
618 public static Map<Object, Object> createAwkMap(boolean sortedArrayKeys) {
619 return AssocArray.create(sortedArrayKeys);
620 }
621
622
623
624
625
626
627
628
629
630
631 public static boolean containsAwkKey(Map<Object, Object> map, Object key) {
632 if (map instanceof AssocArray) {
633 return ((AssocArray) map).isIn(key);
634 }
635 return map.containsKey(key);
636 }
637
638
639
640
641
642
643
644
645
646
647
648
649 public static Object getAssocArrayValue(Map<Object, Object> map, Object key) {
650 if (map instanceof AssocArray) {
651 return map.get(key);
652 }
653 Object value = map.get(key);
654 return value != null ? value : BLANK;
655 }
656
657
658
659
660
661
662
663
664
665
666
667
668 public String getAwkStringEntry(Map<Object, Object> map, Object key) {
669 if (!containsAwkKey(map, key)) {
670 return null;
671 }
672 return toAwkString(getAssocArrayValue(map, key));
673 }
674
675
676
677
678
679
680
681
682 public String toAwkString(Object o) {
683 return AwkPrintf.toAwkString(o, this.convfmt, this.locale);
684 }
685
686
687
688
689
690
691
692
693
694
695
696
697 public boolean compare(Object o1, Object o2, int mode) {
698 return compare2(o1, o2, mode, isIgnoreCase(), this.convfmt, this.locale);
699 }
700
701
702
703
704
705
706
707 public static double toDouble(final Object o) {
708 if (o == null) {
709 return 0;
710 }
711
712 if (o instanceof Number) {
713 return ((Number) o).doubleValue();
714 }
715
716 if (o instanceof Character) {
717 return (double) ((Character) o).charValue();
718 }
719
720 if (o instanceof StrNum) {
721 StrNum strNum = (StrNum) o;
722 if (strNum.isNumber()) {
723 return strNum.doubleValue();
724 }
725 }
726
727
728
729 String s = o.toString();
730 int length = s.length();
731 int start = 0;
732 while (start < length && Character.isWhitespace(s.charAt(start))) {
733 start++;
734 }
735
736
737
738 if (start < length) {
739 char sign = s.charAt(start);
740 if ((sign == '+' || sign == '-') && isBlankToEnd(s, start + 4)) {
741 if (s.regionMatches(true, start + 1, "inf", 0, 3)) {
742 return sign == '-' ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
743 }
744 if (s.regionMatches(true, start + 1, "nan", 0, 3)) {
745 return Double.NaN;
746 }
747 }
748 }
749 int end = numericPrefixEnd(s, start, '.');
750 if (end == start) {
751 return 0;
752 }
753
754 return Double.parseDouble(start == 0 && end == length ? s : s.substring(start, end));
755 }
756
757
758
759
760
761
762
763
764 public static boolean isActuallyLong(double d) {
765 double r = Math.rint(d);
766 return Math.abs(d - r) < Math.ulp(d);
767 }
768
769
770 private static final double TWO_POW_63 = 9.223372036854775808e18;
771
772
773
774
775
776
777
778
779
780
781
782
783 public static Object toScalarNumber(double d) {
784 if (isActuallyLong(d)) {
785 double rounded = Math.rint(d);
786 if (rounded >= -TWO_POW_63 && rounded < TWO_POW_63) {
787 return Long.valueOf((long) rounded);
788 }
789 }
790 return Double.valueOf(d);
791 }
792
793
794
795
796
797
798
799
800
801 public static Object truncateToScalar(double d) {
802 if (Double.isNaN(d) || Double.isInfinite(d)) {
803 return Double.valueOf(d);
804 }
805 return toScalarNumber(d < 0 ? Math.ceil(d) : Math.floor(d));
806 }
807
808
809
810
811
812
813
814
815
816
817 private static boolean isExactIntegral(Object o) {
818 return o instanceof Long || o instanceof Integer;
819 }
820
821
822
823
824
825
826
827
828
829
830
831 public static Object add(Object o1, Object o2) {
832 if (isExactIntegral(o1) && isExactIntegral(o2)) {
833 try {
834 return Math.addExact(((Number) o1).longValue(), ((Number) o2).longValue());
835 } catch (ArithmeticException overflow) {
836 return toDouble(o1) + toDouble(o2);
837 }
838 }
839 return toDouble(o1) + toDouble(o2);
840 }
841
842
843
844
845
846
847
848
849
850
851
852 public static Object subtract(Object o1, Object o2) {
853 if (isExactIntegral(o1) && isExactIntegral(o2)) {
854 try {
855 return Math.subtractExact(((Number) o1).longValue(), ((Number) o2).longValue());
856 } catch (ArithmeticException overflow) {
857 return toDouble(o1) - toDouble(o2);
858 }
859 }
860 return toDouble(o1) - toDouble(o2);
861 }
862
863
864
865
866
867
868
869
870
871
872
873 public static Object multiply(Object o1, Object o2) {
874 if (isExactIntegral(o1) && isExactIntegral(o2)) {
875 try {
876 return Math.multiplyExact(((Number) o1).longValue(), ((Number) o2).longValue());
877 } catch (ArithmeticException overflow) {
878 return toDouble(o1) * toDouble(o2);
879 }
880 }
881 return toDouble(o1) * toDouble(o2);
882 }
883
884
885
886
887
888
889
890
891
892
893
894
895 public static Object divide(Object o1, Object o2) {
896 if (isExactIntegral(o1) && isExactIntegral(o2)) {
897 long l1 = ((Number) o1).longValue();
898 long l2 = ((Number) o2).longValue();
899 if (l2 != 0 && l1 % l2 == 0 && (l1 != Long.MIN_VALUE || l2 != -1)) {
900 return l1 / l2;
901 }
902 }
903 return toDouble(o1) / toDouble(o2);
904 }
905
906
907
908
909
910
911
912
913
914
915
916 public static Object mod(Object o1, Object o2) {
917 if (isExactIntegral(o1) && isExactIntegral(o2)) {
918 long l2 = ((Number) o2).longValue();
919 if (l2 != 0) {
920 return ((Number) o1).longValue() % l2;
921 }
922 }
923 return toDouble(o1) % toDouble(o2);
924 }
925
926
927
928
929
930
931
932
933
934 public static Object pow(Object o1, Object o2) {
935 return Math.pow(toDouble(o1), toDouble(o2));
936 }
937
938
939
940
941
942
943
944
945
946
947 public static Object negate(Object o) {
948 if (isExactIntegral(o)) {
949 long l = ((Number) o).longValue();
950 if (l != Long.MIN_VALUE) {
951 return -l;
952 }
953 }
954 return -toDouble(o);
955 }
956
957
958
959
960
961
962
963 public static long toLong(final Object o) {
964 if (o == null) {
965 return 0;
966 }
967
968 if (o instanceof Number) {
969 return ((Number) o).longValue();
970 }
971
972 if (o instanceof Character) {
973 return (long) ((Character) o).charValue();
974 }
975
976
977
978
979
980
981
982 String s = o.toString();
983 int length = s.length();
984 int index = 0;
985 while (index < length && Character.isWhitespace(s.charAt(index))) {
986 index++;
987 }
988 boolean negative = index < length && s.charAt(index) == '-';
989 if (index < length && (negative || s.charAt(index) == '+')) {
990 index++;
991 }
992 int firstDigit = index;
993 long value = 0;
994 while (index < length && isAsciiDigit(s.charAt(index))) {
995 int digit = s.charAt(index) - '0';
996 if (value > (Long.MAX_VALUE - digit) / 10) {
997
998
999 break;
1000 }
1001 value = value * 10 + digit;
1002 index++;
1003 }
1004 if (index > firstDigit && !continuesNumber(s, index)) {
1005 return negative ? -value : value;
1006 }
1007 return (long) toDouble(o);
1008 }
1009
1010
1011
1012
1013
1014 private static boolean isBlankToEnd(String value, int index) {
1015 for (int i = index; i < value.length(); i++) {
1016 if (!Character.isWhitespace(value.charAt(i))) {
1017 return false;
1018 }
1019 }
1020 return true;
1021 }
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031 private static boolean continuesNumber(String value, int index) {
1032 if (index >= value.length()) {
1033 return false;
1034 }
1035 char c = value.charAt(index);
1036 if (isAsciiDigit(c) || c == '.') {
1037 return true;
1038 }
1039 if (c != 'e' && c != 'E') {
1040 return false;
1041 }
1042 int afterExponent = index + 1;
1043 if (afterExponent < value.length()
1044 && (value.charAt(afterExponent) == '+' || value.charAt(afterExponent) == '-')) {
1045 afterExponent++;
1046 }
1047 return afterExponent < value.length() && isAsciiDigit(value.charAt(afterExponent));
1048 }
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058 public static long parseFieldNumber(Object obj) {
1059 long num = toLong(obj);
1060 if (num < 0) {
1061 throw new AwkRuntimeException(
1062 "Field $(" + obj.toString()
1063 + ") is incorrect.");
1064 }
1065 return num;
1066 }
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083 public static boolean compare2(Object o1, Object o2, int mode) {
1084 return compare2(o1, o2, mode, false);
1085 }
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099 public static boolean compare2(Object o1, Object o2, int mode, boolean ignoreCase) {
1100
1101
1102
1103
1104 return compare2(o1, o2, mode, ignoreCase, null, Locale.US);
1105 }
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128 private static boolean compare2(
1129 Object o1,
1130 Object o2,
1131 int mode,
1132 boolean ignoreCase,
1133 String convfmt,
1134 Locale locale) {
1135 if (o1 instanceof Number && o2 instanceof Number) {
1136 if (isExactIntegral(o1) && isExactIntegral(o2)) {
1137
1138
1139 int comparison = Long.compare(((Number) o1).longValue(), ((Number) o2).longValue());
1140 if (mode == 0) {
1141 return comparison == 0;
1142 }
1143 return mode < 0 ? comparison < 0 : comparison > 0;
1144 }
1145 return compareNumbers(((Number) o1).doubleValue(), ((Number) o2).doubleValue(), mode);
1146 }
1147
1148 if (o1 instanceof UninitializedObject) {
1149 if (isBlankOrZero(o2, convfmt, locale)) {
1150 return mode == 0;
1151 } else {
1152 return mode < 0;
1153 }
1154 }
1155 if (o2 instanceof UninitializedObject) {
1156 if (isBlankOrZero(o1, convfmt, locale)) {
1157 return mode == 0;
1158 } else {
1159 return mode > 0;
1160 }
1161 }
1162
1163 if (isNumericComparisonOperand(o1) && isNumericComparisonOperand(o2)) {
1164 return compareNumbers(getDoubleForComparison(o1), getDoubleForComparison(o2), mode);
1165 }
1166
1167
1168
1169
1170 String o1String = AwkPrintf.toAwkString(o1, convfmt, locale);
1171 String o2String = AwkPrintf.toAwkString(o2, convfmt, locale);
1172
1173 if (mode == 0) {
1174 return ignoreCase ? o1String.equalsIgnoreCase(o2String) : o1String.equals(o2String);
1175 }
1176 int comparison = ignoreCase ? o1String.compareToIgnoreCase(o2String) : o1String.compareTo(o2String);
1177 return mode < 0 ? comparison < 0 : comparison > 0;
1178 }
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189 public int index(String haystack, String needle) {
1190 if (!ignoreCase) {
1191 return haystack.indexOf(needle) + 1;
1192 }
1193 int max = haystack.length() - needle.length();
1194 for (int i = 0; i <= max; i++) {
1195 if (haystack.regionMatches(true, i, needle, 0, needle.length())) {
1196 return i + 1;
1197 }
1198 }
1199 return 0;
1200 }
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213 private static boolean isBlankOrZero(Object value, String convfmt, Locale locale) {
1214 if (value instanceof UninitializedObject) {
1215 return true;
1216 }
1217 if (value instanceof Number) {
1218 return ((Number) value).doubleValue() == 0.0D;
1219 }
1220 if (value instanceof StrNum && ((StrNum) value).isNumber()) {
1221 return ((StrNum) value).doubleValue() == 0.0D;
1222 }
1223 String stringValue = AwkPrintf.toAwkString(value, convfmt, locale);
1224 return "".equals(stringValue) || "0".equals(stringValue);
1225 }
1226
1227 private static boolean isNumericComparisonOperand(Object value) {
1228 return value instanceof Number || value instanceof StrNum && ((StrNum) value).isNumber();
1229 }
1230
1231 private static double getDoubleForComparison(Object value) {
1232 if (value instanceof Number) {
1233 return ((Number) value).doubleValue();
1234 }
1235 return ((StrNum) value).doubleValue();
1236 }
1237
1238 private static boolean compareNumbers(double o1Number, double o2Number, int mode) {
1239 if (mode < 0) {
1240 return o1Number < o2Number;
1241 } else if (mode == 0) {
1242 return o1Number == o2Number;
1243 } else {
1244 return o1Number > o2Number;
1245 }
1246 }
1247
1248
1249
1250
1251
1252
1253
1254 public static Object toJavaScalar(Object value) {
1255 if (value instanceof StrNum) {
1256 return value.toString();
1257 }
1258 if (value instanceof Double || value instanceof Float) {
1259 return toScalarNumber(((Number) value).doubleValue());
1260 }
1261 return value;
1262 }
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273 public boolean isParseableNumber(String value) {
1274 return isParseableNumber(value, decimalSeparator);
1275 }
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289 public static Object untypedToBlank(Object value) {
1290 return value instanceof UntypedObject ? BLANK : value;
1291 }
1292
1293 static boolean isParseableNumber(String value, char decimalSeparator) {
1294 int length = value.length();
1295 int start = 0;
1296 while (start < length && Character.isWhitespace(value.charAt(start))) {
1297 start++;
1298 }
1299 int end = numericPrefixEnd(value, start, decimalSeparator);
1300 return end > start && isBlankToEnd(value, end);
1301 }
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312 static String trimWhitespace(String value) {
1313 int end = value.length();
1314 int start = 0;
1315 while (start < end && Character.isWhitespace(value.charAt(start))) {
1316 start++;
1317 }
1318 while (end > start && Character.isWhitespace(value.charAt(end - 1))) {
1319 end--;
1320 }
1321 return start == 0 && end == value.length() ? value : value.substring(start, end);
1322 }
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344 private static int numericPrefixEnd(String value, int start, char decimalSeparator) {
1345 int length = value.length();
1346 int index = start;
1347
1348 if (index < length && (value.charAt(index) == '+' || value.charAt(index) == '-')) {
1349 index++;
1350 }
1351
1352 boolean digitFound = false;
1353 while (index < length && isAsciiDigit(value.charAt(index))) {
1354 index++;
1355 digitFound = true;
1356 }
1357
1358 if (index < length && value.charAt(index) == decimalSeparator) {
1359 index++;
1360 while (index < length && isAsciiDigit(value.charAt(index))) {
1361 index++;
1362 digitFound = true;
1363 }
1364 }
1365
1366 if (!digitFound) {
1367 return start;
1368 }
1369
1370 if (index < length && (value.charAt(index) == 'e' || value.charAt(index) == 'E')) {
1371 int afterExponent = index + 1;
1372 if (afterExponent < length
1373 && (value.charAt(afterExponent) == '+' || value.charAt(afterExponent) == '-')) {
1374 afterExponent++;
1375 }
1376 int exponentDigits = afterExponent;
1377 while (afterExponent < length && isAsciiDigit(value.charAt(afterExponent))) {
1378 afterExponent++;
1379 }
1380
1381
1382 if (afterExponent > exponentDigits) {
1383 index = afterExponent;
1384 }
1385 }
1386
1387 return index;
1388 }
1389
1390 private static boolean isAsciiDigit(char c) {
1391 return c >= '0' && c <= '9';
1392 }
1393
1394 static String normalizeNumberForComparison(String value, char decimalSeparator) {
1395 return decimalSeparator == '.' ? value : value.replace(decimalSeparator, '.');
1396 }
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409 public static Object inc(Object o) {
1410 if (isExactIntegral(o)) {
1411 long l = ((Number) o).longValue();
1412 if (l != Long.MAX_VALUE) {
1413 return l + 1;
1414 }
1415 }
1416 return toDouble(o) + 1;
1417 }
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430 public static Object dec(Object o) {
1431 if (isExactIntegral(o)) {
1432 long l = ((Number) o).longValue();
1433 if (l != Long.MIN_VALUE) {
1434 return l - 1;
1435 }
1436 }
1437 return toDouble(o) - 1;
1438 }
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457 public final boolean toBoolean(Object o) {
1458 boolean val;
1459 if (o instanceof Integer) {
1460 val = ((Integer) o).intValue() != 0;
1461 } else if (o instanceof Long) {
1462 val = ((Long) o).longValue() != 0;
1463 } else if (o instanceof Double) {
1464 val = ((Double) o).doubleValue() != 0;
1465 } else if (o instanceof StrNum) {
1466 StrNum strNum = (StrNum) o;
1467 val = strNum.isNumber() ? strNum.doubleValue() != 0 : strNum.toString().length() > 0;
1468 } else if (o instanceof String) {
1469 val = (o.toString().length() > 0);
1470 } else if (o instanceof UninitializedObject) {
1471 val = false;
1472 } else if (o instanceof Pattern) {
1473
1474 Pattern pattern = caseAwarePattern((Pattern) o);
1475 Object inputField = jrtGetInputField(0);
1476 String s = inputField instanceof UninitializedObject ? "" : inputField.toString();
1477 Matcher matcher = pattern.matcher(s);
1478 val = matcher.find();
1479 } else {
1480 throw new Error("Unknown operand_stack type: " + o.getClass() + " for value " + o);
1481 }
1482 return val;
1483 }
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494 public int split(Object array, Object string) {
1495 return splitWorker(new StringTokenizer(toAwkString(string)), toArrayMap(array));
1496 }
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510 public int split(Object fieldSeparator, Object array, Object string) {
1511 return splitWorker(splitTokenizer(toAwkString(string), fieldSeparator), toArrayMap(array));
1512 }
1513
1514 private static Map<Object, Object> toArrayMap(Object array) {
1515 if (!(array instanceof Map)) {
1516 throw new IllegalArgumentException("split target must be a Map.");
1517 }
1518 @SuppressWarnings("unchecked")
1519 Map<Object, Object> arrayMap = (Map<Object, Object>) array;
1520 return arrayMap;
1521 }
1522
1523 private int splitWorker(Enumeration<Object> e, Map<Object, Object> array) {
1524 int cnt = 0;
1525 array.clear();
1526 while (e.hasMoreElements()) {
1527 Object value = e.nextElement();
1528 array.put(Long.valueOf(++cnt), toInputScalar(value));
1529 }
1530 array.put(0L, Long.valueOf(cnt));
1531 return cnt;
1532 }
1533
1534
1535
1536
1537
1538
1539
1540
1541 public PartitioningReader getPartitioningReader() {
1542 if (activeSource instanceof StreamInputSource) {
1543 return ((StreamInputSource) activeSource).getPartitioningReader();
1544 }
1545 return null;
1546 }
1547
1548
1549
1550
1551
1552
1553
1554
1555 public Object getInputLine() {
1556 if (recordState != null) {
1557 return recordState.getField(0);
1558 }
1559 return inputLine;
1560 }
1561
1562
1563
1564
1565
1566
1567
1568 public Integer getNF() {
1569 if (recordState == null) {
1570 return Integer.valueOf(0);
1571 }
1572 return Integer.valueOf(recordState.getNF());
1573 }
1574
1575
1576
1577
1578
1579
1580 public void setNF(Object nfObject) {
1581 jrtSetNF(nfObject);
1582 }
1583
1584
1585
1586
1587
1588
1589 public Long getNR() {
1590 return Long.valueOf(nr);
1591 }
1592
1593
1594
1595
1596
1597
1598 public void setNR(Object value) {
1599 this.nr = toLong(value);
1600 }
1601
1602
1603
1604
1605
1606
1607 public Long getFNR() {
1608 return Long.valueOf(fnr);
1609 }
1610
1611
1612
1613
1614
1615
1616 public void setFNR(Object value) {
1617 this.fnr = toLong(value);
1618 }
1619
1620
1621
1622
1623
1624
1625 public Object getFSVar() {
1626 return fs;
1627 }
1628
1629
1630
1631
1632
1633
1634 public String getFSString() {
1635 return fs;
1636 }
1637
1638
1639
1640
1641
1642
1643 public void setFS(Object value) {
1644 this.fs = value == null ? "" : value.toString();
1645 }
1646
1647
1648
1649
1650
1651
1652
1653 public void setIGNORECASE(Object value) {
1654 this.ignorecase = value == null ? Long.valueOf(0L) : value;
1655
1656
1657 this.ignoreCase = toBoolean(this.ignorecase);
1658 }
1659
1660
1661
1662
1663
1664
1665 public Object getIGNORECASEVar() {
1666 return ignorecase;
1667 }
1668
1669
1670
1671
1672
1673
1674
1675
1676 public boolean isIgnoreCase() {
1677 return ignoreCase;
1678 }
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688 public int regexpFlags() {
1689 return ignoreCase ? Pattern.CASE_INSENSITIVE : 0;
1690 }
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702 public int replaceFirst(String orig, String repl, String ere) {
1703 return replace(orig, repl, ere, false);
1704 }
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716 public int replaceAll(String orig, String repl, String ere) {
1717 return replace(orig, repl, ere, true);
1718 }
1719
1720 private int replace(String orig, String repl, String ere, boolean global) {
1721 replaceResult.setLength(0);
1722 String preparedReplacement = prepareReplacement(repl, false);
1723 Matcher matcher = dynamicPattern(ere).matcher(orig);
1724 int count = 0;
1725 while (matcher.find()) {
1726 count++;
1727 matcher.appendReplacement(replaceResult, preparedReplacement);
1728 if (!global) {
1729 break;
1730 }
1731 }
1732 matcher.appendTail(replaceResult);
1733 return count;
1734 }
1735
1736
1737
1738
1739
1740
1741
1742 public String getReplaceResult() {
1743 return replaceResult.toString();
1744 }
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755 public boolean matches(String text, Object regexp) {
1756 if (regexp instanceof Pattern) {
1757
1758 return caseAwarePattern((Pattern) regexp).matcher(text).find();
1759 }
1760 return dynamicPattern(toAwkString(regexp)).matcher(text).find();
1761 }
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771 public int matchPosition(String s, String ere) {
1772 Matcher matcher = dynamicPattern(ere).matcher(s);
1773 if (matcher.find()) {
1774 int start = matcher.start() + 1;
1775 setRSTART(start);
1776 setRLENGTH(matcher.end() - matcher.start());
1777 return start;
1778 }
1779 setRSTART(0);
1780 setRLENGTH(-1);
1781 return 0;
1782 }
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795 public Enumeration<Object> splitTokenizer(String input, Object separator) {
1796 if (separator instanceof Pattern) {
1797 return new RegexTokenizer(input, caseAwarePattern((Pattern) separator));
1798 }
1799 String fsString = toAwkString(separator);
1800 if (fsString.equals(" ")) {
1801 return new StringTokenizer(input);
1802 }
1803 if (fsString.isEmpty()) {
1804 return new CharacterTokenizer(input);
1805 }
1806 if (fsString.length() == 1) {
1807 char fsChar = fsString.charAt(0);
1808 if (ignoreCase && Character.isLetter(fsChar)) {
1809
1810
1811 return new RegexTokenizer(input, dynamicPattern(fsString));
1812 }
1813 return new SingleCharacterTokenizer(input, fsChar);
1814 }
1815 return new RegexTokenizer(input, dynamicPattern(fsString));
1816 }
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829 public static String prepareReplacement(String awkRepl, boolean backreferences) {
1830 return prepareReplacement(awkRepl, backreferences ? Integer.MAX_VALUE : -1);
1831 }
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846 public static String prepareReplacement(String awkRepl, int maxGroup) {
1847 boolean backreferences = maxGroup >= 0;
1848 if (awkRepl == null) {
1849 return "";
1850 }
1851
1852 if ((awkRepl.indexOf('\\') == -1) && (awkRepl.indexOf('$') == -1) && (awkRepl.indexOf('&') == -1)) {
1853 return awkRepl;
1854 }
1855
1856 StringBuilder javaRepl = new StringBuilder();
1857 for (int i = 0; i < awkRepl.length(); i++) {
1858 char c = awkRepl.charAt(i);
1859
1860 if (c == '\\' && i == awkRepl.length() - 1) {
1861
1862
1863
1864 javaRepl.append(backreferences ? "\\\\" : "\\");
1865 continue;
1866 }
1867
1868 if (c == '\\') {
1869 i++;
1870 c = awkRepl.charAt(i);
1871 if (c == '&') {
1872 javaRepl.append('&');
1873 continue;
1874 } else if (c == '\\') {
1875 javaRepl.append("\\\\");
1876 continue;
1877 } else if (backreferences && Character.isDigit(c)) {
1878 if (c - '0' <= maxGroup) {
1879 javaRepl.append('$').append(c);
1880 }
1881
1882
1883 continue;
1884 }
1885
1886 javaRepl.append('\\');
1887 }
1888
1889 if (c == '$') {
1890 javaRepl.append("\\$");
1891 } else if (c == '&') {
1892 javaRepl.append("$0");
1893 } else {
1894 javaRepl.append(c);
1895 }
1896 }
1897
1898 return javaRepl.toString();
1899 }
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911 public Pattern caseAwarePattern(Pattern pattern) {
1912 if (!ignoreCase || (pattern.flags() & Pattern.CASE_INSENSITIVE) != 0) {
1913 return pattern;
1914 }
1915 if (caseInsensitivePatterns == null) {
1916 caseInsensitivePatterns = new IdentityHashMap<Pattern, Pattern>();
1917 }
1918 return caseInsensitivePatterns
1919 .computeIfAbsent(
1920 pattern,
1921 base -> Pattern.compile(base.pattern(), base.flags() | Pattern.CASE_INSENSITIVE));
1922 }
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939 public Pattern dynamicPattern(String ere) {
1940 if (dynamicPatterns == null) {
1941 dynamicPatterns = new HashMap<String, Pattern>();
1942 dynamicPatternsIgnoreCase = new HashMap<String, Pattern>();
1943 }
1944 Map<String, Pattern> cache = ignoreCase ? dynamicPatternsIgnoreCase : dynamicPatterns;
1945 Pattern pattern = cache.get(ere);
1946 if (pattern == null) {
1947 if (cache.size() >= DYNAMIC_PATTERN_CACHE_LIMIT) {
1948 cache.clear();
1949 }
1950 pattern = Pattern.compile(ere, regexpFlags());
1951 cache.put(ere, pattern);
1952 }
1953 return pattern;
1954 }
1955
1956
1957
1958
1959
1960
1961 public Object getRSVar() {
1962 return rs;
1963 }
1964
1965
1966
1967
1968
1969
1970 public String getRSString() {
1971 return rs;
1972 }
1973
1974
1975
1976
1977
1978
1979 public void setRS(Object value) {
1980 this.rs = value == null ? "" : value.toString();
1981 applyRS(this.rs);
1982 }
1983
1984
1985
1986
1987
1988
1989 public Object getOFSVar() {
1990 return ofs;
1991 }
1992
1993
1994
1995
1996
1997
1998 public String getOFSString() {
1999 return ofs;
2000 }
2001
2002
2003
2004
2005
2006
2007 public void setOFS(Object value) {
2008 this.ofs = value == null ? "" : value.toString();
2009 }
2010
2011
2012
2013
2014
2015
2016 public Object getORSVar() {
2017 return ors;
2018 }
2019
2020
2021
2022
2023
2024
2025 public String getORSString() {
2026 return ors;
2027 }
2028
2029
2030
2031
2032
2033
2034 public void setORS(Object value) {
2035 this.ors = value == null ? "" : value.toString();
2036 }
2037
2038
2039
2040
2041
2042
2043 public Integer getRSTART() {
2044 return Integer.valueOf(rstart);
2045 }
2046
2047
2048
2049
2050
2051
2052 public void setRSTART(Object value) {
2053 this.rstart = (int) toLong(value);
2054 }
2055
2056
2057
2058
2059
2060
2061 public Integer getRLENGTH() {
2062 return Integer.valueOf(rlength);
2063 }
2064
2065
2066
2067
2068
2069
2070 public void setRLENGTH(Object value) {
2071 this.rlength = (int) toLong(value);
2072 }
2073
2074
2075
2076
2077
2078
2079 public Object getFILENAME() {
2080 return filename == null ? "" : filename;
2081 }
2082
2083
2084
2085
2086
2087
2088 public void setFILENAMEViaJrt(Object name) {
2089 this.filename = normalizeRecordValue(name);
2090 }
2091
2092
2093
2094
2095
2096
2097 public Object getERRNO() {
2098 return errno == null ? "" : errno;
2099 }
2100
2101
2102
2103
2104
2105
2106 public void setERRNO(Object value) {
2107 this.errno = normalizeRecordValue(value);
2108 }
2109
2110
2111
2112
2113
2114
2115 public Object getARGIND() {
2116 return argind == null ? ZERO : argind;
2117 }
2118
2119
2120
2121
2122
2123
2124 public void setARGIND(Object value) {
2125 this.argind = normalizeRecordValue(value);
2126 }
2127
2128
2129
2130
2131
2132
2133 public Object getSUBSEPVar() {
2134 return subsep;
2135 }
2136
2137
2138
2139
2140
2141
2142 public String getSUBSEPString() {
2143 return subsep;
2144 }
2145
2146
2147
2148
2149
2150
2151 public void setSUBSEP(Object value) {
2152 this.subsep = value == null ? "" : value.toString();
2153 }
2154
2155
2156
2157
2158
2159
2160 public Object getCONVFMTVar() {
2161 return convfmt;
2162 }
2163
2164
2165
2166
2167
2168
2169 public String getCONVFMTString() {
2170 return convfmt;
2171 }
2172
2173
2174
2175
2176
2177
2178 public void setCONVFMT(Object value) {
2179 this.convfmt = value == null ? "" : value.toString();
2180 }
2181
2182
2183
2184
2185
2186
2187 public String getOFMTString() {
2188 return ofmt;
2189 }
2190
2191
2192
2193
2194
2195
2196 public void setOFMT(Object value) {
2197 this.ofmt = value == null ? "" : value.toString();
2198 }
2199
2200
2201
2202
2203
2204
2205 public Object getARGCVar() {
2206 return vm.getARGC();
2207 }
2208
2209
2210
2211
2212
2213
2214 public void setARGC(Object value) {
2215 vm.assignVariable("ARGC", value);
2216 }
2217
2218
2219
2220
2221
2222
2223
2224
2225 public void setInputLine(Object inputLineParam) {
2226 Object inputValue = normalizeRecordValue(inputLineParam);
2227 this.inputLine = inputValue;
2228 recordState = new RecordState(inputValue, null);
2229 }
2230
2231
2232
2233
2234
2235
2236
2237 public Object toInputScalar(Object value) {
2238 if (value instanceof String) {
2239 return new StrNum((String) value, decimalSeparator);
2240 }
2241 if (value instanceof StrNum) {
2242 return value;
2243 }
2244 if (value == null || value instanceof UninitializedObject) {
2245 return new StrNum("", decimalSeparator);
2246 }
2247 return new StrNum(value.toString(), decimalSeparator);
2248 }
2249
2250 private static Object normalizeRecordValue(Object value) {
2251 if (value == null || value instanceof UninitializedObject) {
2252 return "";
2253 }
2254 return value;
2255 }
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267 public boolean consumeInput(final InputSource source) throws IOException {
2268 Objects.requireNonNull(source, "source");
2269 activeSource = source;
2270 if (!source.nextRecord()) {
2271 return false;
2272 }
2273
2274 bindConsumedRecord(source);
2275 return true;
2276 }
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295 public boolean consumeCurrentFileInput(final InputSource source) throws IOException {
2296 Objects.requireNonNull(source, "source");
2297 if (!(source instanceof StreamInputSource)) {
2298
2299 return consumeInput(source);
2300 }
2301 StreamInputSource streamSource = (StreamInputSource) source;
2302 throwIfCurrentFileUnopened(streamSource);
2303 activeSource = source;
2304 if (!streamSource.nextRecordInCurrentFile()) {
2305 return false;
2306 }
2307 bindConsumedRecord(source);
2308 return true;
2309 }
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325 public Object consumeCurrentFileInputToTarget(final InputSource source) throws IOException {
2326 Objects.requireNonNull(source, "source");
2327 if (!(source instanceof StreamInputSource)) {
2328
2329 return consumeInputToTarget(source);
2330 }
2331 StreamInputSource streamSource = (StreamInputSource) source;
2332 throwIfCurrentFileUnopened(streamSource);
2333 activeSource = source;
2334 materializeCurrentRecord();
2335 if (!streamSource.nextRecordInCurrentFile()) {
2336 return null;
2337 }
2338
2339 RecordState inputState = new RecordState(source);
2340 this.nr++;
2341 if (countsTowardFNR(source)) {
2342 this.fnr++;
2343 }
2344 return new StrNum(inputState.getRecordText(), decimalSeparator);
2345 }
2346
2347
2348
2349
2350
2351
2352
2353
2354 private void throwIfCurrentFileUnopened(StreamInputSource streamSource) {
2355 String openError = streamSource.getCurrentFileOpenError();
2356 if (openError != null) {
2357 throw new AwkRuntimeException(
2358 "cannot open file `" + toAwkString(getFILENAME()) + "' for reading: " + openError);
2359 }
2360 }
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376 public boolean advanceToNextFile(final InputSource source) throws IOException {
2377 Objects.requireNonNull(source, "source");
2378 if (source instanceof StreamInputSource) {
2379 return ((StreamInputSource) source).advanceToNextFile();
2380 }
2381
2382 if (syntheticFilePresented) {
2383 return false;
2384 }
2385 syntheticFilePresented = true;
2386 return true;
2387 }
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397 public boolean hasPendingInputFileError(InputSource source) {
2398 return source instanceof StreamInputSource
2399 && ((StreamInputSource) source).getCurrentFileOpenError() != null;
2400 }
2401
2402
2403
2404
2405
2406
2407
2408 private void bindConsumedRecord(InputSource source) {
2409 inputLine = null;
2410 recordState = new RecordState(source);
2411
2412 this.nr++;
2413 if (countsTowardFNR(source)) {
2414 this.fnr++;
2415 }
2416 }
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429 private static boolean countsTowardFNR(InputSource source) {
2430 return source instanceof StreamInputSource || source.isFromFilenameList();
2431 }
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444 public Object consumeInputToTarget(final InputSource source) throws IOException {
2445 Objects.requireNonNull(source, "source");
2446 activeSource = source;
2447 materializeCurrentRecord();
2448 if (!source.nextRecord()) {
2449 return null;
2450 }
2451
2452 RecordState inputState = new RecordState(source);
2453 this.nr++;
2454 if (countsTowardFNR(source)) {
2455 this.fnr++;
2456 }
2457 return new StrNum(inputState.getRecordText(), decimalSeparator);
2458 }
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469 public boolean consumeInputForEval(InputSource source) throws IOException {
2470 return consumeInput(source);
2471 }
2472
2473
2474
2475
2476
2477
2478
2479 protected void initializeInputFields(String record, List<String> preFields) {
2480 recordState = new RecordState(toInputScalar(record), preFields);
2481 }
2482
2483
2484
2485
2486
2487 public void jrtParseFields() {
2488 RecordState state = ensureRecordStateForTextMutation();
2489 state.ensureFieldsMaterialized();
2490 }
2491
2492
2493
2494
2495
2496
2497
2498 public boolean hasInputFields() {
2499 return recordState != null;
2500 }
2501
2502
2503
2504
2505
2506
2507
2508
2509 public void jrtSetNF(Object nfObj) {
2510 int nf = (int) toDouble(nfObj);
2511 if (nf < 0) {
2512 nf = 0;
2513 }
2514
2515 RecordState state = ensureRecordStateForFieldMutation();
2516 int currentNF = state.getNF();
2517
2518 if (nf < currentNF) {
2519 for (int i = currentNF; i > nf; i--) {
2520 state.removeField(i - 1);
2521 }
2522 } else if (nf > currentNF) {
2523 for (int i = currentNF + 1; i <= nf; i++) {
2524 state.addField("");
2525 }
2526 }
2527
2528 state.markRecordTextDirty();
2529 }
2530
2531
2532
2533
2534
2535
2536
2537 public Object jrtGetInputField(Object fieldnumObj) {
2538 return jrtGetInputField(parseFieldNumber(fieldnumObj));
2539 }
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549 public Object jrtGetInputField(long fieldnum) {
2550 if (fieldnum < 0 || fieldnum > Integer.MAX_VALUE) {
2551 throw new AwkRuntimeException("Field $(" + Long.valueOf(fieldnum) + ") is incorrect.");
2552 }
2553 if (recordState == null) {
2554 return BLANK;
2555 }
2556 return recordState.getField((int) fieldnum);
2557 }
2558
2559
2560
2561
2562
2563
2564
2565
2566 public String jrtSetInputField(Object valueObj, long fieldNum) {
2567 if (fieldNum > Integer.MAX_VALUE) {
2568 throw new AwkRuntimeException("Field $(" + Long.valueOf(fieldNum) + ") is incorrect.");
2569 }
2570 String value = valueObj == null ? "" : valueObj.toString();
2571 int fieldIndex = (int) fieldNum;
2572 RecordState state = ensureRecordStateForFieldMutation();
2573 if (valueObj instanceof UninitializedObject) {
2574 if (fieldIndex <= state.getNF()) {
2575 state.setField(fieldIndex - 1, "");
2576 }
2577 } else {
2578 while (state.getNF() < fieldIndex) {
2579 state.addField(BLANK);
2580 }
2581 state.setField(fieldIndex - 1, valueObj);
2582 }
2583 state.markRecordTextDirty();
2584 return value;
2585 }
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597 protected void rebuildDollarZeroFromFields() {
2598 if (recordState != null) {
2599 recordState.markRecordTextDirty();
2600 inputLine = recordState.getField(0);
2601 }
2602 }
2603
2604 private void materializeCurrentRecord() {
2605 if (recordState != null) {
2606 recordState.materialize();
2607 }
2608 }
2609
2610 private RecordState ensureRecordStateForTextMutation() {
2611 if (recordState == null) {
2612 recordState = new RecordState(inputLine, null);
2613 }
2614 return recordState;
2615 }
2616
2617 private RecordState ensureRecordStateForFieldMutation() {
2618 RecordState state = ensureRecordStateForTextMutation();
2619 state.ensureFieldsMaterialized();
2620 return state;
2621 }
2622
2623 private List<Object> sanitizeFields(List<String> rawFields) {
2624 List<Object> copy = new ArrayList<Object>(rawFields.size());
2625 for (String field : rawFields) {
2626 String value = field == null ? "" : field;
2627 copy.add(new StrNum(value, decimalSeparator));
2628 }
2629 return copy;
2630 }
2631
2632 private List<Object> splitRecordText(String recordText, String fieldSeparator) {
2633 List<Object> fields = new ArrayList<Object>();
2634 if (recordText == null || recordText.isEmpty()) {
2635 return fields;
2636 }
2637
2638 Enumeration<Object> tokenizer = splitTokenizer(recordText, fieldSeparator);
2639
2640 while (tokenizer.hasMoreElements()) {
2641 fields.add(new StrNum((String) tokenizer.nextElement(), decimalSeparator));
2642 }
2643 return fields;
2644 }
2645
2646 private static String joinFieldsWithLiteralSeparator(List<Object> fields, String separator) {
2647 StringBuilder sb = new StringBuilder();
2648 for (int i = 0; i < fields.size(); i++) {
2649 if (i > 0) {
2650 sb.append(separator);
2651 }
2652 Object field = fields.get(i);
2653 sb.append(field == null ? "" : field.toString());
2654 }
2655 return sb.toString();
2656 }
2657
2658 private String rebuildRecordTextFromFields(List<Object> fields) {
2659
2660
2661
2662 StringBuilder sb = new StringBuilder();
2663 for (int i = 0; i < fields.size(); i++) {
2664 if (i > 0) {
2665 sb.append(ofs);
2666 }
2667 Object field = fields.get(i);
2668 sb.append(field == null ? "" : toAwkString(field));
2669 }
2670 return sb.toString();
2671 }
2672
2673 private final class RecordState {
2674
2675 private final String fieldSeparatorAtRead;
2676 private final InputSource source;
2677 private String recordText;
2678 private Object recordScalar;
2679 private List<Object> fields;
2680 private boolean recordTextAvailable;
2681 private boolean fieldsAvailable;
2682 private boolean recordTextDirty;
2683 private boolean fieldsDirty;
2684 private boolean recordTextLoadedFromSource;
2685 private boolean fieldsLoadedFromSource;
2686
2687 private RecordState(InputSource source) {
2688 this(null, null, source);
2689 }
2690
2691 private RecordState(Object recordValue, List<String> rawFields) {
2692 this(recordValue, rawFields, null);
2693 }
2694
2695 private RecordState(Object recordValue, List<String> rawFields, InputSource source) {
2696 this.fieldSeparatorAtRead = fs;
2697 this.source = source;
2698 if (recordValue != null) {
2699 this.recordScalar = normalizeRecordValue(recordValue);
2700 this.recordText = this.recordScalar.toString();
2701 this.recordTextAvailable = true;
2702 } else if (rawFields == null && source == null) {
2703 this.recordScalar = "";
2704 this.recordText = "";
2705 this.recordTextAvailable = true;
2706 }
2707 if (rawFields != null) {
2708 this.fields = sanitizeFields(rawFields);
2709 this.fieldsAvailable = true;
2710 this.fieldsDirty = false;
2711 } else {
2712 this.fieldsAvailable = false;
2713 this.fieldsDirty = true;
2714 }
2715 this.recordTextDirty = false;
2716 }
2717
2718 private void ensureFieldsMaterialized() {
2719 if (fieldsAvailable && !fieldsDirty) {
2720 return;
2721 }
2722 if (!recordTextDirty) {
2723 loadFieldsFromSource();
2724 if (fieldsAvailable && !fieldsDirty) {
2725 return;
2726 }
2727 }
2728 fields = splitRecordText(getRecordText(), fieldSeparatorAtRead);
2729 fieldsAvailable = true;
2730 fieldsDirty = false;
2731 }
2732
2733 private String getRecordText() {
2734 if (!recordTextAvailable || recordTextDirty) {
2735 if (recordTextDirty) {
2736 recordText = rebuildRecordTextFromFields(fields);
2737 recordScalar = recordText;
2738 } else {
2739 loadRecordTextFromSource();
2740 if (!recordTextAvailable) {
2741 loadFieldsFromSource();
2742 if (!fieldsAvailable) {
2743 throw new IllegalStateException(
2744 "InputSource must provide record text, fields, or both after nextRecord()");
2745 }
2746 recordText = joinFieldsWithLiteralSeparator(fields, fieldSeparatorAtRead);
2747 recordScalar = new StrNum(recordText, decimalSeparator);
2748 }
2749 }
2750 recordTextAvailable = true;
2751 recordTextDirty = false;
2752 }
2753 return recordText;
2754 }
2755
2756 private int getNF() {
2757 ensureFieldsMaterialized();
2758 return fields.size();
2759 }
2760
2761 private Object getField(int fieldIndex) {
2762 if (fieldIndex == 0) {
2763 String value = getRecordText();
2764 if (recordScalar == null) {
2765 recordScalar = value;
2766 }
2767 return recordScalar;
2768 }
2769 ensureFieldsMaterialized();
2770 int zeroBasedIndex = fieldIndex - 1;
2771 if (zeroBasedIndex < 0 || zeroBasedIndex >= fields.size()) {
2772 return BLANK;
2773 }
2774 return fields.get(zeroBasedIndex);
2775 }
2776
2777 private void setField(int zeroBasedIndex, Object value) {
2778 ensureFieldsMaterialized();
2779 fields.set(zeroBasedIndex, normalizeFieldValue(value));
2780 markRecordTextDirty();
2781 }
2782
2783 private void addField(Object value) {
2784 ensureFieldsMaterialized();
2785 fields.add(normalizeFieldValue(value));
2786 markRecordTextDirty();
2787 }
2788
2789 private Object normalizeFieldValue(Object value) {
2790 if (value == null) {
2791 return "";
2792 }
2793 return value;
2794 }
2795
2796 private void removeField(int zeroBasedIndex) {
2797 ensureFieldsMaterialized();
2798 fields.remove(zeroBasedIndex);
2799 markRecordTextDirty();
2800 }
2801
2802 private void markRecordTextDirty() {
2803 recordTextDirty = true;
2804 recordTextAvailable = fieldsAvailable;
2805 recordScalar = null;
2806 }
2807
2808 private void materialize() {
2809 getRecordText();
2810 ensureFieldsMaterialized();
2811 }
2812
2813 private void loadRecordTextFromSource() {
2814 if (source == null || recordTextLoadedFromSource) {
2815 return;
2816 }
2817 recordText = source.getRecordText();
2818 recordTextAvailable = recordText != null;
2819 if (recordTextAvailable) {
2820 recordScalar = new StrNum(recordText, decimalSeparator);
2821 }
2822 recordTextLoadedFromSource = true;
2823 }
2824
2825 private void loadFieldsFromSource() {
2826 if (source == null || fieldsLoadedFromSource) {
2827 return;
2828 }
2829 List<String> rawFields = source.getFields();
2830 fieldsLoadedFromSource = true;
2831 if (rawFields != null) {
2832 fields = sanitizeFields(rawFields);
2833 fieldsAvailable = true;
2834 fieldsDirty = false;
2835 }
2836 }
2837 }
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851 public Integer jrtConsumeFileInputForGetline(String fileNameParam) {
2852 if (fileNameParam.isEmpty()) {
2853 throw new AwkRuntimeException("expression for `<' redirection has null string value");
2854 }
2855 try {
2856 if (jrtConsumeFileInput(fileNameParam)) {
2857 return ONE;
2858 }
2859 jrtInputString = "";
2860 return ZERO;
2861 } catch (IOException ioe) {
2862 jrtInputString = "";
2863 setERRNO(describeOpenFailure(fileNameParam, ioe));
2864 return MINUS_ONE;
2865 }
2866 }
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881 public Integer jrtConsumeCommandInputForGetline(String cmdString) {
2882 if (cmdString.isEmpty()) {
2883 throw new AwkRuntimeException("expression for `|' redirection has null string value");
2884 }
2885 try {
2886 if (jrtConsumeCommandInput(cmdString)) {
2887 return ONE;
2888 }
2889 jrtInputString = "";
2890 return ZERO;
2891 } catch (IOException ioe) {
2892 jrtInputString = "";
2893 setERRNO(describeIoReason(ioe));
2894 return MINUS_ONE;
2895 }
2896 }
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907 private static String describeOpenFailure(String fileNameParam, IOException ioe) {
2908 if (!isStandardInputName(fileNameParam) && !isNullDeviceName(fileNameParam)) {
2909 File file = new File(toPlatformFileName(fileNameParam));
2910 if (file.isDirectory()) {
2911 return "Is a directory";
2912 }
2913 if (!file.exists()) {
2914 return "No such file or directory";
2915 }
2916 }
2917 return describeIoReason(ioe);
2918 }
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929 static String describeIoReason(IOException ioe) {
2930 String message = ioe.getMessage();
2931 if (message == null || message.isEmpty()) {
2932 return "Permission denied";
2933 }
2934 int open = message.lastIndexOf('(');
2935 if (open >= 0 && message.endsWith(")")) {
2936 return message.substring(open + 1, message.length() - 1);
2937 }
2938 return message;
2939 }
2940
2941
2942
2943
2944
2945
2946
2947
2948 public String jrtGetInputString() {
2949 return jrtInputString;
2950 }
2951
2952
2953
2954
2955
2956
2957
2958
2959 public Map<String, PrintStream> getOutputFiles() {
2960 Map<String, PrintStream> outputFiles = new HashMap<String, PrintStream>();
2961 for (Map.Entry<String, FileOutputState> entry : getIoState().fileOutputs.entrySet()) {
2962 outputFiles.put(entry.getKey(), entry.getValue().sink.getPrintStream());
2963 }
2964 return outputFiles;
2965 }
2966
2967
2968
2969
2970
2971
2972
2973
2974 private static boolean isStandardInputName(String fileNameParam) {
2975 return DEV_STDIN.equals(fileNameParam) || DEV_FD_0.equals(fileNameParam);
2976 }
2977
2978
2979
2980
2981
2982
2983
2984
2985 private static boolean isStandardOutputName(String fileNameParam) {
2986 return DEV_STDOUT.equals(fileNameParam) || DEV_FD_1.equals(fileNameParam);
2987 }
2988
2989
2990
2991
2992
2993
2994
2995
2996 private static boolean isStandardErrorName(String fileNameParam) {
2997 return DEV_STDERR.equals(fileNameParam) || DEV_FD_2.equals(fileNameParam);
2998 }
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018 static boolean isNullDeviceName(String fileNameParam) {
3019 return DEV_NULL.equals(fileNameParam)
3020 || (IS_WINDOWS && WINDOWS_NULL_DEVICE.equalsIgnoreCase(fileNameParam));
3021 }
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042 static String toPlatformFileName(String fileNameParam) {
3043 return IS_WINDOWS && DEV_NULL.equals(fileNameParam) ? WINDOWS_NULL_DEVICE : fileNameParam;
3044 }
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054 private AwkSink getStandardErrorSink() {
3055 if (standardErrorSink == null) {
3056 standardErrorSink = new FlushingAwkSink(warning, locale);
3057 }
3058 return standardErrorSink;
3059 }
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073 protected AwkSink getFileAwkSink(String fileNameParam, boolean append) {
3074 if (isStandardOutputName(fileNameParam)) {
3075 return openSpecialOutput(fileNameParam, awkSink);
3076 }
3077 if (isStandardErrorName(fileNameParam)) {
3078 return openSpecialOutput(fileNameParam, getStandardErrorSink());
3079 }
3080 return getOrCreateFileOutputState(fileNameParam, append).sink;
3081 }
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091 private AwkSink openSpecialOutput(String fileNameParam, AwkSink sink) {
3092 getIoState().specialOutputs.put(fileNameParam, sink);
3093 return sink;
3094 }
3095
3096
3097
3098
3099
3100
3101
3102 protected AwkSink getPipeAwkSink(String cmd) {
3103 return getOrCreateProcessOutputState(cmd).sink;
3104 }
3105
3106
3107
3108
3109
3110
3111
3112 public void printDefault(Object[] values) throws IOException {
3113 awkSink.print(ofs, ors, ofmt, values);
3114 }
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124 public void printToFile(String fileNameParam, boolean append, Object[] values) throws IOException {
3125 getFileAwkSink(fileNameParam, append).print(ofs, ors, ofmt, values);
3126 }
3127
3128
3129
3130
3131
3132
3133
3134
3135 public void printToProcess(String cmd, Object[] values) throws IOException {
3136 AwkSink sink = getPipeAwkSink(cmd);
3137 sink.print(ofs, ors, ofmt, values);
3138 sink.flush();
3139 }
3140
3141
3142
3143
3144
3145
3146
3147
3148 public void printfDefault(String format, Object[] values) throws IOException {
3149 awkSink.printf(ofs, ors, ofmt, convfmt, format, values);
3150 }
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161 public String sprintf(String format, Object... values) {
3162 return awkSink.sprintf(convfmt, format, values);
3163 }
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174 public void printfToFile(String fileNameParam, boolean append, String format, Object[] values)
3175 throws IOException {
3176 AwkSink sink = getFileAwkSink(fileNameParam, append);
3177 sink.printf(ofs, ors, ofmt, convfmt, format, values);
3178 }
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188 public void printfToProcess(String cmd, String format, Object[] values) throws IOException {
3189 AwkSink sink = getPipeAwkSink(cmd);
3190 sink.printf(ofs, ors, ofmt, convfmt, format, values);
3191 sink.flush();
3192 }
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202 public PrintStream jrtGetPrintStream(String fileNameParam, boolean append) {
3203 return getFileAwkSink(fileNameParam, append).getPrintStream();
3204 }
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230 public boolean jrtConsumeFileInput(String fileNameParam) throws IOException {
3231 Map<String, PartitioningReader> fileReaders = getIoState().fileReaders;
3232 PartitioningReader pr = fileReaders.get(fileNameParam);
3233 if (pr == null) {
3234 InputStream inputStream = isStandardInputName(fileNameParam) ?
3235 standardInput : new FileInputStream(toPlatformFileName(fileNameParam));
3236 pr = new PartitioningReader(
3237 new InputStreamReader(inputStream, StandardCharsets.UTF_8),
3238 this.rs);
3239 fileReaders.put(fileNameParam, pr);
3240 }
3241
3242 String recordText = pr.readRecord();
3243 if (recordText == null) {
3244 return false;
3245 }
3246 jrtInputString = recordText;
3247 return true;
3248 }
3249
3250 private static Process spawnProcess(String cmd, boolean inheritStandardInput) throws IOException {
3251 ProcessBuilder pb = IS_WINDOWS
3252
3253 ? new ProcessBuilder("cmd.exe", "/c", cmd)
3254
3255 : new ProcessBuilder("/bin/sh", "-c", cmd);
3256 if (inheritStandardInput) {
3257 pb.redirectInput(ProcessBuilder.Redirect.INHERIT);
3258 }
3259 return pb.start();
3260 }
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281 public void setSpawnedProcessesInheritStandardInput(boolean inherit) {
3282 this.spawnedProcessesInheritStandardInput = inherit;
3283 }
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293 private boolean spawnedProcessInheritsStandardInput() {
3294 return spawnedProcessesInheritStandardInput;
3295 }
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316 public boolean jrtConsumeCommandInput(String cmd) throws IOException {
3317 CommandInputState commandInput = getOrCreateCommandInputState(cmd);
3318 String recordText = commandInput.reader.readRecord();
3319 if (recordText == null) {
3320 return false;
3321 }
3322 jrtInputString = recordText;
3323 return true;
3324 }
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335 public PrintStream jrtSpawnForOutput(String cmd) {
3336 return getPipeAwkSink(cmd).getPrintStream();
3337 }
3338
3339 private FileOutputState getOrCreateFileOutputState(String fileNameParam, boolean append) {
3340 IoState state = getIoState();
3341 FileOutputState outputState = state.fileOutputs.get(fileNameParam);
3342 if (outputState == null) {
3343 outputState = createFileOutputState(fileNameParam, append);
3344 state.fileOutputs.put(fileNameParam, outputState);
3345 }
3346 return outputState;
3347 }
3348
3349 private FileOutputState createFileOutputState(String fileNameParam, boolean append) {
3350 try {
3351 PrintStream printStream = new PrintStream(
3352 new FileOutputStream(toPlatformFileName(fileNameParam), append),
3353 true,
3354 StandardCharsets.UTF_8.name());
3355 return new FileOutputState(new OutputStreamAwkSink(printStream, locale));
3356 } catch (IOException ioe) {
3357 throw new AwkRuntimeException("Cannot open " + fileNameParam + " for writing: " + ioe);
3358 }
3359 }
3360
3361 private CommandInputState getOrCreateCommandInputState(String cmd) throws IOException {
3362 IoState state = getIoState();
3363 CommandInputState commandInput = state.commandInputs.get(cmd);
3364 if (commandInput == null) {
3365 commandInput = createCommandInputState(cmd);
3366 state.commandInputs.put(cmd, commandInput);
3367 }
3368 return commandInput;
3369 }
3370
3371 private CommandInputState createCommandInputState(String cmd) throws IOException {
3372 Process process = null;
3373 Thread errorPump = null;
3374 try {
3375
3376
3377 boolean inheritStandardInput = spawnedProcessInheritsStandardInput();
3378 process = spawnProcess(cmd, inheritStandardInput);
3379 if (!inheritStandardInput) {
3380 process.getOutputStream().close();
3381 }
3382 errorPump = DataPump.dumpAndReturnThread(cmd + " stderr", process.getErrorStream(), error);
3383 PartitioningReader reader = new PartitioningReader(
3384 new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8),
3385 this.rs);
3386 return new CommandInputState(process, reader, errorPump);
3387 } catch (IOException ioe) {
3388 if (process != null) {
3389 process.destroy();
3390 }
3391 joinDataPump(errorPump);
3392 throw ioe;
3393 }
3394 }
3395
3396 private ProcessOutputState getOrCreateProcessOutputState(String cmd) {
3397 IoState state = getIoState();
3398 ProcessOutputState outputState = state.processOutputs.get(cmd);
3399 if (outputState == null) {
3400 outputState = createProcessOutputState(cmd);
3401 state.processOutputs.put(cmd, outputState);
3402 }
3403 return outputState;
3404 }
3405
3406 private ProcessOutputState createProcessOutputState(String cmd) {
3407 Process process = null;
3408 Thread stderrPump = null;
3409 Thread stdoutPump = null;
3410 PrintStream processOutput = null;
3411 try {
3412 processOutput = awkSink.getPrintStream();
3413
3414 process = spawnProcess(cmd, false);
3415 stderrPump = DataPump.dumpAndReturnThread(cmd + " stderr", process.getErrorStream(), error);
3416 stdoutPump = DataPump.dumpAndReturnThread(cmd + " stdout", process.getInputStream(), processOutput);
3417 PrintStream processInput = new PrintStream(process.getOutputStream(), true, StandardCharsets.UTF_8.name());
3418 return new ProcessOutputState(
3419 process,
3420 new OutputStreamAwkSink(processInput, locale),
3421 processOutput,
3422 stdoutPump,
3423 stderrPump);
3424 } catch (IOException ioe) {
3425 if (process != null) {
3426 process.destroy();
3427 }
3428 joinDataPump(stdoutPump);
3429 joinDataPump(stderrPump);
3430 throw new AwkRuntimeException("Can't spawn " + cmd + ": " + ioe);
3431 }
3432 }
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449 public Integer jrtClose(String fileNameParam) {
3450 boolean b1 = jrtCloseFileReader(fileNameParam);
3451 boolean b2 = jrtCloseCommandReader(fileNameParam);
3452 boolean b3 = jrtCloseOutputFile(fileNameParam);
3453 boolean b4 = jrtCloseOutputStream(fileNameParam);
3454 boolean b5 = jrtCloseSpecialOutput(fileNameParam);
3455
3456 return (b1 || b2 || b3 || b4 || b5) ? ZERO : MINUS_ONE;
3457 }
3458
3459
3460
3461
3462
3463
3464 public void jrtCloseAll() {
3465 IoState state = ioState;
3466 if (state == null) {
3467 return;
3468 }
3469 Set<String> set = new HashSet<String>();
3470 for (String s : state.fileReaders.keySet()) {
3471 set.add(s);
3472 }
3473 for (String s : state.commandInputs.keySet()) {
3474 set.add(s);
3475 }
3476 for (String s : state.fileOutputs.keySet()) {
3477 set.add(s);
3478 }
3479 for (String s : state.processOutputs.keySet()) {
3480 set.add(s);
3481 }
3482 for (String s : state.specialOutputs.keySet()) {
3483 set.add(s);
3484 }
3485 for (String s : set) {
3486 jrtClose(s);
3487 }
3488 }
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502 private boolean jrtCloseSpecialOutput(String fileNameParam) {
3503 IoState state = ioState;
3504 if (state == null) {
3505 return false;
3506 }
3507 AwkSink sink = state.specialOutputs.remove(fileNameParam);
3508 if (sink == null) {
3509 return false;
3510 }
3511 try {
3512 sink.flush();
3513 return true;
3514 } catch (IOException ioe) {
3515 setERRNO(ioe.toString());
3516 return false;
3517 }
3518 }
3519
3520 private boolean jrtCloseOutputFile(String fileNameParam) {
3521 IoState state = ioState;
3522 if (state == null) {
3523 return false;
3524 }
3525 FileOutputState outputState = state.fileOutputs.remove(fileNameParam);
3526 if (outputState != null) {
3527 outputState.sink.getPrintStream().close();
3528 }
3529 return outputState != null;
3530 }
3531
3532 private boolean jrtCloseOutputStream(String cmd) {
3533 IoState state = ioState;
3534 if (state == null) {
3535 return false;
3536 }
3537 ProcessOutputState outputState = state.processOutputs.remove(cmd);
3538 if (outputState == null) {
3539 return false;
3540 }
3541 outputState.sink.getPrintStream().close();
3542 try {
3543
3544
3545 outputState.process.waitFor();
3546 outputState.process.exitValue();
3547 } catch (InterruptedException ie) {
3548 Thread.currentThread().interrupt();
3549 outputState.process.destroyForcibly();
3550 throw new AwkRuntimeException(
3551 "Caught exception while waiting for process exit: " + ie);
3552 } finally {
3553 joinDataPump(outputState.stdoutPump);
3554 joinDataPump(outputState.stderrPump);
3555 outputState.processOutput.flush();
3556 error.flush();
3557 }
3558 return true;
3559 }
3560
3561 private boolean jrtCloseFileReader(String fileNameParam) {
3562 IoState state = ioState;
3563 if (state == null) {
3564 return false;
3565 }
3566 PartitioningReader pr = state.fileReaders.get(fileNameParam);
3567 if (pr == null) {
3568 return false;
3569 }
3570 state.fileReaders.remove(fileNameParam);
3571 if (isStandardInputName(fileNameParam)) {
3572
3573
3574
3575
3576
3577 return true;
3578 }
3579 try {
3580 pr.close();
3581 return true;
3582 } catch (IOException ioe) {
3583 return false;
3584 }
3585 }
3586
3587 private boolean jrtCloseCommandReader(String cmd) {
3588 IoState state = ioState;
3589 if (state == null) {
3590 return false;
3591 }
3592 CommandInputState commandInput = state.commandInputs.remove(cmd);
3593 if (commandInput == null) {
3594 return false;
3595 }
3596 try {
3597 commandInput.reader.close();
3598 try {
3599
3600
3601 commandInput.process.waitFor();
3602 commandInput.process.exitValue();
3603 } catch (InterruptedException ie) {
3604 Thread.currentThread().interrupt();
3605 commandInput.process.destroyForcibly();
3606 throw new AwkRuntimeException(
3607 "Caught exception while waiting for process exit: " + ie);
3608 }
3609 return true;
3610 } catch (IOException ioe) {
3611 return false;
3612 } finally {
3613 joinDataPump(commandInput.errorPump);
3614 error.flush();
3615 }
3616 }
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632 public Integer jrtSystem(String cmd) {
3633 try {
3634 PrintStream processOutput = awkSink.getPrintStream();
3635
3636
3637 boolean inheritStandardInput = spawnedProcessInheritsStandardInput();
3638 Process p = spawnProcess(cmd, inheritStandardInput);
3639 if (!inheritStandardInput) {
3640 p.getOutputStream().close();
3641 }
3642 Thread errorPump = DataPump.dumpAndReturnThread(cmd + " stderr", p.getErrorStream(), error);
3643 Thread outputPump = DataPump.dumpAndReturnThread(cmd + " stdout", p.getInputStream(), processOutput);
3644 boolean interrupted = false;
3645 int retcode;
3646 while (true) {
3647 try {
3648 retcode = p.waitFor();
3649 break;
3650 } catch (InterruptedException ie) {
3651
3652 interrupted = true;
3653 }
3654 }
3655 joinDataPump(outputPump);
3656 joinDataPump(errorPump);
3657 processOutput.flush();
3658 error.flush();
3659 if (interrupted) {
3660 Thread.currentThread().interrupt();
3661 }
3662 return Integer.valueOf(retcode);
3663 } catch (IOException ioe) {
3664 return MINUS_ONE;
3665 }
3666 }
3667
3668 private static void joinDataPump(Thread pump) {
3669 if (pump == null) {
3670 return;
3671 }
3672 boolean interrupted = false;
3673 while (true) {
3674 try {
3675 pump.join();
3676 break;
3677 } catch (InterruptedException ie) {
3678 interrupted = true;
3679 }
3680 }
3681 if (interrupted) {
3682 Thread.currentThread().interrupt();
3683 }
3684 }
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697 public static String sprintfNoCatch(Locale locale, String fmtArg, Object... arr) throws IllegalFormatException {
3698 return String.format(locale, fmtArg, arr);
3699 }
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710 public static void printfNoCatch(Locale locale, String fmtArg, Object... arr) {
3711 System.out.print(sprintfNoCatch(locale, fmtArg, arr));
3712 }
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724 public static void printfNoCatch(PrintStream ps, Locale locale, String fmtArg, Object... arr) {
3725 ps.print(sprintfNoCatch(locale, fmtArg, arr));
3726 }
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737 public static String substr(Object startposObj, String str) {
3738 int startpos = (int) toDouble(startposObj);
3739 if (startpos <= 0) {
3740 throw new AwkRuntimeException("2nd arg to substr must be a positive integer");
3741 }
3742 if (startpos > str.length()) {
3743 return "";
3744 } else {
3745 return str.substring(startpos - 1);
3746 }
3747 }
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759 public static String substr(Object sizeObj, Object startposObj, String str) {
3760 int startpos = (int) toDouble(startposObj);
3761 if (startpos <= 0) {
3762 throw new AwkRuntimeException("2nd arg to substr must be a positive integer");
3763 }
3764 if (startpos > str.length()) {
3765 return "";
3766 }
3767 int size = (int) toDouble(sizeObj);
3768 if (size < 0) {
3769 throw new AwkRuntimeException("3nd arg to substr must be a non-negative integer");
3770 }
3771 if (startpos + size > str.length()) {
3772 return str.substring(startpos - 1);
3773 } else {
3774 return str.substring(startpos - 1, startpos + size - 1);
3775 }
3776 }
3777
3778
3779
3780
3781
3782
3783
3784
3785 public static int timeSeed() {
3786 long l = new Date().getTime();
3787 long l2 = l % (1000 * 60 * 60 * 24);
3788 int seed = (int) l2;
3789 return seed;
3790 }
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800 public static BSDRandom newRandom(int seed) {
3801 return new BSDRandom(seed);
3802 }
3803
3804
3805
3806
3807
3808
3809
3810
3811 public void applyRS(Object rsObj) {
3812 if (activeSource instanceof StreamInputSource) {
3813 ((StreamInputSource) activeSource).setRecordSeparator(rsObj.toString());
3814 }
3815 }
3816 }