Debian Codegraph @

src/c/unixsys.d

raw
1 /* -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*- */
2 /* vim: set filetype=c tabstop=2 shiftwidth=2 expandtab: */
3
4 /*
5 * unixsys.s - Unix shell interface
6 *
7 * Copyright (c) 1984 Taiichi Yuasa and Masami Hagiya
8 * Copyright (c) 1990 Giuseppe Attardi
9 * Copyright (c) 2001 Juan Jose Garcia Ripoll
10 *
11 * See file 'LICENSE' for the copyright details.
12 *
13 */
14
15 #include <stdlib.h>
16 #include <string.h>
17 #include <stdio.h>
18 #include <fcntl.h>
19 #include <errno.h>
20 #include <signal.h> /* to see whether we have SIGCHLD */
21 #if !defined(_MSC_VER)
22 # include <unistd.h>
23 #endif
24 #include <ecl/ecl.h>
25 #include <ecl/internal.h>
26 #if defined(ECL_MS_WINDOWS_HOST)
27 # include <windows.h>
28 #endif
29 #ifdef HAVE_SYS_WAIT_H
30 # include <sys/wait.h>
31 #endif
32 #include <ecl/ecl-inl.h>
33
34 /* Shared libraries do not have direct access to environ on Darwin */
35 #if defined(__APPLE__)
36 # include <crt_externs.h>
37 # define environ (*_NSGetEnviron())
38 /* Mingw defines 'environ' to be a macro instead of a global variable. */
39 #elif !defined(environ) && defined(HAVE_ENVIRON)
40 extern char **environ;
41 #endif
42
43 #if defined(__APPLE__)
44 #include <TargetConditionals.h> /* for TARGET_OS_IPHONE */
45 #endif
46
47 cl_object
48 si_system(cl_object cmd_string)
49 {
50 #if !defined(HAVE_SYSTEM) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
51 FElibc_error("si_system not implemented",1);
52 @(return ECL_NIL);
53 #else
54 cl_object cmd = si_copy_to_simple_base_string(cmd_string);
55 int code = system((const char *)(cmd->base_string.self));
56 @(return ecl_make_fixnum(code));
57 #endif
58 }
59
60 cl_object
61 si_getenv(cl_object var)
62 {
63 const char *value;
64
65 /* Strings have to be null terminated base strings */
66 var = si_copy_to_simple_base_string(var);
67 value = getenv((char*)var->base_string.self);
68 @(return ((value == NULL)? ECL_NIL : ecl_make_simple_base_string(value,-1)));
69 }
70
71 #if defined(HAVE_SETENV) || defined(HAVE_PUTENV)
72 cl_object
73 si_setenv(cl_object var, cl_object value)
74 {
75 const cl_env_ptr the_env = ecl_process_env();
76 cl_fixnum ret_val;
77
78 /* Strings have to be null terminated base strings */
79 var = si_copy_to_simple_base_string(var);
80 if (value == ECL_NIL) {
81 #ifdef HAVE_SETENV
82 /* Remove the variable when setting to nil, so that
83 * (si:setenv "foo" nil), then (si:getenv "foo) returns
84 * the right thing. */
85 unsetenv((char*)var->base_string.self);
86 #else
87 #if defined(ECL_MS_WINDOWS_HOST)
88 si_setenv(var, cl_core.null_string);
89 #else
90 putenv((char*)var->base_string.self);
91 #endif
92 #endif
93 ret_val = 0;
94 } else {
95 #ifdef HAVE_SETENV
96 value = si_copy_to_simple_base_string(value);
97 ret_val = setenv((char*)var->base_string.self,
98 (char*)value->base_string.self, 1);
99 #else
100 value = cl_format(4, ECL_NIL, @"~A=~A", var,
101 value);
102 value = si_copy_to_simple_base_string(value);
103 putenv((char*)value->base_string.self);
104 #endif
105 }
106 if (ret_val == -1)
107 CEerror(ECL_T, "SI:SETENV failed: insufficient space in environment.",
108 1, ECL_NIL);
109 ecl_return1(the_env, value);
110 }
111 #endif
112
113 cl_object
114 si_environ(void)
115 {
116 cl_object output = ECL_NIL;
117 #ifdef HAVE_ENVIRON
118 char **p;
119 for (p = environ; *p; p++) {
120 output = CONS(ecl_make_constant_base_string(*p,-1), output);
121 }
122 output = cl_nreverse(output);
123 #else
124 # if defined(ECL_MS_WINDOWS_HOST)
125 LPTCH p;
126 for (p = GetEnvironmentStrings(); *p; ) {
127 output = CONS(ecl_make_constant_base_string(p,-1), output);
128 do { (void)0; } while (*(p++));
129 }
130 output = cl_nreverse(output);
131 # endif
132 #endif /* HAVE_ENVIRON */
133 @(return output);
134 }
135
136 cl_object
137 si_getpid(void)
138 {
139 #if defined(NACL)
140 FElibc_error("si_getpid not implemented",1);
141 @(return ECL_NIL);
142 #else
143 @(return ecl_make_fixnum(getpid()));
144 #endif
145 }
146
147 cl_object
148 si_getuid(void)
149 {
150 #if defined(ECL_MS_WINDOWS_HOST)
151 @(return ecl_make_fixnum(0));
152 #else
153 @(return ecl_make_integer(getuid()));
154 #endif
155 }
156
157 ecl_def_ct_base_string(fake_in_name, "PIPE-READ-ENDPOINT", 18, static, const);
158 ecl_def_ct_base_string(fake_out_name, "PIPE-WRITE-ENDPOINT", 19, static, const);
159
160 cl_object
161 si_make_pipe()
162 {
163 #if defined(NACL)
164 FElibc_error("si_make_pipe not implemented",1);
165 @(return ECL_NIL);
166 #else
167 cl_object output;
168 int fds[2], ret;
169 #if defined(ECL_MS_WINDOWS_HOST)
170 ret = _pipe(fds, 4096, _O_BINARY);
171 #else
172 ret = pipe(fds);
173 #endif
174 if (ret < 0) {
175 FElibc_error("Unable to create pipe", 0);
176 output = ECL_NIL;
177 } else {
178 cl_object in = ecl_make_stream_from_fd(fake_in_name, fds[0], ecl_smm_input, 8,
179 ECL_STREAM_DEFAULT_FORMAT, ECL_NIL);
180 cl_object out = ecl_make_stream_from_fd(fake_out_name, fds[1], ecl_smm_output, 8,
181 ECL_STREAM_DEFAULT_FORMAT, ECL_NIL);
182 output = cl_make_two_way_stream(in, out);
183 }
184 @(return output);
185 #endif
186 }
187
188 static cl_object
189 from_list_to_execve_argument(cl_object l, char ***environp)
190 {
191 cl_object p;
192 cl_index j, total_size = 0, nstrings = 0;
193 cl_object buffer, buffer_stream;
194 char **my_environ;
195 for (p = l; !Null(p); p = ECL_CONS_CDR(p)) {
196 cl_object s = ECL_CONS_CAR(p);
197 total_size += s->base_string.fillp + 1;
198 nstrings++;
199 }
200 buffer = ecl_alloc_adjustable_base_string(total_size + 1);
201 my_environ = ecl_alloc((nstrings + 1) * sizeof(char*));
202 buffer_stream = si_make_sequence_output_stream(1, buffer);
203 for (j = 0, p = l; !Null(p); p = ECL_CONS_CDR(p)) {
204 cl_object s = ECL_CONS_CAR(p);
205 my_environ[j++] = (char*)buffer->base_string.self + buffer->base_string.fillp;
206 si_do_write_sequence(s, buffer_stream, ecl_make_fixnum(0), ECL_NIL);
207 ecl_write_char(0, buffer_stream);
208 }
209 ecl_write_char(0, buffer_stream);
210 my_environ[j] = 0;
211 if (environp) *environp = my_environ;
212 return buffer;
213 }
214
215 cl_object
216 si_waitpid(cl_object pid, cl_object wait)
217 {
218 cl_object status, code;
219 #if defined(NACL)
220 FElibc_error("si_waitpid not implemented",1);
221 @(return ECL_NIL);
222 #elif defined(ECL_MS_WINDOWS_HOST)
223 cl_env_ptr the_env = ecl_process_env();
224 HANDLE *hProcess = ecl_foreign_data_pointer_safe(pid);
225 DWORD exitcode;
226 int ok;
227 WaitForSingleObject(*hProcess, Null(wait)? 0 : INFINITE);
228 ecl_disable_interrupts_env(the_env);
229 ok = GetExitCodeProcess(*hProcess, &exitcode);
230 if (!ok) {
231 status = @':error';
232 code = ECL_NIL;
233 } else if (exitcode == STILL_ACTIVE) {
234 status = @':running';
235 code = ECL_NIL;
236 } else {
237 status = @':exited';
238 code = ecl_make_fixnum((int)exitcode);
239 pid->foreign.data = NULL;
240 CloseHandle(*hProcess);
241 }
242 ecl_enable_interrupts_env(the_env);
243 #else
244 int code_int, error;
245
246 if (Null(wait))
247 error = waitpid(ecl_to_fix(pid), &code_int, WNOHANG | WUNTRACED | WCONTINUED);
248 else
249 error = waitpid(ecl_to_fix(pid), &code_int, 0);
250
251 if (error < 0) {
252 if (errno == EINTR) {
253 status = @':abort';
254 } else {
255 status = @':error';
256 }
257 code = ECL_NIL;
258 pid = ECL_NIL;
259 } else if (error == 0) {
260 status = ECL_NIL;
261 code = ECL_NIL;
262 pid = ECL_NIL;
263 } else {
264 pid = ecl_make_fixnum(error);
265 if (WIFEXITED(code_int)) {
266 status = @':exited';
267 code = ecl_make_fixnum(WEXITSTATUS(code_int));
268 } else if (WIFSIGNALED(code_int)) {
269 status = @':signaled';
270 code = ecl_make_fixnum(WTERMSIG(code_int));
271 } else if (WIFSTOPPED(code_int)) {
272 status = @':stopped';
273 code = ecl_make_fixnum(WSTOPSIG(code_int));
274 } else if (WIFCONTINUED(code_int)) {
275 status = @':resumed';
276 code = ecl_make_fixnum(SIGCONT);
277 } else {
278 status = @':running';
279 code = ECL_NIL;
280 }
281 }
282 #endif
283 @(return status code pid);
284 }
285
286 #if !defined(ECL_MS_WINDOWS_HOST)
287 cl_object
288 si_killpid(cl_object pid, cl_object signal) {
289 int ret = kill(ecl_fixnum(pid), ecl_fixnum(signal));
290 return ecl_make_fixnum(ret);
291 }
292 #endif
293
294 #if defined(ECL_MS_WINDOWS_HOST)
295 static cl_object
296 make_windows_handle(HANDLE h)
297 {
298 cl_object foreign = ecl_allocate_foreign_data(@':pointer-void',
299 sizeof(HANDLE*));
300 HANDLE *ph = (HANDLE*)foreign->foreign.data;
301 *ph = h;
302 return foreign;
303 }
304 #endif
305
306 #if defined(ECL_MS_WINDOWS_HOST)
307 HANDLE
308 ecl_stream_to_HANDLE(cl_object s, bool output)
309 {
310 if (ecl_unlikely(!ECL_ANSI_STREAM_P(s)))
311 return INVALID_HANDLE_VALUE;
312 switch ((enum ecl_smmode)s->stream.mode) {
313 #if defined(ECL_WSOCK)
314 case ecl_smm_input_wsock:
315 case ecl_smm_output_wsock:
316 case ecl_smm_io_wsock:
317 #endif
318 case ecl_smm_io_wcon:
319 return (HANDLE)IO_FILE_DESCRIPTOR(s);
320 default: {
321 int stream_descriptor = ecl_stream_to_handle(s, output);
322 return (stream_descriptor < 0)?
323 INVALID_HANDLE_VALUE:
324 (HANDLE)_get_osfhandle(stream_descriptor);
325 }
326 }
327 }
328 #endif
329
330 #if defined(ECL_MS_WINDOWS_HOST)
331 static void
332 create_descriptor(cl_object stream, cl_object direction,
333 HANDLE *child, int *parent) {
334 SECURITY_ATTRIBUTES attr;
335 HANDLE current = GetCurrentProcess();
336 attr.nLength = sizeof(SECURITY_ATTRIBUTES);
337 attr.lpSecurityDescriptor = NULL;
338 attr.bInheritHandle = TRUE;
339
340 if (stream == @':stream') {
341 /* Creates a pipe that we can write to and the child reads
342 from. We duplicate one extreme of the pipe so that the child
343 does not inherit it. */
344 HANDLE tmp;
345 if (direction == @':input') {
346 if (CreatePipe(child, &tmp, &attr, 0) == 0)
347 return;
348 if (DuplicateHandle(current, tmp, current,
349 &tmp, 0, FALSE,
350 DUPLICATE_CLOSE_SOURCE |
351 DUPLICATE_SAME_ACCESS) == 0)
352 return;
353
354 *parent = _open_osfhandle((intptr_t)tmp, _O_WRONLY);
355 }
356 else /* if (direction == @':output') */ {
357 if (CreatePipe(&tmp, child, &attr, 0) == 0)
358 return;
359 if (DuplicateHandle(current, tmp, current,
360 &tmp, 0, FALSE,
361 DUPLICATE_CLOSE_SOURCE |
362 DUPLICATE_SAME_ACCESS) == 0)
363 return;
364
365 *parent = _open_osfhandle((intptr_t)tmp, _O_RDONLY);
366 }
367
368 if (*parent < 0)
369 printf("open_osfhandle failed\n");
370 }
371 else if (!Null(cl_streamp(stream))) {
372 HANDLE stream_handle = ecl_stream_to_HANDLE
373 (stream, direction != @':input');
374 if (stream_handle == INVALID_HANDLE_VALUE) {
375 CEerror(@"Create a new stream.",
376 "~S argument to RUN-PROGRAM does not have a file handle:~%~S",
377 2, direction, stream);
378 create_descriptor(@':stream', direction, child, parent);
379 return;
380 }
381 DuplicateHandle(current, stream_handle,
382 current, child, 0, TRUE,
383 DUPLICATE_SAME_ACCESS);
384 }
385 else {
386 FEerror("Invalid ~S argument to EXT:RUN-PROGRAM.", 1, stream);
387 }
388 }
389 #else
390 static void
391 create_descriptor(cl_object stream, cl_object direction,
392 int *child, int *parent) {
393 if (stream == @':stream') {
394 int fd[2], ret;
395 ret = pipe(fd);
396 if (ret != 0) {
397 FElibc_error("Unable to create pipe", 0);
398 }
399 if (direction == @':input') {
400 *parent = fd[1];
401 *child = fd[0];
402 } else {
403 *parent = fd[0];
404 *child = fd[1];
405 }
406 }
407 else if (!Null(cl_streamp(stream))) {
408 *child = ecl_stream_to_handle
409 (stream, direction != @':input');
410 if (*child >= 0) {
411 *child = dup(*child);
412 } else {
413 CEerror(@"Create a new stream.",
414 "~S argument to RUN-PROGRAM does not have a file handle:~%~S",
415 2, direction, stream);
416 create_descriptor(@':stream', direction, child, parent);
417 return;
418 }
419 }
420 else {
421 FEerror("Invalid ~S argument to EXT:RUN-PROGRAM.", 1, stream);
422 }
423 }
424 #endif
425
426
427 cl_object
428 si_run_program_inner(cl_object command, cl_object argv, cl_object my_environ, cl_object wait)
429 {
430 cl_env_ptr the_env = ecl_process_env();
431 int parent_write = 0, parent_read = 0, parent_error = 0;
432 cl_object pid, stream_read, exit_status;
433
434 #if defined(ECL_MS_WINDOWS_HOST)
435 argv = cl_format(4, ECL_NIL,
436 @"~A~{ ~A~}",
437 command, argv);
438 #else
439 argv = CONS(command, argv);
440 #endif
441
442 pid = si_spawn_subprocess(command, argv, my_environ, @':stream', @':stream', @':output');
443 parent_write = ecl_fixnum(ecl_nth_value(the_env, 1));
444 parent_read = ecl_fixnum(ecl_nth_value(the_env, 2));
445 parent_error = ecl_fixnum(ecl_nth_value(the_env, 3));
446
447 /* descriptor is closed in the stream finalizer */
448 stream_read = ecl_make_stream_from_fd(command, parent_read,
449 ecl_smm_input, 8,
450 ECL_STREAM_DEFAULT_FORMAT,
451 @':default');
452
453 if (wait != ECL_NIL) {
454 si_waitpid(pid, ECL_T);
455 exit_status = ecl_nth_value(the_env, 1);
456 } else {
457 exit_status = ECL_NIL;
458 }
459
460 /* close unused descriptors */
461 close(parent_write);
462 close(parent_error);
463
464 @(return stream_read exit_status pid)
465 }
466
467 cl_object
468 si_spawn_subprocess(cl_object command, cl_object argv, cl_object my_environ,
469 cl_object input, cl_object output, cl_object error) {
470
471 int parent_write = 0, parent_read = 0, parent_error = 0;
472 cl_object pid;
473
474 /* my_environ is either a list or `:default'. */
475 if (!ECL_LISTP(my_environ) && !ecl_eql(my_environ, @':default')) {
476 FEerror("Malformed :ENVIRON argument to EXT:RUN-PROGRAM.", 0);
477 }
478
479 #if defined(ECL_MS_WINDOWS_HOST)
480 {
481 BOOL ok;
482 DWORD saved_errno;
483 STARTUPINFO st_info;
484 PROCESS_INFORMATION pr_info;
485 HANDLE child_stdout, child_stdin, child_stderr;
486 HANDLE current = GetCurrentProcess();
487 cl_object env_buffer;
488 char *env = NULL;
489
490 argv = si_string_to_octets(5, argv,
491 @':null-terminate', ECL_T,
492 @':element-type', @'base-char');
493 if (ECL_LISTP(my_environ)) {
494 env_buffer = from_list_to_execve_argument(my_environ, NULL);
495 env = (char*)env_buffer->base_string.self;
496 }
497
498 create_descriptor(input, @':input', &child_stdin, &parent_write);
499 create_descriptor(output, @':output', &child_stdout, &parent_read);
500 if (error == @':output') {
501 /* The child inherits a duplicate of its own output handle. */
502 DuplicateHandle(current, child_stdout, current,
503 &child_stderr, 0, TRUE,
504 DUPLICATE_SAME_ACCESS);
505 /* Same for the parent_read and parent_error. */
506 parent_error = dup(parent_read);
507 }
508 else
509 create_descriptor(error, @':output', &child_stderr, &parent_error);
510
511 ZeroMemory(&st_info, sizeof(STARTUPINFO));
512 st_info.cb = sizeof(STARTUPINFO);
513 st_info.lpTitle = NULL; /* No window title, just exec name */
514 st_info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; /* Specify std{in,out,err} */
515 st_info.wShowWindow = SW_HIDE;
516 st_info.hStdInput = child_stdin;
517 st_info.hStdOutput = child_stdout;
518 st_info.hStdError = child_stderr;
519 ZeroMemory(&pr_info, sizeof(PROCESS_INFORMATION));
520
521 /* Command is passed as is from argv. It is responsibility of
522 higher level interface to decide, whenever arguments should be
523 quoted or left as-is. */
524 ok = CreateProcess(NULL, (char*)argv->base_string.self,
525 NULL, NULL, /* lpProcess/ThreadAttributes */
526 TRUE, /* Inherit handles (for files) */
527 0, /* dwCreationFlags */
528 env, /* Inherit environment */
529 NULL, /* Current directory */
530 &st_info, /* Startup info */
531 &pr_info); /* Process info */
532
533 /* Child handles must be closed in the parent process */
534 /* otherwise the created pipes are never closed */
535 if (ok) {
536 CloseHandle(pr_info.hThread);
537 pid = make_windows_handle(pr_info.hProcess);
538 } else {
539 pid = ECL_NIL;
540 saved_errno = GetLastError();
541 }
542
543 if (child_stdin) CloseHandle(child_stdin);
544 if (child_stdout) CloseHandle(child_stdout);
545 if (child_stderr) CloseHandle(child_stderr);
546
547 if (Null(pid)) {
548 if (parent_write) close(parent_write);
549 if (parent_read) close(parent_read);
550 if (parent_error > 0) close(parent_error);
551 SetLastError(saved_errno);
552 FEwin32_error("Could not spawn subprocess to run ~S.", 1, command);
553 }
554 }
555 #elif !defined(NACL) /* All POSIX but NaCL/pNaCL */
556 {
557 cl_object command_encoded = si_string_to_octets(3, command, @':null-terminate', ECL_T);
558 int child_pid;
559 int child_stdin, child_stdout, child_stderr;
560 int saved_errno;
561
562 create_descriptor(input, @':input', &child_stdin, &parent_write);
563 create_descriptor(output, @':output', &child_stdout, &parent_read);
564 if (error == @':output') {
565 child_stderr = child_stdout;
566 parent_error = dup(parent_read);
567 } else {
568 create_descriptor(error, @':output', &child_stderr, &parent_error);
569 }
570
571 child_pid = fork();
572 if (child_pid == 0) {
573 /* Child */
574 int j;
575 cl_object p;
576 char **argv_ptr = ecl_alloc((ecl_length(argv) + 1) * sizeof(char*));
577 for (p = argv, j = 0; p != ECL_NIL; p = ECL_CONS_CDR(p)) {
578 cl_object arg = si_string_to_octets(3, ECL_CONS_CAR(p), @':null-terminate', ECL_T);
579 argv_ptr[j++] = (char*)arg->base_string.self;
580 }
581 argv_ptr[j] = NULL;
582
583 if (parent_write) close(parent_write);
584 if (parent_read) close(parent_read);
585 if (parent_error) close(parent_error);
586
587 dup2(child_stdin, STDIN_FILENO);
588 dup2(child_stdout, STDOUT_FILENO);
589 dup2(child_stderr, STDERR_FILENO);
590
591 if (ECL_LISTP(my_environ)) {
592 char **pstrings;
593 from_list_to_execve_argument(my_environ, &pstrings);
594 #if defined(HAVE_ENVIRON)
595 environ = pstrings;
596 execvp((char*)command_encoded->base_string.self, argv_ptr);
597 #else
598 execve((char*)command_encoded->base_string.self, argv_ptr, pstrings);
599 #endif
600 } else {
601 execvp((char*)command_encoded->base_string.self, argv_ptr);
602 }
603 /* at this point exec has failed */
604 perror("exec");
605 _exit(EXIT_FAILURE);
606 } else if (child_pid > 0) {
607 pid = ecl_make_fixnum(child_pid);
608 } else {
609 pid = ECL_NIL;
610 saved_errno = errno;
611 }
612
613 close(child_stdin);
614 close(child_stdout);
615 if (!(error == @':output')) close(child_stderr);
616
617 if (Null(pid)) {
618 if (parent_write) close(parent_write);
619 if (parent_read) close(parent_read);
620 if (parent_error > 0) close(parent_error);
621 errno = saved_errno;
622 FElibc_error("Could not spawn subprocess to run ~S.", 1, command);
623 }
624 }
625 #else /* NACL */
626 {
627 FEerror("ext:run-program not implemented", 0);
628 @(return ECL_NIL);
629 }
630 #endif
631
632 @(return pid
633 ecl_make_fixnum(parent_write)
634 ecl_make_fixnum(parent_read)
635 ecl_make_fixnum(parent_error))
636 }