forked from mario-goulart/chicken-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
posixwin.scm
1617 lines (1428 loc) · 48.2 KB
/
posixwin.scm
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
;;;; posixwin.scm - Miscellaneous file- and process-handling routines, available on Windows
;
; Copyright (c) 2008-2014, The CHICKEN Team
; Copyright (c) 2000-2007, Felix L. Winkelmann
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
; conditions are met:
;
; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
; disclaimer.
; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
; disclaimer in the documentation and/or other materials provided with the distribution.
; Neither the name of the author nor the names of its contributors may be used to endorse or promote
; products derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
; Not implemented:
;
; open/noctty open/nonblock open/fsync open/sync
; perm/isvtx perm/isuid perm/isgid
; file-select
; symbolic-link?
; set-signal-mask! signal-mask signal-masked? signal-mask! signal-unmask!
; user-information group-information get-groups set-groups! initialize-groups
; errno/wouldblock
; change-directory*
; change-file-owner
; current-user-id current-group-id current-effective-user-id current-effective-group-id
; current-effective-user-name
; set-user-id! set-group-id!
; create-session
; process-group-id set-process-group-id!
; create-symbolic-link read-symbolic-link
; file-truncate
; file-lock file-lock/blocking file-unlock file-test-lock
; create-fifo fifo?
; prot/...
; map/...
; set-alarm!
; terminal-name
; process-fork process-wait
; parent-process-id
; process-signal
; Issues
;
; - Use of a UTF8 encoded string will not work properly. Windows uses a
; 16-bit UNICODE character string encoding and specialized system calls
; and/or structure settings for the use of such strings.
(declare
(unit posix)
(uses scheduler irregex extras files ports)
(disable-interrupts)
(hide $quote-args-list $exec-setup $exec-teardown)
(not inline ##sys#interrupt-hook ##sys#user-interrupt-hook)
(foreign-declare #<<EOF
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <signal.h>
#include <utime.h>
#include <winsock2.h>
#define ARG_MAX 256
#define PIPE_BUF 512
#ifndef ENV_MAX
# define ENV_MAX 1024
#endif
static C_TLS char *C_exec_args[ ARG_MAX ];
static C_TLS char *C_exec_env[ ENV_MAX ];
static C_TLS struct group *C_group;
static C_TLS int C_pipefds[ 2 ];
static C_TLS time_t C_secs;
/* pipe handles */
static C_TLS HANDLE C_rd0, C_wr0, C_wr0_, C_rd1, C_wr1, C_rd1_;
static C_TLS HANDLE C_save0, C_save1; /* saved I/O handles */
static C_TLS char C_rdbuf; /* one-char buffer for read */
static C_TLS int C_exstatus;
/* platform information; initialized for cached testing */
static C_TLS char C_hostname[256] = "";
static C_TLS char C_osver[16] = "";
static C_TLS char C_osrel[16] = "";
static C_TLS char C_processor[16] = "";
static C_TLS char C_shlcmd[256] = "";
/* Windows NT or better */
static int C_isNT = 0;
/* Current user name */
static C_TLS TCHAR C_username[255 + 1] = "";
/* Directory Operations */
#define C_mkdir(str) C_fix(mkdir(C_c_string(str)))
#define C_chdir(str) C_fix(chdir(C_c_string(str)))
#define C_rmdir(str) C_fix(rmdir(C_c_string(str)))
#ifndef __WATCOMC__
/* DIRENT stuff */
struct dirent
{
char * d_name;
};
typedef struct
{
struct _finddata_t fdata;
int handle;
struct dirent current;
} DIR;
static DIR * C_fcall
opendir(const char *name)
{
int name_len = strlen(name);
int what_len = name_len + 3;
DIR *dir = (DIR *)malloc(sizeof(DIR));
char *what;
if (!dir)
{
errno = ENOMEM;
return NULL;
}
what = (char *)malloc(what_len);
if (!what)
{
free(dir);
errno = ENOMEM;
return NULL;
}
C_strlcpy(what, name, what_len);
if (strchr("\\/", name[name_len - 1]))
C_strlcat(what, "*", what_len);
else
C_strlcat(what, "\\*", what_len);
dir->handle = _findfirst(what, &dir->fdata);
if (dir->handle == -1)
{
free(what);
free(dir);
return NULL;
}
dir->current.d_name = NULL; /* as the first-time indicator */
free(what);
return dir;
}
static int C_fcall
closedir(DIR * dir)
{
if (dir)
{
int res = _findclose(dir->handle);
free(dir);
return res;
}
return -1;
}
static struct dirent * C_fcall
readdir(DIR * dir)
{
if (dir)
{
if (!dir->current.d_name /* first time after opendir */
|| _findnext(dir->handle, &dir->fdata) != -1)
{
dir->current.d_name = dir->fdata.name;
return &dir->current;
}
}
return NULL;
}
#endif /* ifndef __WATCOMC__ */
#ifdef __WATCOMC__
/* there is no P_DETACH in Watcom CRTL */
# define P_DETACH P_NOWAIT
#endif
#define open_binary_input_pipe(a, n, name) C_mpointer(a, _popen(C_c_string(name), "r"))
#define open_text_input_pipe(a, n, name) open_binary_input_pipe(a, n, name)
#define open_binary_output_pipe(a, n, name) C_mpointer(a, _popen(C_c_string(name), "w"))
#define open_text_output_pipe(a, n, name) open_binary_output_pipe(a, n, name)
#define close_pipe(p) C_fix(_pclose(C_port_file(p)))
#define C_chmod(fn, m) C_fix(chmod(C_data_pointer(fn), C_unfix(m)))
#define C_setvbuf(p, m, s) C_fix(setvbuf(C_port_file(p), NULL, C_unfix(m), C_unfix(s)))
#define C_test_access(fn, m) C_fix(access((char *)C_data_pointer(fn), C_unfix(m)))
#define C_pipe(d, m) C_fix(_pipe(C_pipefds, PIPE_BUF, C_unfix(m)))
#define C_close(fd) C_fix(close(C_unfix(fd)))
#define C_getenventry(i) environ[ i ]
#define C_lstat(fn) C_stat(fn)
static void C_fcall
C_set_arg_string(char **where, int i, char *dat, int len)
{
char *ptr;
if (dat)
{
ptr = (char *)C_malloc(len + 1);
C_memcpy(ptr, dat, len);
ptr[ len ] = '\0';
/* Can't barf() here, so the NUL byte check happens in Scheme */
}
else
ptr = NULL;
where[ i ] = ptr;
}
static void C_fcall
C_free_arg_string(char **where) {
while (*where) C_free(*(where++));
}
#define C_set_exec_arg(i, a, len) C_set_arg_string(C_exec_args, i, a, len)
#define C_set_exec_env(i, a, len) C_set_arg_string(C_exec_env, i, a, len)
#define C_free_exec_args() (C_free_arg_string(C_exec_args), C_SCHEME_TRUE)
#define C_free_exec_env() (C_free_arg_string(C_exec_env), C_SCHEME_TRUE)
#define C_execvp(f) C_fix(execvp(C_data_pointer(f), (const char *const *)C_exec_args))
#define C_execve(f) C_fix(execve(C_data_pointer(f), (const char *const *)C_exec_args, (const char *const *)C_exec_env))
/* MS replacement for the fork-exec pair */
#define C_spawnvp(m, f) C_fix(spawnvp(C_unfix(m), C_data_pointer(f), (const char *const *)C_exec_args))
#define C_spawnvpe(m, f) C_fix(spawnvpe(C_unfix(m), C_data_pointer(f), (const char *const *)C_exec_args, (const char *const *)C_exec_env))
#define C_open(fn, fl, m) C_fix(open(C_c_string(fn), C_unfix(fl), C_unfix(m)))
#define C_read(fd, b, n) C_fix(read(C_unfix(fd), C_data_pointer(b), C_unfix(n)))
#define C_write(fd, b, n) C_fix(write(C_unfix(fd), C_data_pointer(b), C_unfix(n)))
#define C_flushall() C_fix(_flushall())
#define C_umask(m) C_fix(_umask(C_unfix(m)))
#define C_ctime(n) (C_secs = (n), ctime(&C_secs))
#define TIME_STRING_MAXLENGTH 255
static char C_time_string [TIME_STRING_MAXLENGTH + 1];
#undef TIME_STRING_MAXLENGTH
/*
mapping from Win32 error codes to errno
*/
typedef struct
{
DWORD win32;
int libc;
} errmap_t;
static errmap_t errmap[] =
{
{ERROR_INVALID_FUNCTION, EINVAL},
{ERROR_FILE_NOT_FOUND, ENOENT},
{ERROR_PATH_NOT_FOUND, ENOENT},
{ERROR_TOO_MANY_OPEN_FILES, EMFILE},
{ERROR_ACCESS_DENIED, EACCES},
{ERROR_INVALID_HANDLE, EBADF},
{ERROR_ARENA_TRASHED, ENOMEM},
{ERROR_NOT_ENOUGH_MEMORY, ENOMEM},
{ERROR_INVALID_BLOCK, ENOMEM},
{ERROR_BAD_ENVIRONMENT, E2BIG},
{ERROR_BAD_FORMAT, ENOEXEC},
{ERROR_INVALID_ACCESS, EINVAL},
{ERROR_INVALID_DATA, EINVAL},
{ERROR_INVALID_DRIVE, ENOENT},
{ERROR_CURRENT_DIRECTORY, EACCES},
{ERROR_NOT_SAME_DEVICE, EXDEV},
{ERROR_NO_MORE_FILES, ENOENT},
{ERROR_LOCK_VIOLATION, EACCES},
{ERROR_BAD_NETPATH, ENOENT},
{ERROR_NETWORK_ACCESS_DENIED, EACCES},
{ERROR_BAD_NET_NAME, ENOENT},
{ERROR_FILE_EXISTS, EEXIST},
{ERROR_CANNOT_MAKE, EACCES},
{ERROR_FAIL_I24, EACCES},
{ERROR_INVALID_PARAMETER, EINVAL},
{ERROR_NO_PROC_SLOTS, EAGAIN},
{ERROR_DRIVE_LOCKED, EACCES},
{ERROR_BROKEN_PIPE, EPIPE},
{ERROR_DISK_FULL, ENOSPC},
{ERROR_INVALID_TARGET_HANDLE, EBADF},
{ERROR_INVALID_HANDLE, EINVAL},
{ERROR_WAIT_NO_CHILDREN, ECHILD},
{ERROR_CHILD_NOT_COMPLETE, ECHILD},
{ERROR_DIRECT_ACCESS_HANDLE, EBADF},
{ERROR_NEGATIVE_SEEK, EINVAL},
{ERROR_SEEK_ON_DEVICE, EACCES},
{ERROR_DIR_NOT_EMPTY, ENOTEMPTY},
{ERROR_NOT_LOCKED, EACCES},
{ERROR_BAD_PATHNAME, ENOENT},
{ERROR_MAX_THRDS_REACHED, EAGAIN},
{ERROR_LOCK_FAILED, EACCES},
{ERROR_ALREADY_EXISTS, EEXIST},
{ERROR_FILENAME_EXCED_RANGE, ENOENT},
{ERROR_NESTING_NOT_ALLOWED, EAGAIN},
{ERROR_NOT_ENOUGH_QUOTA, ENOMEM},
{0, 0}
};
static void C_fcall
set_errno(DWORD w32err)
{
errmap_t *map;
for (map = errmap; map->win32; ++map)
{
if (map->win32 == w32err)
{
errno = map->libc;
return;
}
}
errno = ENOSYS; /* For lack of anything better */
}
static int C_fcall
set_last_errno()
{
set_errno(GetLastError());
return 0;
}
static int C_fcall
process_wait(C_word h, C_word t)
{
if (WaitForSingleObject((HANDLE)h, (t ? 0 : INFINITE)) == WAIT_OBJECT_0)
{
DWORD ret;
if (GetExitCodeProcess((HANDLE)h, &ret))
{
CloseHandle((HANDLE)h);
C_exstatus = ret;
return 1;
}
}
return set_last_errno();
}
#define C_process_wait(p, t) (process_wait(C_unfix(p), C_truep(t)) ? C_SCHEME_TRUE : C_SCHEME_FALSE)
#define C_sleep(t) (Sleep(C_unfix(t) * 1000), C_fix(0))
static int C_fcall
get_hostname()
{
/* Do we already have hostname? */
if (strlen(C_hostname))
{
return 1;
}
else
{
WSADATA wsa;
if (WSAStartup(MAKEWORD(1, 1), &wsa) == 0)
{
int nok = gethostname(C_hostname, sizeof(C_hostname));
WSACleanup();
return !nok;
}
return 0;
}
}
static int C_fcall
sysinfo()
{
/* Do we need to build the sysinfo? */
if (!strlen(C_osrel))
{
OSVERSIONINFO ovf;
ZeroMemory(&ovf, sizeof(ovf));
ovf.dwOSVersionInfoSize = sizeof(ovf);
if (get_hostname() && GetVersionEx(&ovf))
{
SYSTEM_INFO si;
_snprintf(C_osver, sizeof(C_osver) - 1, "%d.%d.%d",
ovf.dwMajorVersion, ovf.dwMinorVersion, ovf.dwBuildNumber);
strncpy(C_osrel, "Win", sizeof(C_osrel) - 1);
switch (ovf.dwPlatformId)
{
case VER_PLATFORM_WIN32s:
strncpy(C_osrel, "Win32s", sizeof(C_osrel) - 1);
break;
case VER_PLATFORM_WIN32_WINDOWS:
if (ovf.dwMajorVersion == 4)
{
if (ovf.dwMinorVersion == 0)
strncpy(C_osrel, "Win95", sizeof(C_osrel) - 1);
else if (ovf.dwMinorVersion == 10)
strncpy(C_osrel, "Win98", sizeof(C_osrel) - 1);
else if (ovf.dwMinorVersion == 90)
strncpy(C_osrel, "WinMe", sizeof(C_osrel) - 1);
}
break;
case VER_PLATFORM_WIN32_NT:
C_isNT = 1;
if (ovf.dwMajorVersion == 6)
strncpy(C_osrel, "WinVista", sizeof(C_osrel) - 1);
else if (ovf.dwMajorVersion == 5)
{
if (ovf.dwMinorVersion == 2)
strncpy(C_osrel, "WinServer2003", sizeof(C_osrel) - 1);
else if (ovf.dwMinorVersion == 1)
strncpy(C_osrel, "WinXP", sizeof(C_osrel) - 1);
else if ( ovf.dwMinorVersion == 0)
strncpy(C_osrel, "Win2000", sizeof(C_osrel) - 1);
}
else if (ovf.dwMajorVersion <= 4)
strncpy(C_osrel, "WinNT", sizeof(C_osrel) - 1);
break;
}
GetSystemInfo(&si);
strncpy(C_processor, "Unknown", sizeof(C_processor) - 1);
switch (si.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_INTEL:
strncpy(C_processor, "x86", sizeof(C_processor) - 1);
break;
# ifdef PROCESSOR_ARCHITECTURE_IA64
case PROCESSOR_ARCHITECTURE_IA64:
strncpy(C_processor, "IA64", sizeof(C_processor) - 1);
break;
# endif
# ifdef PROCESSOR_ARCHITECTURE_AMD64
case PROCESSOR_ARCHITECTURE_AMD64:
strncpy(C_processor, "x64", sizeof(C_processor) - 1);
break;
# endif
# ifdef PROCESSOR_ARCHITECTURE_IA32_ON_WIN64
case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64:
strncpy(C_processor, "WOW64", sizeof(C_processor) - 1);
break;
# endif
}
}
else
return set_last_errno();
}
return 1;
}
static int C_fcall
get_shlcmd()
{
/* Do we need to build the shell command pathname? */
if (!strlen(C_shlcmd))
{
if (sysinfo()) /* for C_isNT */
{
char *cmdnam = C_isNT ? "\\cmd.exe" : "\\command.com";
UINT len = GetSystemDirectory(C_shlcmd, sizeof(C_shlcmd) - strlen(cmdnam));
if (len)
C_strlcpy(C_shlcmd + len, cmdnam, sizeof(C_shlcmd));
else
return set_last_errno();
}
else
return 0;
}
return 1;
}
#define C_get_hostname() (get_hostname() ? C_SCHEME_TRUE : C_SCHEME_FALSE)
#define C_sysinfo() (sysinfo() ? C_SCHEME_TRUE : C_SCHEME_FALSE)
#define C_get_shlcmd() (get_shlcmd() ? C_SCHEME_TRUE : C_SCHEME_FALSE)
/* GetUserName */
static int C_fcall
get_user_name()
{
if (!strlen(C_username))
{
DWORD bufCharCount = sizeof(C_username) / sizeof(C_username[0]);
if (!GetUserName(C_username, &bufCharCount))
return set_last_errno();
}
return 1;
}
#define C_get_user_name() (get_user_name() ? C_SCHEME_TRUE : C_SCHEME_FALSE)
/*
Spawn a process directly.
Params:
app Command to execute.
cmdlin Command line (arguments).
env Environment for the new process (may be NULL).
handle, stdin, stdout, stderr
Spawned process info are returned in integers.
When spawned process shares standard io stream with the parent
process the respective value in handle, stdin, stdout, stderr
is -1.
params A bitmask controling operation.
Bit 1: Child & parent share standard input if this bit is set.
Bit 2: Share standard output if bit is set.
Bit 3: Share standard error if bit is set.
Returns: zero return value indicates failure.
*/
static int C_fcall
C_process(const char * app, const char * cmdlin, const char ** env,
C_word * phandle,
int * pstdin_fd, int * pstdout_fd, int * pstderr_fd,
int params)
{
int i;
int success = TRUE;
const int f_share_io[3] = { params & 1, params & 2, params & 4};
int io_fds[3] = { -1, -1, -1 };
HANDLE
child_io_handles[3] = { NULL, NULL, NULL },
standard_io_handles[3] = {
GetStdHandle(STD_INPUT_HANDLE),
GetStdHandle(STD_OUTPUT_HANDLE),
GetStdHandle(STD_ERROR_HANDLE)};
const char modes[3] = "rww";
HANDLE cur_process = GetCurrentProcess(), child_process = NULL;
void* envblk = NULL;
/****** create io handles & fds ***/
for (i=0; i<3 && success; ++i)
{
if (f_share_io[i])
{
success = DuplicateHandle(
cur_process, standard_io_handles[i],
cur_process, &child_io_handles[i],
0, FALSE, DUPLICATE_SAME_ACCESS);
}
else
{
HANDLE a, b;
success = CreatePipe(&a,&b,NULL,0);
if(success)
{
HANDLE parent_end;
if (modes[i]=='r') { child_io_handles[i]=a; parent_end=b; }
else { parent_end=a; child_io_handles[i]=b; }
success = (io_fds[i] = _open_osfhandle((C_word)parent_end,0)) >= 0;
/* Make new handle inheritable */
if (success)
success = SetHandleInformation(child_io_handles[i], HANDLE_FLAG_INHERIT, -1);
}
}
}
#if 0 /* Requires a sorted list by key! */
/****** create environment block if necessary ****/
if (env && success)
{
char** p;
int len = 0;
for (p = env; *p; ++p) len += strlen(*p) + 1;
if (envblk = C_malloc(len + 1))
{
char* pb = (char*)envblk;
for (p = env; *p; ++p)
{
C_strlcpy(pb, *p, len+1);
pb += strlen(*p) + 1;
}
*pb = '\0';
/* This _should_ already have been checked for embedded NUL bytes */
}
else
success = FALSE;
}
#endif
/****** finally spawn process ****/
if (success)
{
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&pi,sizeof pi);
ZeroMemory(&si,sizeof si);
si.cb = sizeof si;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = child_io_handles[0];
si.hStdOutput = child_io_handles[1];
si.hStdError = child_io_handles[2];
/* FIXME passing 'app' param causes failure & possible stack corruption */
success = CreateProcess(
NULL, (char*)cmdlin, NULL, NULL, TRUE, 0, envblk, NULL, &si, &pi);
if (success)
{
child_process=pi.hProcess;
CloseHandle(pi.hThread);
}
else
set_last_errno();
}
else
set_last_errno();
/****** cleanup & return *********/
/* parent must close child end */
for (i=0; i<3; ++i) {
if (child_io_handles[i] != NULL)
CloseHandle(child_io_handles[i]);
}
if (success)
{
*phandle = (C_word)child_process;
*pstdin_fd = io_fds[0];
*pstdout_fd = io_fds[1];
*pstderr_fd = io_fds[2];
}
else
{
for (i=0; i<3; ++i) {
if (io_fds[i] != -1)
_close(io_fds[i]);
}
}
return success;
}
static int set_file_mtime(char *filename, C_word tm)
{
struct _utimbuf tb;
tb.actime = tb.modtime = C_num_to_int(tm);
return _utime(filename, &tb);
}
EOF
) )
;;; common code
(include "posix-common.scm")
;;; Lo-level I/O:
(define-foreign-variable _pipe_buf int "PIPE_BUF")
(define pipe/buf _pipe_buf)
(define-foreign-variable _o_rdonly int "O_RDONLY")
(define-foreign-variable _o_wronly int "O_WRONLY")
(define-foreign-variable _o_rdwr int "O_RDWR")
(define-foreign-variable _o_creat int "O_CREAT")
(define-foreign-variable _o_append int "O_APPEND")
(define-foreign-variable _o_excl int "O_EXCL")
(define-foreign-variable _o_trunc int "O_TRUNC")
(define-foreign-variable _o_binary int "O_BINARY")
(define-foreign-variable _o_text int "O_TEXT")
(define-foreign-variable _o_noinherit int "O_NOINHERIT")
(define open/rdonly _o_rdonly)
(define open/wronly _o_wronly)
(define open/rdwr _o_rdwr)
(define open/read _o_rdwr)
(define open/write _o_wronly)
(define open/creat _o_creat)
(define open/append _o_append)
(define open/excl _o_excl)
(define open/trunc _o_trunc)
(define open/binary _o_binary)
(define open/text _o_text)
(define open/noinherit _o_noinherit)
(define-foreign-variable _s_irusr int "S_IREAD")
(define-foreign-variable _s_iwusr int "S_IWRITE")
(define-foreign-variable _s_ixusr int "S_IEXEC")
(define-foreign-variable _s_irgrp int "S_IREAD")
(define-foreign-variable _s_iwgrp int "S_IWRITE")
(define-foreign-variable _s_ixgrp int "S_IEXEC")
(define-foreign-variable _s_iroth int "S_IREAD")
(define-foreign-variable _s_iwoth int "S_IWRITE")
(define-foreign-variable _s_ixoth int "S_IEXEC")
(define-foreign-variable _s_irwxu int "S_IREAD | S_IWRITE | S_IEXEC")
(define-foreign-variable _s_irwxg int "S_IREAD | S_IWRITE | S_IEXEC")
(define-foreign-variable _s_irwxo int "S_IREAD | S_IWRITE | S_IEXEC")
(define perm/irusr _s_irusr)
(define perm/iwusr _s_iwusr)
(define perm/ixusr _s_ixusr)
(define perm/irgrp _s_irgrp)
(define perm/iwgrp _s_iwgrp)
(define perm/ixgrp _s_ixgrp)
(define perm/iroth _s_iroth)
(define perm/iwoth _s_iwoth)
(define perm/ixoth _s_ixoth)
(define perm/irwxu _s_irwxu)
(define perm/irwxg _s_irwxg)
(define perm/irwxo _s_irwxo)
(define file-open
(let ([defmode (bitwise-ior _s_irwxu (fxior _s_irgrp _s_iroth))] )
(lambda (filename flags . mode)
(let ([mode (if (pair? mode) (car mode) defmode)])
(##sys#check-string filename 'file-open)
(##sys#check-exact flags 'file-open)
(##sys#check-exact mode 'file-open)
(let ([fd (##core#inline "C_open" (##sys#make-c-string filename 'file-open) flags mode)])
(when (eq? -1 fd)
(##sys#update-errno)
(##sys#signal-hook #:file-error 'file-open "cannot open file" filename flags mode) )
fd) ) ) ) )
(define file-close
(lambda (fd)
(##sys#check-exact fd 'file-close)
(when (fx< (##core#inline "C_close" fd) 0)
(##sys#update-errno)
(##sys#signal-hook #:file-error 'file-close "cannot close file" fd) ) ) )
(define file-read
(lambda (fd size . buffer)
(##sys#check-exact fd 'file-read)
(##sys#check-exact size 'file-read)
(let ([buf (if (pair? buffer) (car buffer) (make-string size))])
(unless (and (##core#inline "C_blockp" buf) (##core#inline "C_byteblockp" buf))
(##sys#signal-hook #:type-error 'file-read "bad argument type - not a string or blob" buf) )
(let ([n (##core#inline "C_read" fd buf size)])
(when (eq? -1 n)
(##sys#update-errno)
(##sys#signal-hook #:file-error 'file-read "cannot read from file" fd size) )
(list buf n) ) ) ) )
(define file-write
(lambda (fd buffer . size)
(##sys#check-exact fd 'file-write)
(unless (and (##core#inline "C_blockp" buffer) (##core#inline "C_byteblockp" buffer))
(##sys#signal-hook #:type-error 'file-write "bad argument type - not a string or blob" buffer) )
(let ([size (if (pair? size) (car size) (##sys#size buffer))])
(##sys#check-exact size 'file-write)
(let ([n (##core#inline "C_write" fd buffer size)])
(when (eq? -1 n)
(##sys#update-errno)
(##sys#signal-hook #:file-error 'file-write "cannot write to file" fd size) )
n) ) ) )
(define file-mkstemp
(lambda (template)
(##sys#check-string template 'file-mkstemp)
(let* ((diz "0123456789abcdefghijklmnopqrstuvwxyz")
(diz-len (string-length diz))
(max-attempts (* diz-len diz-len diz-len))
(tmpl (string-copy template)) ; We'll overwrite this later
(tmpl-len (string-length tmpl))
(first-x (let loop ((i (fx- tmpl-len 1)))
(if (and (fx>= i 0)
(eq? (string-ref tmpl i) #\X))
(loop (fx- i 1))
(fx+ i 1)))))
(cond ((not (directory-exists? (or (pathname-directory template) ".")))
;; Quit early instead of looping needlessly with C_open
;; failing every time. This is a race condition, but not
;; a security-critical one.
(##sys#signal-hook #:file-error 'file-mkstemp "non-existent directory" template))
((fx= first-x tmpl-len)
(##sys#signal-hook #:file-error 'file-mkstemp "invalid template" template)))
(let loop ((count 1))
(let suffix-loop ((index (fx- tmpl-len 1)))
(when (fx>= index first-x)
(string-set! tmpl index (string-ref diz (random diz-len)))
(suffix-loop (fx- index 1))))
(let ((fd (##core#inline "C_open"
(##sys#make-c-string tmpl 'file-open)
(bitwise-ior open/rdwr open/creat open/excl)
(fxior _s_irusr _s_iwusr))))
(if (eq? -1 fd)
(if (fx< count max-attempts)
(loop (fx+ count 1))
(posix-error #:file-error 'file-mkstemp "cannot create temporary file" template))
(values fd tmpl)))))))
;;; Directory stuff:
(define-inline (create-directory-helper name)
(unless (fx= 0 (##core#inline "C_mkdir" (##sys#make-c-string name 'create-directory)))
(##sys#update-errno)
(##sys#signal-hook #:file-error 'create-directory
"cannot create directory" name)))
(define-inline (create-directory-helper-silent name)
(unless (##sys#file-exists? name #f #t #f)
(create-directory-helper name)))
(define-inline (create-directory-helper-parents name)
(let* ((l (string-split name "/\\"))
(c (car l)))
(for-each
(lambda (x)
(set! c (string-append c "/" x))
(create-directory-helper-silent c))
(cdr l))))
(define create-directory
(lambda (name #!optional parents?)
(##sys#check-string name 'create-directory)
(let ((name name))
(if parents?
(create-directory-helper-parents name)
(create-directory-helper name))
name)))
(define change-directory
(lambda (name)
(##sys#check-string name 'change-directory)
(let ((sname (##sys#make-c-string name 'change-directory)))
(unless (fx= 0 (##core#inline "C_chdir" sname))
(##sys#update-errno)
(##sys#signal-hook
#:file-error 'change-directory "cannot change current directory" name) )
name)))
;;; Pipes:
(let ()
(define (mode arg) (if (pair? arg) (##sys#slot arg 0) '###text))
(define (badmode m) (##sys#error "illegal input/output mode specifier" m))
(define (check cmd inp r)
(##sys#update-errno)
(if (##sys#null-pointer? r)
(##sys#signal-hook #:file-error "cannot open pipe" cmd)
(let ([port (##sys#make-port inp ##sys#stream-port-class "(pipe)" 'stream)])
(##core#inline "C_set_file_ptr" port r)
port) ) )
(set! open-input-pipe
(lambda (cmd . m)
(##sys#check-string cmd 'open-input-pipe)
(let ([m (mode m)])
(check
cmd #t
(case m
((###text) (##core#inline_allocate ("open_text_input_pipe" 2) (##sys#make-c-string cmd 'open-input-pipe)))
((###binary) (##core#inline_allocate ("open_binary_input_pipe" 2) (##sys#make-c-string cmd 'open-input-pipe)))
(else (badmode m)) ) ) ) ) )
(set! open-output-pipe
(lambda (cmd . m)
(##sys#check-string cmd 'open-output-pipe)
(let ((m (mode m)))
(check
cmd #f
(case m
((###text) (##core#inline_allocate ("open_text_output_pipe" 2) (##sys#make-c-string cmd 'open-output-pipe)))
((###binary) (##core#inline_allocate ("open_binary_output_pipe" 2) (##sys#make-c-string cmd 'open-output-pipe)))
(else (badmode m)) ) ) ) ) )
(set! close-input-pipe
(lambda (port)
(##sys#check-input-port port #t 'close-input-pipe)
(let ((r (##core#inline "close_pipe" port)))
(##sys#update-errno)
(when (eq? -1 r)
(##sys#signal-hook #:file-error 'close-input-pipe "error while closing pipe" port) )
r)))
(set! close-output-pipe
(lambda (port)
(##sys#check-output-port port #t 'close-output-pipe)
(let ((r (##core#inline "close_pipe" port)))
(##sys#update-errno)
(when (eq? -1 r)
(##sys#signal-hook #:file-error 'close-output-pipe "error while closing pipe" port) )
r))))
(define call-with-input-pipe
(lambda (cmd proc . mode)
(let ([p (apply open-input-pipe cmd mode)])
(##sys#call-with-values
(lambda () (proc p))
(lambda results
(close-input-pipe p)
(apply values results) ) ) ) ) )
(define call-with-output-pipe
(lambda (cmd proc . mode)
(let ([p (apply open-output-pipe cmd mode)])
(##sys#call-with-values
(lambda () (proc p))
(lambda results
(close-output-pipe p)
(apply values results) ) ) ) ) )
(define with-input-from-pipe
(lambda (cmd thunk . mode)
(let ([p (apply open-input-pipe cmd mode)])
(fluid-let ((##sys#standard-input p))
(##sys#call-with-values
thunk
(lambda results
(close-input-pipe p)
(apply values results) ) ) ) ) ) )
(define with-output-to-pipe
(lambda (cmd thunk . mode)
(let ([p (apply open-output-pipe cmd mode)])
(fluid-let ((##sys#standard-output p))
(##sys#call-with-values
thunk
(lambda results
(close-output-pipe p)
(apply values results) ) ) ) ) ) )
;;; Pipe primitive:
(define-foreign-variable _pipefd0 int "C_pipefds[ 0 ]")
(define-foreign-variable _pipefd1 int "C_pipefds[ 1 ]")
(define create-pipe
(lambda (#!optional (mode (fxior open/binary open/noinherit)))
(when (fx< (##core#inline "C_pipe" #f mode) 0)
(##sys#update-errno)
(##sys#signal-hook #:file-error 'create-pipe "cannot create pipe") )
(values _pipefd0 _pipefd1) ) )
;;; Signal processing:
(define-foreign-variable _nsig int "NSIG")
(define-foreign-variable _sigterm int "SIGTERM")
(define-foreign-variable _sigint int "SIGINT")
(define-foreign-variable _sigfpe int "SIGFPE")
(define-foreign-variable _sigill int "SIGILL")
(define-foreign-variable _sigsegv int "SIGSEGV")
(define-foreign-variable _sigabrt int "SIGABRT")
(define-foreign-variable _sigbreak int "SIGBREAK")
(define signal/term _sigterm)
(define signal/int _sigint)
(define signal/fpe _sigfpe)
(define signal/ill _sigill)
(define signal/segv _sigsegv)
(define signal/abrt _sigabrt)
(define signal/break _sigbreak)
(define signal/alrm 0)
(define signal/chld 0)
(define signal/cont 0)
(define signal/hup 0)
(define signal/io 0)
(define signal/kill 0)
(define signal/pipe 0)
(define signal/prof 0)
(define signal/quit 0)
(define signal/stop 0)
(define signal/trap 0)
(define signal/tstp 0)
(define signal/urg 0)
(define signal/usr1 0)
(define signal/usr2 0)
(define signal/vtalrm 0)
(define signal/winch 0)
(define signal/xcpu 0)
(define signal/xfsz 0)
(define signals-list
(list
signal/term signal/int signal/fpe signal/ill
signal/segv signal/abrt signal/break))
;;; More errno codes:
(define errno/perm _eperm)
(define errno/noent _enoent)