forked from xlq/lua-subprocess
-
Notifications
You must be signed in to change notification settings - Fork 3
/
subprocess.c
1380 lines (1274 loc) · 40.5 KB
/
subprocess.c
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
/* Copyright (c) 2010 Joshua Phillips
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifdef OS_POSIX
#define _POSIX_SOURCE
#endif
#if !defined(OS_WINDOWS) && !defined(OS_POSIX)
#error None of these are defined: OS_WINDOWS, OS_POSIX
#else
#define LUA_LIB
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "errno.h"
#include "fcntl.h"
#include "assert.h"
#include "liolib-copy.h"
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
/* Compatibility for Lua 5.1.
*
* luaL_setfuncs() is used to create a module table where the functions have
* json_config_t as their first upvalue. Code borrowed from Lua 5.2 source. */
static void luaL_setfuncs (lua_State *l, const luaL_Reg *reg, int nup)
{
int i;
luaL_checkstack(l, nup, "too many upvalues");
for (; reg->name != NULL; reg++) { /* fill the table with given functions */
for (i = 0; i < nup; i++) /* copy upvalues to the top */
lua_pushvalue(l, -nup);
lua_pushcclosure(l, reg->func, nup); /* closure with those upvalues */
lua_setfield(l, -(nup + 2), reg->name);
}
lua_pop(l, nup); /* remove upvalues */
}
# define lua_rawlen lua_objlen
#else
#define lua_equal(L,idx1,idx2) lua_compare(L,(idx1),(idx2),LUA_OPEQ)
#endif
#if defined(OS_POSIX)
#include "unistd.h"
#include "sys/wait.h"
#include "sys/stat.h"
#include "stdio.h"
typedef int filedes_t;
/* return 1 if the named directory exists and is a directory */
static int direxists(const char *fname)
{
struct stat statbuf;
if (stat(fname, &statbuf)){
return 0;
}
return !!S_ISDIR(statbuf.st_mode);
}
#elif defined(OS_WINDOWS)
#include "windows.h"
/* Some SDKs don't define this */
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
#endif
typedef HANDLE filedes_t;
/* return 1 if the named directory exists and is a directory */
static int direxists(const char *fname)
{
DWORD result;
result = GetFileAttributes(fname);
if (result == INVALID_FILE_ATTRIBUTES) return 0;
return !!(result & FILE_ATTRIBUTE_DIRECTORY);
}
#endif /* defined(OS_WINDOWS) */
/* Some systems don't define these, but we use them as indices for our arrays.
I probably oughtn't, in case a system doesn't use 0, 1 and 2 for these. */
#ifndef STDIN_FILENO
#define STDIN_FILENO 0
#define STDOUT_FILENO 1
#define STDERR_FILENO 2
#endif
/* This is the proc object, which is stored as Lua userdata */
struct proc {
#if defined(OS_POSIX)
pid_t pid;
#elif defined(OS_WINDOWS)
DWORD pid;
HANDLE hProcess;
#endif
unsigned char done; /* set to 1 when child has finished and closed */
int exitcode;
};
/* Lua registry key for proc metatable */
#define SP_PROC_META "subprocess_proc*"
/* Environment keys */
/* This is an integer index into the environment of C functions in this module.
At this index is stored a table of [pid]=proc items. The items in this table
will all have their `done` fields set to false. This table is at present only
used for the `subprocess.wait` function.
On POSIX, it is used to get the proc object corresponding to a pid. On
Windows, it is used to assemble a HANDLE array for WaitForMultipleObjects. */
static int SP_LIST;
/* Function to count number of keys in a table.
Table must be at top of stack. */
static int countkeys(lua_State *L)
{
int i = 0;
lua_checkstack(L, 3);
lua_pushnil(L);
while (lua_next(L, -2)){
++i;
lua_pop(L, 1);
}
return i;
}
/* Check to see if object at the given index is a proc object.
Return pointer to proc object, or NULL if it isn't. */
static struct proc *toproc(lua_State *L, int index)
{
int eq;
if (lua_type(L, index) != LUA_TUSERDATA) return NULL;
lua_getmetatable(L, index);
luaL_getmetatable(L, SP_PROC_META);
eq = lua_equal(L, -2, -1);
lua_pop(L, 2);
if (!eq) return NULL;
return lua_touserdata(L, index);
}
/* Same but raise an error instead of returning NULL */
#define checkproc(L, index) ((struct proc *) luaL_checkudata((L), (index), SP_PROC_META))
/* Create and return a new proc object */
static struct proc *newproc(lua_State *L)
{
struct proc *proc = lua_newuserdata(L, sizeof *proc);
proc->done = 1;
proc->pid = 0;
luaL_getmetatable(L, SP_PROC_META);
lua_setmetatable(L, -2);
lua_newtable(L);
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
lua_setfenv(L, -2);
#else
lua_setuservalue(L, -2);
#endif
return proc;
}
/* Mark a process (at index) as done */
static void doneproc(lua_State *L, int index)
{
struct proc *proc = toproc(L, index);
if (!proc){
fputs("subprocess.c: doneproc: not a proc\n", stderr);
} else {
proc->done = 1;
/* remove proc from SP_LIST */
lua_checkstack(L, 4);
lua_pushvalue(L, index); /* stack: proc */
lua_pushlightuserdata(L, &SP_LIST);
lua_rawget(L, LUA_REGISTRYINDEX);
/* stack: proc list */
if (lua_isnil(L, -1)){
fputs("subprocess.c: XXX: SP_LIST IS NIL\n", stderr);
} else {
lua_pushinteger(L, proc->pid); /* stack: proc list pid */
lua_pushvalue(L, -1); /* stack: proc list pid pid */
lua_gettable(L, -3); /* stack: proc list pid proc2 */
if (!lua_equal(L, -4, -1)){
/* lookup by pid didn't work */
fputs("subprocess.c: doneproc: XXX: pid lookup in SP_LIST failed\n", stderr);
lua_pop(L, 2); /* stack: proc list */
} else {
lua_pop(L, 1); /* stack: proc list pid */
lua_pushnil(L); /* stack: proc list pid nil */
lua_settable(L, -3); /* stack: proc list */
}
/* stack: proc list */
}
lua_pop(L, 2);
}
}
/* Remove old SP_LIST entries by polling them.
Calling this every now and again can avoid leaking proc objects
that are not waited for. */
static int prune(lua_State *L)
{
int top = lua_gettop(L);
lua_checkstack(L, 5);
lua_pushlightuserdata(L, &SP_LIST);
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_isnil(L, -1)){
lua_pop(L, 1);
return 0;
}
lua_pushnil(L);
while (lua_next(L, -2)){
lua_getfield(L, -1, "poll");
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
lua_pop(L, 1);
}
lua_settop(L, top);
return 0;
}
/* Special constants for popen arguments. */
static char PIPE, STDOUT;
/* Names of standard file handles. */
static const char *fd_names[3] = {"stdin", "stdout", "stderr"};
/* Information about what to do for a standard file handle.
This is constructed from popen arguments. */
struct fdinfo {
enum {
FDMODE_INHERIT = 0, /* fd is inherited from parent */
FDMODE_FILENAME, /* open named file */
FDMODE_FILEDES, /* use a file descriptor */
FDMODE_FILEOBJ, /* use FILE* */
FDMODE_PIPE, /* create and use pipe */
FDMODE_STDOUT /* redirect to stdout (only for stderr) */
} mode;
union {
const char *filename;
filedes_t filedes;
FILE *fileobj;
} info;
};
/* Close multiple file descriptors */
static void closefds(filedes_t *fds, int n)
{
int i;
for (i=0; i<n; ++i){
#if defined(OS_POSIX)
if (fds[i] != -1)
close(fds[i]);
#elif defined(OS_WINDOWS)
if (fds[i] != INVALID_HANDLE_VALUE)
CloseHandle(fds[i]);
#endif
}
}
/* Close multiple C files */
static void closefiles(FILE **files, int n)
{
int i;
for (i=0; i<n; ++i)
if (files[i] != NULL)
fclose(files[i]);
}
/* Free multiple strings */
static void freestrings(char **strs, int n)
{
int i;
for (i=0; i<n; ++i)
if (strs[i] != NULL)
free(strs[i]);
}
#ifdef OS_WINDOWS
/* Copy a Windows error into a buffer */
static void copy_w32error(char errmsg_out[], size_t errmsg_len, DWORD error)
{
if (FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0,
(void *) errmsg_out, errmsg_len, NULL) == 0)
{
strncpy(errmsg_out, "failed to get error message", errmsg_len + 1);
}
}
/* Push a Windows error onto a Lua stack */
static void push_w32error(lua_State *L, DWORD error)
{
LPTSTR buf;
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error, 0, (void *) &buf, 1, NULL) == 0)
{
lua_pushliteral(L, "failed to get error message");
} else {
lua_pushstring(L, buf);
LocalFree(buf);
}
}
/* n is 0, 1 or 2
return handle for standard input/output/error */
static HANDLE getstdhandle(int n)
{
DWORD n2;
switch (n){
case 0: n2 = STD_INPUT_HANDLE; break;
case 1: n2 = STD_OUTPUT_HANDLE; break;
case 2: n2 = STD_ERROR_HANDLE; break;
default: return INVALID_HANDLE_VALUE;
}
return GetStdHandle(n2);
}
struct str {
char *data;
size_t len;
size_t size; /* size allocated */
};
static void str_init(struct str *s)
{
s->data = NULL;
s->len = 0;
s->size = 0;
}
/* Append n chars from s2 */
static int str_appendlstr(struct str *s, char *s2, size_t n)
{
void *newp;
if (s->size < s->len + n){
if (s->size < 16) s->size = 16;
while (s->size < s->len + n)
s->size = (s->size * 3) / 2;
newp = realloc(s->data, s->size + 1);
if (newp == NULL){
free(s->data);
return 0;
}
s->data = newp;
}
memcpy(s->data + s->len, s2, n);
s->len += n;
s->data[s->len] = '\0';
return 1;
}
static int str_appendc(struct str *s, char ch)
{
return str_appendlstr(s, &ch, 1);
}
/* Compiles command line for CreateProcess. Returns malloc'd string. */
static char *compile_cmdline(const char *const *args)
{
/* " --> \"
\" --> \\\"
\<NUL> --> \\ */
struct str str;
const char *arg;
str_init(&str);
while (*args != NULL){
arg = *args++;
if (!str_appendc(&str, '"')) return NULL;
while (arg[0]){
if (arg[0] == '"'){
if (!str_appendlstr(&str, "\\\"", 2)) return NULL;
} else if (arg[0] == '\\'){
if (arg[1] == '"' || arg[1] == '\0'){
if (!str_appendlstr(&str, "\\\\", 2)) return NULL;
} else {
if (!str_appendc(&str, '\\')) return NULL;
}
} else {
if (!str_appendc(&str, arg[0])) return NULL;
}
arg++;
}
if (!str_appendlstr(&str, "\" ", 2)) return NULL;
}
str.data[str.len - 1] = '\0';
return str.data;
}
#endif
/* Function for opening subprocesses. Returns 0 on success and -1 on failure.
On failure, errmsg_out shall contain a '\0'-terminated error message. */
static int dopopen(const char *const *args, /* program arguments with NULL sentinel */
const char *executable, /* actual executable */
struct fdinfo fdinfo[3], /* info for stdin/stdout/stderr */
int close_fds, /* 1 to close all fds */
int binary, /* 1 to use binary files */
const char *cwd, /* working directory for program */
struct proc *proc, /* populated on success! */
FILE *pipe_ends_out[3], /* pipe ends are put here */
char errmsg_out[], /* written to on failure */
size_t errmsg_len /* length of errmsg_out (EXCLUDING sentinel) */
)
#if defined(OS_POSIX)
{
int fds[3];
int i;
struct fdinfo *fdi;
int piperw[2];
int errpipe[2]; /* pipe for returning error status */
int flags;
int en; /* saved errno */
int count;
pid_t pid;
errmsg_out[errmsg_len] = '\0';
for (i=0; i<3; ++i)
pipe_ends_out[i] = NULL;
/* Manage stdin/stdout/stderr */
for (i=0; i<3; ++i){
fdi = &fdinfo[i];
switch (fdi->mode){
case FDMODE_INHERIT:
inherit:
fds[i] = dup(i);
if (fds[i] == -1){
fd_failure:
strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
closefds(fds, i);
closefiles(pipe_ends_out, i);
return -1;
}
break;
case FDMODE_FILENAME:
if (i == STDIN_FILENO){
if ((fds[i] = open(fdi->info.filename, O_RDONLY)) == -1) goto fd_failure;
} else {
if ((fds[i] = creat(fdi->info.filename, 0666)) == -1) goto fd_failure;
}
break;
case FDMODE_FILEDES:
if ((fds[i] = dup(fdi->info.filedes)) == -1) goto fd_failure;
break;
case FDMODE_FILEOBJ:
if ((fds[i] = dup(fileno(fdi->info.fileobj))) == -1) goto fd_failure;
break;
case FDMODE_PIPE:
if (pipe(piperw) == -1) goto fd_failure;
if (i == STDIN_FILENO){
fds[i] = piperw[0]; /* give read end to process */
if ((pipe_ends_out[i] = fdopen(piperw[1], "w")) == NULL) goto fd_failure;
} else {
fds[i] = piperw[1]; /* give write end to process */
if ((pipe_ends_out[i] = fdopen(piperw[0], "r")) == NULL) goto fd_failure;
}
break;
case FDMODE_STDOUT:
if (i == STDERR_FILENO){
if ((fds[STDERR_FILENO] = dup(fds[STDOUT_FILENO])) == -1) goto fd_failure;
} else goto inherit;
break;
}
}
/* Find executable name */
if (!executable){
/* use first arg */
executable = args[0];
}
assert(executable != NULL);
/* Create a pipe for returning error status */
if (pipe(errpipe) == -1){
strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
closefds(fds, 3);
closefiles(pipe_ends_out, 3);
return -1;
}
/* Make write end close on exec */
flags = fcntl(errpipe[1], F_GETFD);
if (flags == -1){
pipe_failure:
strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
closefds(errpipe, 2);
closefds(fds, 3);
closefiles(pipe_ends_out, 3);
return -1;
}
if (fcntl(errpipe[1], F_SETFD, flags | FD_CLOEXEC) == -1) goto pipe_failure;
/* Do the fork/exec (TODO: use vfork somehow?) */
pid = fork();
if (pid == -1) goto pipe_failure;
else if (pid == 0){
/* child */
close(errpipe[0]);
/* dup file descriptors */
for (i=0; i<3; ++i){
if (dup2(fds[i], i) == -1) goto child_failure;
}
/* close other fds */
if (close_fds){
for (i=3; i<sysconf(_SC_OPEN_MAX); ++i){
if (i != errpipe[1])
close(i);
}
}
/* change directory */
if (cwd && chdir(cwd)) goto child_failure;
/* exec! Farewell, subprocess.c! */
execvp(executable, (char *const*) args); /* XXX: const cast */
/* Oh dear, we're still here. */
child_failure:
en = errno;
write(errpipe[1], &en, sizeof en);
_exit(1);
}
/* parent */
/* close unneeded fds */
closefds(fds, 3);
close(errpipe[1]);
/* read errno from child */
while ((count = read(errpipe[0], &en, sizeof en)) == -1)
if (errno != EAGAIN && errno != EINTR) break;
if (count > 0){
/* exec failed */
close(errpipe[0]);
strncpy(errmsg_out, strerror(en), errmsg_len + 1);
return -1;
}
close(errpipe[0]);
/* Child is now running */
proc->done = 0;
proc->pid = pid;
return 0;
}
#elif defined(OS_WINDOWS)
{
HANDLE hfiles[3], piper, pipew, hfile;
int i, fd;
struct fdinfo *fdi;
SECURITY_ATTRIBUTES secattr;
STARTUPINFO si;
PROCESS_INFORMATION pi;
char *cmdline;
errmsg_out[errmsg_len] = '\0';
/* Create a SECURITY_ATTRIBUTES for inheritable handles */
secattr.nLength = sizeof secattr;
secattr.lpSecurityDescriptor = NULL;
secattr.bInheritHandle = TRUE;
for (i=0; i<3; ++i)
pipe_ends_out[i] = NULL;
/* Manage stdin/stdout/stderr */
for (i=0; i<3; ++i){
fdi = &fdinfo[i];
switch (fdi->mode){
case FDMODE_INHERIT:
inherit:
/* XXX: duplicated file handles share the
same object (and thus file cursor, etc.).
CreateFile might be a better idea. */
hfile = getstdhandle(i);
if (hfile == INVALID_HANDLE_VALUE){
fd_failure:
copy_w32error(errmsg_out, errmsg_len, GetLastError());
closefds(hfiles, i);
closefiles(pipe_ends_out, i);
return -1;
}
dup_hfile:
if (DuplicateHandle(GetCurrentProcess(), hfile,
GetCurrentProcess(), &hfiles[i], 0, TRUE,
DUPLICATE_SAME_ACCESS) == 0)
{
goto fd_failure;
}
break;
case FDMODE_FILENAME:
if (i == STDIN_FILENO){
hfiles[i] = CreateFile(
fdi->info.filename,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
&secattr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
} else {
hfiles[i] = CreateFile(
fdi->info.filename,
GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
&secattr,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
}
if (hfiles[i] == INVALID_HANDLE_VALUE){
goto fd_failure;
}
break;
case FDMODE_FILEDES:
if (DuplicateHandle(GetCurrentProcess(), fdi->info.filedes,
GetCurrentProcess(), &hfiles[i], 0, TRUE,
DUPLICATE_SAME_ACCESS) == 0)
{
goto fd_failure;
}
break;
case FDMODE_FILEOBJ:
fd = _fileno(fdi->info.fileobj);
if (fd == -1){
get_osf_failure:
strncpy(errmsg_out, strerror(errno), errmsg_len + 1);
failure:
closefds(hfiles, i);
closefiles(pipe_ends_out, i);
return -1;
}
hfile = (HANDLE) _get_osfhandle(fd);
if (hfile == INVALID_HANDLE_VALUE) goto get_osf_failure;
goto dup_hfile;
case FDMODE_PIPE:
if (CreatePipe(&piper, &pipew, &secattr, 0) == 0)
goto fd_failure;
if (i == STDIN_FILENO){
hfiles[i] = piper;
fd = _open_osfhandle((long) pipew, binary ? 0 : _O_TEXT);
if (fd == -1){
strncpy(errmsg_out, "_open_osfhandle failed", errmsg_len + 1);
goto failure;
}
pipe_ends_out[i] = _fdopen(fd, "w");
if (pipe_ends_out[i] == 0){
strncpy(errmsg_out, "_fdopen failed", errmsg_len + 1);
goto failure;
}
} else {
hfiles[i] = pipew;
fd = _open_osfhandle((long) piper, _O_RDONLY | (binary ? 0 : _O_TEXT));
if (fd == -1){
strncpy(errmsg_out, "_open_osfhandle failed", errmsg_len + 1);
goto failure;
}
pipe_ends_out[i] = _fdopen(fd, "r");
if (pipe_ends_out[i] == 0){
strncpy(errmsg_out, "_fdopen failed", errmsg_len + 1);
goto failure;
}
}
break;
case FDMODE_STDOUT:
if (i == STDERR_FILENO){
hfile = hfiles[STDOUT_FILENO];
goto dup_hfile;
} else goto inherit;
}
}
/* Find executable name */
if (executable == NULL){
/* use first arg */
/*executable = args[0];*/
}
/* Compile command line into string. Yuck. */
cmdline = compile_cmdline(args);
if (!cmdline){
strncpy(errmsg_out, "memory full", errmsg_len + 1);
closefds(hfiles, 3);
closefiles(pipe_ends_out, 3);
return -1;
}
si.cb = sizeof si;
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwFlags = STARTF_USESTDHANDLES;
si.cbReserved2 = 0;
si.lpReserved2 = NULL;
si.hStdInput = hfiles[0];
si.hStdOutput = hfiles[1];
si.hStdError = hfiles[2];
if (CreateProcess(
executable, /* lpApplicationName */
cmdline, /* lpCommandLine */
NULL, /* lpProcessAttributes */
NULL, /* lpThreadAttributes */
TRUE, /* bInheritHandles */
0, /* dwCreationFlags */
NULL, /* lpEnvironment */
cwd, /* lpCurrentDirectory */
&si, /* lpStartupInfo */
&pi) /* lpProcessInformation */
== 0){
copy_w32error(errmsg_out, errmsg_len, GetLastError());
free(cmdline);
closefds(hfiles, 3);
closefiles(pipe_ends_out, 3);
return -1;
}
CloseHandle(pi.hThread); /* Don't want this handle */
free(cmdline);
closefds(hfiles, 3); /* XXX: is this correct? */
proc->done = 0;
proc->pid = pi.dwProcessId;
proc->hProcess = pi.hProcess;
return 0;
}
#endif
/* popen {arg0, arg1, arg2, ..., [executable=...]} */
static int superpopen(lua_State *L)
{
struct proc *proc = NULL;
/* List of arguments (malloc'd NULL-terminated array of C strings.
The C strings are owned by Lua) */
int nargs = 0;
const char **args = NULL;
/* Command to run (owned by Lua) */
const char *executable = NULL;
/* Directory to run it in (owned by Lua) */
const char *cwd = NULL;
/* File options */
struct fdinfo fdinfo[3];
/* Close fds? */
int close_fds = 0;
/* Use binary mode for files? */
int binary = 0;
FILE *pipe_ends[3] = {NULL, NULL, NULL};
int i, result;
FILE *f;
const char *s;
char errmsg_buf[256];
prune(L);
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 1);
proc = newproc(L);
/* Stack: kwargs proc <strings etc....>
Lua strings are left on the stack while they are needed,
and Lua can garbage-collect them later. */
/* get arguments */
nargs = lua_rawlen(L, 1);
if (nargs == 0) return luaL_error(L, "no arguments specified");
args = lua_newuserdata(L, (nargs + 1) * sizeof *args); /*alloc((nargs + 1) * sizeof *args);*/
if (!args) return luaL_error(L, "memory full");
for (i=0; i<=nargs; ++i) args[i] = NULL;
luaL_checkstack(L, nargs, "cannot grow stack");
for (i=1; i<=nargs; ++i){
lua_rawgeti(L, 1, i);
s = lua_tostring(L, -1);
if (!s){
/*freestrings(args, nargs);
free(args);*/
return luaL_error(L, "popen argument %d not a string", (int) i);
}
args[i-1] = s; /*strdup(s);*/
/*if (args[i-1] == NULL){
strings_failure:
freestrings(args, nargs);
free(args);
return luaL_error(L, "memory full");
} */
/*lua_pop(L, 1);*/
}
luaL_checkstack(L, 12, "cannot grow stack");
/* get executable string */
lua_getfield(L, 1, "executable");
s = lua_tostring(L, -1);
if (s){
executable = s; /*strdup(s);*/
/*if (executable == NULL) goto strings_failure;*/
} else lua_pop(L, 1);
/*lua_pop(L, 1); */ /* to match lua_getfield */
/* get directory name */
lua_getfield(L, 1, "cwd");
cwd = lua_tostring(L, -1);
if (cwd == NULL) lua_pop(L, 1);
else {
/*if (lua_isstring(L, -1)){
cwd = lua_tostring(L, -1);*/ /*strdup(lua_tostring(L, -1));
if (!cwd){
free(executable);
freestrings(args, nargs);
free(args);
return luaL_error(L, "memory full");
} */
/* make sure the cwd exists */
if (!direxists(cwd)){
/*free(executable);
freestrings(args, nargs);*/
/*free(args);*/
return luaL_error(L, "directory `%s' does not exist", cwd);
}
}
/*lua_pop(L, 1);*/
/* close_fds */
lua_getfield(L, 1, "close_fds");
close_fds = lua_toboolean(L, -1);
lua_pop(L, 1);
/* binary */
lua_getfield(L, 1, "binary");
binary = lua_toboolean(L, -1);
lua_pop(L, 1);
/* handle stdin/stdout/stderr */
for (i=0; i<3; ++i){
lua_getfield(L, 1, fd_names[i]);
if (lua_isnil(L, -1)){
fdinfo[i].mode = FDMODE_INHERIT;
lua_pop(L, 1);
} else if (lua_touserdata(L, -1) == &PIPE){
fdinfo[i].mode = FDMODE_PIPE;
lua_pop(L, 1);
} else if (lua_touserdata(L, -1) == &STDOUT){
if (i == STDERR_FILENO /*&& fdinfo[STDOUT_FILENO].mode == FDMODE_PIPE*/){
fdinfo[i].mode = FDMODE_STDOUT;
} else {
lua_pushliteral(L, "STDOUT must be used only for stderr"/* when stdout is set to PIPE"*/);
files_failure:
/*for (j=0; j<i; ++j){
if (fdinfo[j].mode == FDMODE_FILENAME)
free(fdinfo[j].info.filename);
}
free(executable);
freestrings(args, nargs);
free(args);*/
return lua_error(L);
}
lua_pop(L, 1);
} else if (lua_isstring(L, -1)){
/* open a file */
fdinfo[i].mode = FDMODE_FILENAME;
/*if ((fdinfo[i].info.filename = strdup(lua_tostring(L, -1))) == NULL){
lua_pushliteral(L, "out of memory");
goto files_failure;
} */
fdinfo[i].info.filename = lua_tostring(L, -1);
/* do not pop */
} else if (lua_isnumber(L, -1)){
/* use this fd */
fdinfo[i].mode = FDMODE_FILEDES;
fdinfo[i].info.filedes = (filedes_t) lua_tointeger(L, -1);
lua_pop(L, 1);
} else {
f = liolib_copy_tofile(L, -1);
if (f){
fdinfo[i].mode = FDMODE_FILEOBJ;
fdinfo[i].info.fileobj = f;
} else {
/* huh? */
lua_pushfstring(L, "unexpected value for %s", fd_names[i]);
goto files_failure;
}
lua_pop(L, 1);
}
}
result = dopopen(args, executable, fdinfo, close_fds, binary, cwd, proc, pipe_ends, errmsg_buf, 255);
/*for (i=0; i<3; ++i)
if (fdinfo[i].mode == FDMODE_FILENAME)
free(fdinfo[i].info.filename);
free(executable);
freestrings(args, nargs);
free(args);*/
if (result == -1){
/* failed */
return luaL_error(L, "popen failed: %s", errmsg_buf);
}
/* Put pipe objects in proc userdata's environment */
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
lua_getfenv(L, 2);
#else
lua_getuservalue(L, 2);
#endif
for (i=0; i<3; ++i){
if (pipe_ends[i]){
*liolib_copy_newfile(L) = pipe_ends[i];
lua_setfield(L, -2, fd_names[i]);
}
}
lua_pop(L, 1);
/* Put proc object in SP_LIST table */
lua_pushlightuserdata(L, &SP_LIST);
lua_rawget(L, LUA_REGISTRYINDEX);
if (lua_isnil(L, -1)){
fputs("subprocess.c: XXX: SP_LIST IS NIL\n", stderr);
} else {
lua_pushinteger(L, proc->pid); /* stack: list pid */
lua_pushvalue(L, 2); /* stack: list pid proc */
lua_settable(L, -3); /* stack: list */
}
lua_pop(L, 1);
/* Return the proc */
lua_settop(L, 2);
return 1;
}
/* __gc */
static int proc_gc(lua_State *L)
{
struct proc *proc = checkproc(L, 1);
if (!proc->done){
#if defined(OS_POSIX)
/* Try to wait for process to avoid leaving zombie.
If the process hasn't finished yet, we'll end up leaving a zombie. */
int stat;
waitpid(proc->pid, &stat, WNOHANG);
#elif defined(OS_WINDOWS)
CloseHandle(proc->hProcess);
#endif
doneproc(L, 1);
}
return 0;
}
/* __index */
static int proc_index(lua_State *L)
{
struct proc *proc;
const char *s;
lua_settop(L, 2);
proc = checkproc(L, 1);
/* first check environment table */
#if !defined(LUA_VERSION_NUM) || LUA_VERSION_NUM < 502
lua_getfenv(L, 1);
#else
lua_getuservalue(L, 1);
#endif
lua_pushvalue(L, 2);
lua_gettable(L, 3);
if (!lua_isnil(L, 4)) return 1;
lua_pop(L, 2);
/* next check metatable */
lua_getmetatable(L, 1);
lua_pushvalue(L, 2);
lua_gettable(L, 3);
if (!lua_isnil(L, 4)) return 1;
lua_pop(L, 2);
/* lastly, fixed fields */
s = lua_tostring(L, 2);
if (!strcmp(s, "pid")){
lua_pushinteger(L, proc->pid);
return 1;
} else if (!strcmp(s, "exitcode") && proc->done){