/
nqp.ops
4509 lines (3640 loc) · 138 KB
/
nqp.ops
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_OPS_PREAMBLE
#include <errno.h>
/* Parroty includes. */
#include "parrot/parrot.h"
#include "parrot/extend.h"
#include "parrot/dynext.h"
#include "parrot/io.h"
#include "pmc/pmc_filehandle.h"
/* 6modely includes. */
#include "../6model/sixmodelobject.h"
#include "../6model/repr_registry.h"
#include "../6model/reprs/NFA.h"
#include "../6model/serialization_context.h"
#include "../6model/containers.h"
#include "../guts/multi_dispatch.h"
#include "../pmc/pmc_nqplexinfo.h"
#include "pmc_sub.h"
/* SHA1 algorithm. */
#include "../../../../3rdparty/sha1/sha1.h"
#if PARROT_HAS_ICU
# include <unicode/uchar.h>
#endif
/* Did we do the dynop setup yet?
* XXX Relies on this happening once in a single thread at startup. */
static INTVAL initialized = 0;
/* Cached type IDs. */
static INTVAL stable_id = 0;
static INTVAL smo_id = 0;
static INTVAL disp_id = 0;
static INTVAL qrpa_id = 0;
static INTVAL ohash_id = 0;
/* Built-in meta-objects. */
static PMC *KnowHOW = NULL;
static PMC *KnowHOWAttribute = NULL;
/* FileHandle PMC for nqpevent */
static PMC *nqpevent_fh = NULL;
static INTVAL nqpdebflags_i = 0;
/* Serialization context upside-down stack (element 0 is the latest, new entries
* unshifted). Tracks the SC (if any) that we are currently in; stack because we
* may have multiple on the go due to compiling nested module dependencies. */
PMC *compiling_scs = NULL;
/* Disables the SC write barrier temporarily. Zero is enabled, otherwise it's the
* number of nested enable/disable we are in. */
INTVAL sc_write_barrier_off_depth = 0;
/* Empty hash, used in deconstruct op. */
static PMC *empty_hash = NULL;
/* SC write barrier for objects. */
static void SC_write_barrier_obj(PARROT_INTERP, PMC *obj) {
if (!sc_write_barrier_off_depth && VTABLE_get_bool(interp, compiling_scs)) {
PMC *comp_sc = VTABLE_get_pmc_keyed_int(interp, compiling_scs, 0);
if (SC_PMC(obj) != comp_sc) {
SC_repossess_object(interp, comp_sc, SC_PMC(obj), obj);
SC_PMC(obj) = comp_sc;
/*printf("SC OBJECT WRITE BARRIER HIT (%s)\n",
Parrot_str_cstring(interp, VTABLE_name(interp, obj)));*/
}
}
}
/* SC write barrier for STables. */
static void SC_write_barrier_st(PARROT_INTERP, STable *st) {
if (!sc_write_barrier_off_depth && VTABLE_get_bool(interp, compiling_scs)) {
PMC *comp_sc = VTABLE_get_pmc_keyed_int(interp, compiling_scs, 0);
if (st->sc != comp_sc) {
SC_repossess_stable(interp, comp_sc, st->sc, st->stable_pmc);
st->sc = comp_sc;
/*printf("SC STABLE WRITE BARRIER HIT (%s)\n",
Parrot_str_cstring(interp, VTABLE_name(interp, st->WHAT)));*/
}
}
}
/* Test for something being a list (RPA or QRPA). */
static INTVAL
nqp_islist(PMC *pmc) {
INTVAL type = pmc->vtable->base_type;
return (INTVAL)(type == qrpa_id || type == enum_class_ResizablePMCArray
|| type == enum_class_ResizableStringArray);
}
/* Test for something being a hash. */
static INTVAL
nqp_ishash(PMC *pmc) {
INTVAL type = pmc->vtable->base_type;
return (INTVAL)(type == enum_class_Hash || type == ohash_id);
}
/* This public-domain C quick sort implementation by Darel Rex Finley. */
static INTVAL
revquicksort(INTVAL *arr, INTVAL elements) {
#define MAX_LEVELS 100
INTVAL piv, beg[MAX_LEVELS], end[MAX_LEVELS], i = 0, L, R ;
beg[0] = 0;
end[0] = elements;
while (i >= 0) {
L = beg[i];
R = end[i] - 1;
if (L < R) {
piv = arr[L];
if (i == MAX_LEVELS - 1)
return 0;
while (L < R) {
while (arr[R] <= piv && L < R)
R--;
if (L < R)
arr[L++] = arr[R];
while (arr[L] >= piv && L < R)
L++;
if (L < R)
arr[R--] =arr[L];
}
arr[L] = piv;
beg[i+1] = L + 1;
end[i+1] = end[i];
end[i++] = L;
}
else {
i--;
}
}
return 1;
}
/* Does a run of the NFA. Produces a list of integers indicating the
* chosen ordering. */
static INTVAL * nqp_nfa_run(PARROT_INTERP, NFABody *nfa, STRING *target, INTVAL offset, INTVAL *total_fates_out) {
INTVAL eos = Parrot_str_length(interp, target);
INTVAL gen = 1;
INTVAL numcur = 0;
INTVAL numnext = 0;
INTVAL *done, *fates, *curst, *nextst, *longlit;
INTVAL i, fate_arr_len, num_states, total_fates, prev_fates, usedlonglit;
INTVAL orig_offset = offset;
/* Allocate "done states", "current states" and "next states" arrays. */
num_states = nfa->num_states;
done = (INTVAL *)mem_sys_allocate_zeroed((num_states + 1) * sizeof(INTVAL));
curst = (INTVAL *)mem_sys_allocate_zeroed((num_states + 1) * sizeof(INTVAL));
nextst = (INTVAL *)mem_sys_allocate_zeroed((num_states + 1) * sizeof(INTVAL));
/* Allocate fates array. */
fate_arr_len = 1 + VTABLE_elements(interp, nfa->fates);
fates = (INTVAL *)mem_sys_allocate(sizeof(INTVAL) * fate_arr_len);
total_fates = 0;
longlit = (INTVAL *)mem_sys_allocate(sizeof(INTVAL) * fate_arr_len);
usedlonglit = 0;
/* fprintf(stderr, "nqp_nfa_run offset %d fates %d\n", offset, fate_arr_len); */
nextst[numnext++] = 1;
while (numnext && offset <= eos) {
/* Swap next and current */
INTVAL *temp = curst;
curst = nextst;
nextst = temp;
numcur = numnext;
numnext = 0;
/* Save how many fates we have before this position is considered. */
prev_fates = total_fates;
while (numcur) {
NFAStateInfo *edge_info;
INTVAL edge_info_elems;
INTVAL st = curst[--numcur];
if (st <= num_states) {
if (done[st] == gen)
continue;
done[st] = gen;
}
edge_info = nfa->states[st - 1];
edge_info_elems = nfa->num_state_edges[st - 1];
for (i = 0; i < edge_info_elems; i++) {
INTVAL act = edge_info[i].act;
INTVAL to = edge_info[i].to;
if (act <= EDGE_EPSILON) {
if (act < 0) {
/* fprintf(stderr, "neg act %d\n", act); */
act &= 0xff;
}
if (act == EDGE_FATE) {
/* Crossed a fate edge. Check if we already saw this, and
* if so bump the entry we already saw. */
INTVAL arg = edge_info[i].arg.i;
INTVAL j;
INTVAL found_fate = 0;
arg &= 0xffffff; /* remove after rebootstrap */
for (j = 0; j < total_fates; j++) {
if (found_fate)
fates[j - 1] = fates[j];
if (fates[j] == arg) {
found_fate = 1;
if (j < prev_fates)
prev_fates--;
}
}
if (arg < usedlonglit)
arg -= longlit[arg] << 24;
/* fprintf(stderr, "fate edge %llx\n", (long long unsigned int)act); */
if (found_fate) {
fates[total_fates - 1] = arg;
}
else {
if (total_fates >= fate_arr_len) {
fate_arr_len = total_fates + 1;
fates = (INTVAL *)mem_sys_realloc(fates,
sizeof(INTVAL) * fate_arr_len);
}
fates[total_fates++] = arg;
}
continue;
}
else if (act == EDGE_EPSILON && to <= num_states && done[to] != gen) {
if (to)
curst[numcur++] = to;
continue;
}
}
if (offset >= eos) {
/* Can't match, so drop state. */
continue;
}
switch (act) {
case EDGE_CODEPOINT: {
UINTVAL arg = edge_info[i].arg.i;
if (STRING_ord(interp, target, offset) == arg) {
nextst[numnext++] = to;
/* fprintf(stderr, "codepoint %c\n", arg); */
}
continue;
}
case EDGE_CODEPOINT_LL: {
UINTVAL arg = edge_info[i].arg.i;
if (STRING_ord(interp, target, offset) == arg) {
INTVAL fate = (edge_info[i].act >> 8) & 0xfffff;
nextst[numnext++] = to;
while (usedlonglit <= fate)
longlit[usedlonglit++] = 0;
longlit[fate] = offset - orig_offset;
/* fprintf(stderr, "codepoint_ll %c fate %d\n", arg, fate); */
}
continue;
}
case EDGE_CODEPOINT_NEG: {
UINTVAL arg = edge_info[i].arg.i;
if (STRING_ord(interp, target, offset) != arg)
nextst[numnext++] = to;
continue;
}
case EDGE_CHARCLASS: {
INTVAL arg = edge_info[i].arg.i;
if (Parrot_str_is_cclass(interp, arg, target, offset))
nextst[numnext++] = to;
continue;
}
case EDGE_CHARCLASS_NEG: {
INTVAL arg = edge_info[i].arg.i;
if (!Parrot_str_is_cclass(interp, arg, target, offset))
nextst[numnext++] = to;
continue;
}
case EDGE_CHARLIST: {
STRING *arg = edge_info[i].arg.s;
STRING *chr = STRING_substr(interp, target, offset, 1);
if (STRING_index(interp, arg, chr, 0) >= 0)
nextst[numnext++] = to;
continue;
}
case EDGE_CHARLIST_NEG: {
STRING *arg = edge_info[i].arg.s;
STRING *chr = STRING_substr(interp, target, offset, 1);
if (STRING_index(interp, arg, chr, 0) < 0)
nextst[numnext++] = to;
continue;
}
case EDGE_CODEPOINT_I: {
UINTVAL uc_arg = edge_info[i].arg.uclc.uc;
UINTVAL lc_arg = edge_info[i].arg.uclc.lc;
UINTVAL ord = STRING_ord(interp, target, offset);
if (ord == lc_arg || ord == uc_arg)
nextst[numnext++] = to;
continue;
}
case EDGE_CODEPOINT_I_LL: {
UINTVAL uc_arg = edge_info[i].arg.uclc.uc;
UINTVAL lc_arg = edge_info[i].arg.uclc.lc;
UINTVAL ord = STRING_ord(interp, target, offset);
if (ord == lc_arg || ord == uc_arg) {
INTVAL fate = (edge_info[i].act >> 8) & 0xfffff;
nextst[numnext++] = to;
while (usedlonglit <= fate)
longlit[usedlonglit++] = 0;
longlit[fate] = offset - orig_offset;
}
continue;
}
case EDGE_CODEPOINT_I_NEG: {
UINTVAL uc_arg = edge_info[i].arg.uclc.uc;
UINTVAL lc_arg = edge_info[i].arg.uclc.lc;
UINTVAL ord = STRING_ord(interp, target, offset);
if (ord != lc_arg && ord != uc_arg)
nextst[numnext++] = to;
continue;
}
case EDGE_CHARRANGE: {
UINTVAL uc_arg = edge_info[i].arg.uclc.uc;
UINTVAL lc_arg = edge_info[i].arg.uclc.lc;
UINTVAL ord = STRING_ord(interp, target, offset);
if (ord >= lc_arg && ord <= uc_arg)
nextst[numnext++] = to;
continue;
}
case EDGE_CHARRANGE_NEG: {
UINTVAL uc_arg = edge_info[i].arg.uclc.uc;
UINTVAL lc_arg = edge_info[i].arg.uclc.lc;
UINTVAL ord = STRING_ord(interp, target, offset);
if (ord < lc_arg || ord > uc_arg)
nextst[numnext++] = to;
continue;
}
}
}
}
/* Move to next character and generation. */
offset++;
gen++;
/* If we got multiple fates at this offset, sort them by the
* literal length and declaration order (both encoded in fate number).
* The high 40 bits of the fate encodes literal length, while the low
* 24 bits encode fate. Both want to be descending order. */
if (total_fates - prev_fates > 1) {
INTVAL char_fates = total_fates - prev_fates;
revquicksort(&fates[total_fates - char_fates], char_fates);
}
}
mem_sys_free(done);
mem_sys_free(curst);
mem_sys_free(nextst);
/* strip any literal lengths, leaving only fates */
if (usedlonglit) {
/* fprintf(stderr, "Final\n"); */
for (i = 0; i < total_fates; i++) {
/* fprintf(stderr, "\t%llx\n", (long long unsigned int)fates[i]); */
fates[i] &= 0xffffff;
}
}
*total_fates_out = total_fates;
return fates;
}
/* Constants for values the type field above may have. */
#define BIND_VAL_INT 1
#define BIND_VAL_NUM 2
#define BIND_VAL_STR 3
#define BIND_VAL_OBJ 4
/* The current dispatcher, for the next thing that wants one to take.
* Note, should really be per thread. */
static PMC *current_dispatcher = NULL;
PARROT_CAN_RETURN_NULL
PARROT_WARN_UNUSED_RESULT
static PMC* sub_find_pad(PARROT_INTERP, ARGIN(STRING *lex_name), ARGIN(PMC *ctx))
{
ASSERT_ARGS(Parrot_sub_find_pad)
while (1) {
PMC * const lex_pad = Parrot_pcc_get_lex_pad(interp, ctx);
PMC * outer = Parrot_pcc_get_outer_ctx(interp, ctx);
if (PMC_IS_NULL(outer))
return lex_pad;
PARROT_ASSERT(outer->vtable->base_type == enum_class_CallContext);
if (!PMC_IS_NULL(lex_pad))
if (VTABLE_exists_keyed_str(interp, lex_pad, lex_name))
return lex_pad;
ctx = outer;
}
}
/* the Parrot env variables abstraction doesn't support traversing through all the env variables so we need this ifdef*/
#ifndef WIN32
# ifdef __APPLE_CC__
# include <crt_externs.h>
# define environ (*_NSGetEnviron())
# else /* !__APPLE_CC__ */
extern char **environ;
# endif /* __APPLE_CC__ */
#endif /* !WIN32 */
/* we have our own Run_OS_Command as the parrot one doesn't support passing env variables */
#ifdef WIN32
#include <windows.h>
#include <process.h>
static char * pack_env_hash(Parrot_Interp interp, PMC* hash_pmc) {
Hash *hash = (Hash *)VTABLE_get_pointer(interp, hash_pmc);
STRING *equal = Parrot_str_new_constant(interp, "=");
STRING *key, *value, *env_var, *env_var_with_null;
STRING *packed = Parrot_str_new_constant(interp, "");
STRING *null = Parrot_str_new(interp, "\0", 1);
/* Parrot_hash_value_to_string is not exported*/
parrot_hash_iterate(hash,
key = (STRING *)_bucket->key;
value = VTABLE_get_string_keyed_str(interp, hash_pmc, key);
env_var = Parrot_str_concat(interp, key, Parrot_str_concat(interp, equal, value));
env_var_with_null = Parrot_str_concat(interp, env_var, null);
packed = Parrot_str_concat(interp, packed, env_var_with_null);
);
return Parrot_str_to_cstring(interp, packed);
}
#endif
static char **pack_arg_array(Parrot_Interp interp, PMC* array_pmc) {
INTVAL array_size = VTABLE_elements(interp, array_pmc);
char **packed = (char **)mem_sys_allocate((array_size + 1) * sizeof(char *));
INTVAL i = 0;
if (array_size > 0) {
for (i = 0; i < array_size; i++) {
PMC *pmc = VTABLE_get_pmc_keyed_int(interp, array_pmc, i);
STRING *str = (STRING *)VTABLE_get_string(interp, pmc);
packed[i] = Parrot_str_to_cstring(interp, str);
}
}
packed[i] = NULL;
return packed;
}
#ifdef WIN32
static int is_space(unsigned char c) {
return c == 0x09 || c == 0x0A || c == 0x0B
|| c == 0x0C || c == 0x0D || c == 0x20
|| c == 0x85;
}
static char *find_next_space(const char *s) {
short in_quotes = 0;
while (*s) {
/* ignore doubled backslashes, or backslash+quote */
if (*s == '\\' && (s[1] == '\\' || s[1] == '"')) {
s += 2;
}
/* keep track of when we're within quotes */
else if (*s == '"') {
s++;
in_quotes = !in_quotes;
}
/* break it up only at spaces that aren't in quotes */
else if (!in_quotes && is_space(*s))
return (char*)s;
else
s++;
}
return (char*)s;
}
/* Autoquoting command-line arguments for nqp::spawn. */
static char *create_command_line(const char *const *args) {
int index, argc;
char *cmd, *ptr;
const char *arg;
size_t len = 0;
short bat_file = 0;
short cmd_shell = 0;
short dumb_shell = 0;
short extra_quotes = 0;
short quote_next = 0;
char *cname = (char*)args[0];
size_t clen = strlen(cname);
/* The NT cmd.exe shell has the following peculiarity that needs to be
* worked around. It strips a leading and trailing dquote when any
* of the following is true:
* 1. the /S switch was used
* 2. there are more than two dquotes
* 3. there is a special character from this set: &<>()@^|
* 4. no whitespace characters within the two dquotes
* 5. string between two dquotes isn't an executable file
* To work around this, we always add a leading and trailing dquote
* to the string, if the first argument is either "cmd.exe" or "cmd",
* and there were at least two or more arguments passed to cmd.exe
* (not including switches).
* XXX the above rules (from "cmd /?") don't seem to be applied
* always, making for the convolutions below :-(
*/
if (cname) {
if (!clen)
clen = strlen(cname);
if (clen > 4
&& (stricmp(&cname[clen-4], ".bat") == 0
|| (stricmp(&cname[clen-4], ".cmd") == 0))) {
bat_file = 1;
len += 3;
}
else {
char *exe = strrchr(cname, '/');
char *exe2 = strrchr(cname, '\\');
if (exe2 > exe)
exe = exe2;
if (exe)
++exe;
else
exe = cname;
if (stricmp(exe, "cmd.exe") == 0 || stricmp(exe, "cmd") == 0) {
cmd_shell = 1;
len += 3;
}
else if (stricmp(exe, "command.com") == 0
|| stricmp(exe, "command") == 0) {
dumb_shell = 1;
}
}
}
for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
size_t curlen = strlen(arg);
if (!(arg[0] == '"' && arg[curlen-1] == '"'))
len += 2; /* assume quoting needed (worst case) */
len += curlen + 1;
}
argc = index;
cmd = (char *)mem_sys_allocate(len * sizeof(char));
ptr = cmd;
if (bat_file) {
*ptr++ = '"';
extra_quotes = 1;
}
for (index = 0; (arg = (char*)args[index]) != NULL; ++index) {
short do_quote = 0;
size_t curlen = strlen(arg);
/* we want to protect empty arguments and ones with spaces with
* dquotes, but only if they aren't already there */
if (!dumb_shell) {
if (!curlen) {
do_quote = 1;
}
else if (quote_next) {
/* see if it really is multiple arguments pretending to
* be one and force a set of quotes around it */
if (*find_next_space(arg))
do_quote = 1;
}
else if (!(arg[0] == '"' && curlen > 1 && arg[curlen-1] == '"')) {
size_t i = 0;
while (i < curlen) {
/* is space */
if (is_space(arg[i])) {
do_quote = 1;
}
else if (arg[i] == '"') {
do_quote = 0;
break;
}
i++;
}
}
}
if (do_quote)
*ptr++ = '"';
strcpy(ptr, arg);
ptr += curlen;
if (do_quote)
*ptr++ = '"';
if (args[index+1])
*ptr++ = ' ';
if (!extra_quotes
&& cmd_shell
&& curlen >= 2
&& *arg == '/' /* see if arg is "/c", "/x/c", "/x/d/c" etc. */
&& stricmp(arg+curlen-2, "/c") == 0) {
/* is there a next argument? */
if (args[index+1]) {
/* are there two or more next arguments? */
if (args[index+2]) {
*ptr++ = '"';
extra_quotes = 1;
}
else {
/* single argument, force quoting if it has spaces */
quote_next = 1;
}
}
}
}
if (extra_quotes)
*ptr++ = '"';
*ptr = '\0';
return cmd;
}
static PIOHANDLE Run_OS_Command_Piped(PARROT_INTERP, PMC *command, PMC *env_hash, INTVAL flags,
INTVAL *pid, INTVAL *status) {
HANDLE current = GetCurrentProcess();
HANDLE hnull = INVALID_HANDLE_VALUE;
HANDLE hread = INVALID_HANDLE_VALUE;
HANDLE hwrite = INVALID_HANDLE_VALUE;
HANDLE hchild = INVALID_HANDLE_VALUE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
SECURITY_ATTRIBUTES sec;
const char *env = pack_env_hash(interp, env_hash);
const char *const *argv = pack_arg_array(interp, command);
const char *cmd = create_command_line(argv);
PIOHANDLE os_handle;
pi.hThread = INVALID_HANDLE_VALUE;
pi.hProcess = INVALID_HANDLE_VALUE;
sec.nLength = sizeof sec;
sec.lpSecurityDescriptor = NULL;
sec.bInheritHandle = TRUE;
si.cb = sizeof si;
GetStartupInfo(&si);
si.dwFlags = STARTF_USESTDHANDLES;
if (CreatePipe(&hread, &hwrite, NULL, 0) == 0)
goto fail;
if (DuplicateHandle(current, flags & PARROT_EXEC_STDOUT ? hwrite : hread,
current, &hchild,
0, TRUE,
DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)
== 0)
goto fail;
if (hchild == INVALID_HANDLE_VALUE)
goto fail;
if (flags & PARROT_EXEC_STDOUT) {
/* Redirect input to NULL. This is to avoid
* interferences in case both the child and
* the parent tries to read from stdin.
* May be unnecessary or even interfere
* with valid usages, need more feedback. */
hnull = CreateFile("NUL", GENERIC_READ|GENERIC_WRITE,
0, &sec, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hnull == INVALID_HANDLE_VALUE)
goto fail;
si.hStdInput = hnull;
si.hStdOutput = hchild;
si.hStdError = hchild;
}
else {
si.hStdInput = hchild;
}
if (CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, env, NULL, &si, &pi) == 0)
goto fail;
if (flags & PARROT_EXEC_STDOUT) {
os_handle = hread;
CloseHandle(hwrite);
}
else {
os_handle = hwrite;
CloseHandle(hread);
}
Parrot_str_free_cstring(cmd);
CloseHandle(pi.hThread);
*pid = (INTVAL)pi.hProcess;
return os_handle;
fail:
if (cmd != NULL)
Parrot_str_free_cstring(cmd);
if (hnull != INVALID_HANDLE_VALUE)
CloseHandle(hnull);
if (hread != INVALID_HANDLE_VALUE)
CloseHandle(hread);
if (hwrite != INVALID_HANDLE_VALUE)
CloseHandle(hwrite);
if (hchild != INVALID_HANDLE_VALUE)
CloseHandle(hchild);
if (pi.hThread != INVALID_HANDLE_VALUE)
CloseHandle(pi.hThread);
if (pi.hProcess != INVALID_HANDLE_VALUE)
CloseHandle(pi.hProcess);
Parrot_ex_throw_from_c_noargs(interp, EXCEPTION_UNIMPLEMENTED,
"pipe open error");
}
static INTVAL Run_OS_Command(PARROT_INTERP, PMC *command, PMC *env_hash)
{
DWORD status = 0;
STARTUPINFO si;
PROCESS_INFORMATION pi;
const char *env = pack_env_hash(interp, env_hash);
const char *const *argv = pack_arg_array(interp, command);
const char *cmd = create_command_line(argv);
memset(&si, 0, sizeof (si));
si.cb = sizeof (si);
memset(&pi, 0, sizeof (pi));
/* Start the child process. */
if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, env, NULL, &si, &pi))
Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_NOSPAWN,
"Can't spawn child process");
WaitForSingleObject(pi.hProcess, INFINITE);
if (!GetExitCodeProcess(pi.hProcess, &status)) {
Parrot_warn(interp, PARROT_WARNINGS_PLATFORM_FLAG,
"Process completed: Failed to get exit code.");
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
Parrot_str_free_cstring(env);
mem_sys_free(cmd);
/* Return exit code left shifted by 8 for POSIX emulation. */
return status << 8;
}
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static char ** pack_env_hash(Parrot_Interp interp, PMC* hash_pmc) {
Hash *hash = (Hash *)VTABLE_get_pointer(interp, hash_pmc);
STRING *equal = Parrot_str_new_constant(interp, "=");
STRING *key, *value, *env_var;
INTVAL hash_size = Parrot_hash_size(interp, hash);
char** packed = (char **)mem_sys_allocate_zeroed(sizeof(char*) * (hash_size+1));
INTVAL i = 0;
/* Parrot_hash_value_to_string is not exported*/
parrot_hash_iterate(hash,
key = (STRING *)_bucket->key;
value = VTABLE_get_string_keyed_str(interp, hash_pmc,key);
env_var = Parrot_str_concat(interp, key, Parrot_str_concat(interp,equal,value));
packed[i++] = Parrot_str_to_cstring(interp, env_var);
);
packed[hash_size] = NULL;
return packed;
}
static void free_packed(char **env) {
INTVAL i = 0;
while (env[i]) {
Parrot_str_free_cstring(env[i]);
i++;
}
mem_sys_free(env);
}
static INTVAL Run_OS_Command(PARROT_INTERP, PMC *command, PMC *env_hash)
{
pid_t child;
child = fork();
/* Did we fail? */
if (-1 == child)
Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_NOSPAWN,
"Can't spawn child process");
/* Are we the parent or child? */
if (child) {
/* parent */
int status;
waitpid(child, &status, 0);
return status;
}
else {
/* child */
char **saved = environ;
char **cmd = pack_arg_array(interp, command);
char **env = pack_env_hash(interp, env_hash);
char *prog = cmd[0];
int status;
environ = env;
status = execvp(prog, cmd);
/* if we get here, something's horribly wrong, but free anyway... */
free_packed(env);
free_packed(cmd);
environ = saved;
if (status)
PARROT_FORCE_EXIT(status);
_exit(0);
}
/* make gcc happy */
return 1;
}
static PIOHANDLE Run_OS_Command_Piped(PARROT_INTERP, PMC *command, PMC *env_hash, INTVAL flags,
INTVAL *pid, INTVAL *status) {
char **saved = environ;
char **cmd = pack_arg_array(interp, command);
char **env = pack_env_hash(interp, env_hash);
char *prog = cmd[0];
PIOHANDLE handles[3];
int in_fds[2];
int out_fds[2];
int err_fds[2];
if (flags & PARROT_EXEC_STDIN
&& pipe(in_fds) < 0)
goto error_pipe_in;
if (flags & PARROT_EXEC_STDOUT
&& pipe(out_fds) < 0)
goto error_pipe_out;
if (flags & PARROT_EXEC_STDERR
&& pipe(err_fds) < 0)
goto error_pipe_err;
*pid = fork();
if (*pid < 0)
goto error_fork;
if (*pid > 0) {
if (flags & PARROT_EXEC_STDIN) {
/* close fd for reading */
close(in_fds[0]);
handles[0] = in_fds[1];
}
if (flags & PARROT_EXEC_STDOUT) {
/* close fd for writing */
close(out_fds[1]);
handles[1] = out_fds[0];
}
if (flags & PARROT_EXEC_STDERR) {
/* close fd for writing */
close(err_fds[1]);
handles[2] = err_fds[0];
}
}
else /* (pid == 0) */ {
/* Child - exec process */
if (flags & PARROT_EXEC_STDIN) {
/* redirect stdin to pipe */
close(in_fds[1]);
close(STDIN_FILENO);
if (dup(in_fds[0]) != STDIN_FILENO)
PARROT_FORCE_EXIT(EXIT_FAILURE);
}
if (flags & PARROT_EXEC_STDOUT) {
/* redirect stdout to pipe */
close(out_fds[0]);
close(STDOUT_FILENO);
if (dup(out_fds[1]) != STDOUT_FILENO)
PARROT_FORCE_EXIT(EXIT_FAILURE);
if (!(flags & PARROT_EXEC_STDERR)) {
close(STDERR_FILENO);
if (dup(out_fds[1]) != STDERR_FILENO)
PARROT_FORCE_EXIT(EXIT_FAILURE);
}
}
if (flags & PARROT_EXEC_STDERR) {
/* redirect stderr to pipe */
close(err_fds[0]);
close(STDERR_FILENO);
if (dup(err_fds[1]) != STDERR_FILENO)
PARROT_FORCE_EXIT(EXIT_FAILURE);
}
environ = env;
*status = execvp(prog, cmd);
/* if we get here, something's horribly wrong, but free anyway... */
free_packed(env);
free_packed(cmd);
environ = saved;
/* Will never reach this unless exec fails.
* No need to clean up, we're just going to exit */
perror("execvp");
PARROT_FORCE_EXIT(EXIT_FAILURE);
}
return handles[1];
error_fork:
if (flags & PARROT_EXEC_STDERR) {
close(err_fds[0]);
close(err_fds[1]);
}
error_pipe_err:
if (flags & PARROT_EXEC_STDOUT) {
close(out_fds[0]);
close(out_fds[1]);
}
error_pipe_out:
if (flags & PARROT_EXEC_STDIN) {
close(in_fds[0]);
close(in_fds[1]);
}
error_pipe_in:
Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_PIO_ERROR,
"Error executing process: %s", strerror(errno));
}
#endif
/*
printf("key: %s\n", Parrot_str_to_cstring(interp,key));
printf("value: %s\n", Parrot_str_to_cstring(interp,value));
printf("env_var: %s\n", Parrot_str_to_cstring(interp,env_var));
*/
END_OPS_PREAMBLE
/*
=item nqp_dynop_setup()
Does various setup tasks for the benefit of the other dynops.
=cut
*/
inline op nqp_dynop_setup() :base_core {
if (!initialized) {
PMC *obj_sc_barrier, *st_sc_barrier, *global_context;
/* Look up and cache some type IDs. */
stable_id = Parrot_pmc_get_type_str(interp, Parrot_str_new(interp, "STable", 0));
smo_id = Parrot_pmc_get_type_str(interp, Parrot_str_new(interp, "SixModelObject", 0));
qrpa_id = Parrot_pmc_get_type_str(interp, Parrot_str_new(interp, "QRPA", 0));
ohash_id = Parrot_pmc_get_type_str(interp, Parrot_str_new(interp, "OwnedHash", 0));
/* Initialize the object model. */
SixModelObject_initialize(interp, &KnowHOW, &KnowHOWAttribute);
/* Initialize the container system. */
SixModelObject_containers_setup(interp);
/* Initialize compiling SCs list. */
compiling_scs = Parrot_pmc_new(interp, enum_class_ResizablePMCArray);
Parrot_pmc_gc_register(interp, compiling_scs);
/* Set up write barrier functions. */
/* XXX Really want a better, cheaper place to put them... */
obj_sc_barrier = Parrot_pmc_new(interp, enum_class_Pointer);
VTABLE_set_pointer(interp, obj_sc_barrier, SC_write_barrier_obj);
VTABLE_set_pmc_keyed_str(interp, interp->root_namespace,
Parrot_str_new_constant(interp, "_OBJ_SC_BARRIER"), obj_sc_barrier);
st_sc_barrier = Parrot_pmc_new(interp, enum_class_Pointer);