File: unix.c

package info (click to toggle)
swi-prolog 8.0.2+dfsg-3+deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 72,036 kB
  • sloc: ansic: 349,612; perl: 306,654; java: 5,208; cpp: 4,436; sh: 3,042; ruby: 1,594; yacc: 845; makefile: 136; xml: 82; sed: 12; sql: 6
file content (538 lines) | stat: -rw-r--r-- 11,387 bytes parent folder | download | duplicates (3)
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
/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (c)  2008-2015, University of Amsterdam
                              VU University Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. 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.

    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 OWNER 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.
*/

#include <config.h>

#include <SWI-Stream.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <assert.h>
#include "clib.h"
#include <signal.h>
#include <string.h>
#include <errno.h>
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#ifdef HAVE_CRT_EXTERNS_H
#include <crt_externs.h>
#endif

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Unix process management.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

static IOSTREAM *
name_to_stream(const char *name)
{ IOSTREAM *s;
  term_t t = PL_new_term_ref();

  PL_put_atom_chars(t, name);
  if ( PL_get_stream_handle(t, &s) )
    return s;

  return NULL;
}


static void
flush_stream(const char *name)
{ IOSTREAM *s;

  if ( (s = name_to_stream(name)) )
    Sflush(s);

  PL_release_stream(s);
}



static foreign_t
pl_fork(term_t a0)
{ pid_t pid;

  flush_stream("user_output");		/* general call to flush all IO? */

  if ( (pid = fork()) < 0 )
    return PL_resource_error("memory");

  if ( pid > 0 )
  { return PL_unify_integer(a0, pid);
  } else
  { PL_set_prolog_flag("pid", PL_INTEGER|FF_FORCE, (intptr_t)getpid());

    return PL_unify_atom_chars(a0, "child");
  }
}


#define free_argv(n) \
	{ int _k; \
	  for( _k=1; _k <= n; _k++) \
	    free(argv[_k]); \
	  free(argv); \
	}

static foreign_t
pl_exec(term_t cmd)
{ size_t argc;
  atom_t name;

  if ( PL_get_name_arity(cmd, &name, &argc) )
  { term_t a = PL_new_term_ref();
    char **argv = malloc(sizeof(char*) * (argc + 2));
    size_t i;

    argv[0] = (char *)PL_atom_chars(name);

    for(i=1; i<=argc; i++)
    { char *s;

      if ( PL_get_arg(i, cmd, a) &&
	   PL_get_chars(a, &s, CVT_ALL|REP_MB|BUF_MALLOC) )
	argv[i] = s;
      else
      { free_argv(i-1);
	return pl_error("exec", 1, NULL, ERR_ARGTYPE, i, a, "atomic");
      }
    }
    argv[argc+1] = NULL;

    execvp(argv[0], argv);
    free_argv(argc);
    return pl_error("exec", 1, NULL, ERR_ERRNO, errno, "execute", "command", cmd);
  }

  return pl_error("exec", 1, NULL, ERR_ARGTYPE, 1, cmd, "compound");
}


static foreign_t
pl_wait(term_t Pid, term_t Status)
{ int status;
  pid_t pid = -1;
  int pid_i;

  if ( PL_is_variable(Pid) )
  { pid = -1;
  } else if ( PL_get_integer_ex(Pid, &pid_i) )
  { if ( pid_i <= 0 )
      return PL_domain_error("process_id", Pid);
    pid = pid_i;
  } else
    return FALSE;

  for(;;)
  { pid = waitpid(pid, &status, 0);
    if ( pid == -1 && errno == EINTR )
    { if ( PL_handle_signals() < 0 )
	return FALSE;
    } else
    { break;
    }
  }

  if ( pid == -1 )
    return pl_error("wait", 2, NULL, ERR_ERRNO, errno, "wait", "process", Pid);

  if ( PL_unify_integer(Pid, pid) )
  { if ( WIFEXITED(status) )
      return PL_unify_term(Status,
			   CompoundArg("exited", 1),
			   IntArg(WEXITSTATUS(status)));
    if ( WIFSIGNALED(status) )
      return PL_unify_term(Status,
			   CompoundArg("signaled", 1),
			   IntArg(WTERMSIG(status)));
    if ( WIFSTOPPED(status) )
      return PL_unify_term(Status,
			   CompoundArg("stopped", 1),
			   IntArg(WSTOPSIG(status)));
    assert(0);
  }

  return FALSE;
}


static foreign_t
pl_kill(term_t Pid, term_t Sig)
{ int pid;
  int sig;

  if ( !PL_get_integer(Pid, &pid) )
    return pl_error("kill", 2, NULL, ERR_ARGTYPE, 1, Pid, "pid");
  if ( !PL_get_signum_ex(Sig, &sig) )
    return FALSE;

  if ( kill(pid, sig) < 0 )
    return pl_error("kill", 2, NULL, ERR_ERRNO, errno,
		    "kill", "process", Pid);

  return TRUE;
}


		 /*******************************
		 *	   STREAM STUFF		*
		 *******************************/

static foreign_t
pl_pipe(term_t Read, term_t Write)
{ int fd[2];
  IOSTREAM *in, *out;

  if ( pipe(fd) != 0 )
    return pl_error("pipe", 2, NULL, ERR_ERRNO, errno, "create", "pipe", 0);

  in  = Sfdopen(fd[0], "r");
  out = Sfdopen(fd[1], "w");

  if ( PL_open_stream(Read, in) &&
       PL_open_stream(Write, out) )
    return TRUE;

  return FALSE;
}


static int
get_stream_no(term_t t, IOSTREAM **s, int *fn)
{ if ( PL_get_integer(t, fn) )
    return TRUE;
  if ( PL_get_stream_handle(t, s) )
  { *fn = Sfileno(*s);
    return TRUE;
  }

  return FALSE;
}


static foreign_t
pl_dup(term_t from, term_t to)
{ IOSTREAM *f = NULL, *t = NULL;
  int rval = FALSE;
  int fn, tn;

  if ( !get_stream_no(from, &f, &fn) ||
       !get_stream_no(to, &t, &tn) )
    goto out;

  if ( dup2(fn, tn) < 0 )
  { pl_error("dup", 2, NULL, ERR_ERRNO, errno, "dup", "stream", from);
    goto out;
  } else
  { rval = TRUE;
  }

out:
  if ( f )
    PL_release_stream(f);
  if ( t )
    PL_release_stream(t);

  return rval;
}


static foreign_t
pl_environ(term_t l)
{
#ifdef HAVE__NSGETENVIRON
  char **environ = *_NSGetEnviron();
#else
  extern char **environ;
#endif
  char **e;
  term_t t = PL_copy_term_ref(l);
  term_t t2 = PL_new_term_ref();
  term_t nt = PL_new_term_ref();
  term_t vt = PL_new_term_ref();
  functor_t FUNCTOR_equal2 = PL_new_functor(PL_new_atom("="), 2);

  for(e = environ; *e; e++)
  { char *s = strchr(*e, '=');

    if ( !s )
      s = *e + strlen(*e);

    { int len = s-*e;
      char *name = alloca(len+1);

      strncpy(name, *e, len);
      name[len] = '\0';
      PL_put_atom_chars(nt, name);
      PL_put_atom_chars(vt, s+1);
      if ( !PL_cons_functor(nt, FUNCTOR_equal2, nt, vt) ||
	   !PL_unify_list(t, t2, t) ||
	   !PL_unify(t2, nt) )
	return FALSE;
    }
  }

  return PL_unify_nil(t);
}


		 /*******************************
		 *	    DEAMON IO		*
		 *******************************/

static IOSTREAM *log_stream = NULL;		/* Write log output here */

static ssize_t
read_eof(void *handle, char *buf, size_t count)
{ return 0;
}


static ssize_t
write_null(void *handle, char *buf, size_t count)
{ if ( log_stream )
  { Slock(log_stream);
    Sfwrite(buf, count, sizeof(char), log_stream);
    Sunlock(log_stream);
  }

  return count;
}


static long
seek_error(void *handle, long pos, int whence)
{ return -1;
}


static int
close_null(void *handle)
{ return 0;
}


static IOFUNCTIONS dummy =
{ read_eof,
  write_null,
  seek_error,
  close_null,
  NULL
};


static void
close_underlying_fd(IOSTREAM *s)
{ if ( s )
  { int fd;

    if ( (fd = Sfileno(s)) >= 0 && (s->flags & SIO_ISATTY) )
    { close(fd);

      s->functions = &dummy;
      s->flags &= ~SIO_FILE|SIO_ISATTY;	/* no longer a file */
      s->flags |= SIO_LBUF;		/* do line-buffering */
    }
  }
}


static void
detach_process(void)
{
#ifdef HAVE_SETSID
  setsid();
#else
  int fd;

  if ( (fd = open("/dev/tty", 2)) )
  { ioctl(fd, TIOCNOTTY, NULL);		/* detach from controlling tty */
    close(fd);
  }
#endif
}

static foreign_t
pl_detach_IO(term_t stream)
{ if ( !log_stream )
  { IOSTREAM *s;

    if ( !PL_get_stream_handle(stream, &s) )
      return FALSE;
    log_stream = s;
    PL_release_stream(s);

    close_underlying_fd(Serror);
    close_underlying_fd(Soutput);
    close_underlying_fd(Sinput);

    detach_process();
  }

  return TRUE;
}

#if defined(HAVE_PRCTL) && defined(HAVE_SYS_PRCTL_H)
#include <sys/prctl.h>

static foreign_t
pl_prctl(term_t option)
{ atom_t name;
  size_t arity;

  if ( PL_get_name_arity(option, &name, &arity) )
  { const char *opt = PL_atom_chars(name);
    term_t a = PL_new_term_refs(4);

    if ( arity <= 4 )
    { size_t i;

      for(i=0; i<arity; i++)
	_PL_get_arg(i+1, option, a+i);

      if ( strcmp(opt, "set_dumpable") == 0 && arity == 1 )
      { int i;

	if ( !PL_get_bool_ex(a+0, &i) )
	  return FALSE;
	if ( prctl(PR_SET_DUMPABLE, i, 0, 0, 0) >= 0 )
	  return TRUE;
	return pl_error("prctl", 1, NULL, ERR_ERRNO,
			errno, "set_dumpable", "process", a+0);
      } else if ( strcmp(opt, "get_dumpable") == 0 && arity == 1 )
      { int rc = prctl(PR_GET_DUMPABLE, 0,0,0,0);

	if ( rc >= 0 )
	  return PL_unify_bool(a+0, rc);
	return pl_error("prctl", 1, NULL, ERR_ERRNO,
			errno, "get_dumpable", "process", a+0);
      }
    }

    return PL_domain_error("prctl_option", option);
  } else
  { return PL_type_error("compound", option);
  }
}


#else
#undef HAVE_PRCTL
#endif

#ifdef HAVE_SYSCONF
#include <unistd.h>

struct conf
{ int         code;
  const char *name;
};

static const struct conf confs[] =
{ {_SC_ARG_MAX, "arg_max" },
  {_SC_CHILD_MAX, "child_max" },
  {_SC_CLK_TCK, "clk_tck" },
  {_SC_OPEN_MAX, "open_max" },
  {_SC_PAGESIZE, "pagesize" },
#ifdef _SC_PHYS_PAGES
  {_SC_PHYS_PAGES, "phys_pages" },
#endif
#ifdef _SC_AVPHYS_PAGES
  {_SC_AVPHYS_PAGES, "avphys_pages" },
#endif
#ifdef _SC_NPROCESSORS_CONF
  {_SC_NPROCESSORS_CONF, "nprocessors_conf" },
#endif
#ifdef _SC_NPROCESSORS_ONLN
  {_SC_NPROCESSORS_ONLN, "nprocessors_onln" },
#endif
  {0, NULL}
};

static foreign_t
pl_sysconf(term_t conf)
{ atom_t name;
  size_t arity;

  if ( PL_get_name_arity(conf, &name, &arity) )
  { const char *s = PL_atom_chars(name);
    const struct conf *c = confs;

    for(c=confs; c->name; c++)
    { if ( strcmp(c->name, s) == 0 )
      { term_t a;

	return ( (a = PL_new_term_ref()) &&
		 PL_get_arg(1, conf, a) &&
		 PL_unify_integer(a, sysconf(c->code))
	       );
      }
    }

    return FALSE;
  }
  return PL_type_error("compound", conf);
}
#endif



install_t
install_unix()
{ PL_register_foreign("fork_",     1, pl_fork, 0);
  PL_register_foreign("exec",      1, pl_exec, 0);
  PL_register_foreign("wait",      2, pl_wait, 0);
  PL_register_foreign("kill",      2, pl_kill, 0);
  PL_register_foreign("pipe",      2, pl_pipe, 0);
  PL_register_foreign("dup",       2, pl_dup, 0);
  PL_register_foreign("detach_IO", 1, pl_detach_IO, 0);
  PL_register_foreign("environ",   1, pl_environ, 0);
#ifdef HAVE_PRCTL
  PL_register_foreign("prctl",     1, pl_prctl, 0);
#endif
#ifdef HAVE_SYSCONF
  PL_register_foreign("sysconf",   1, pl_sysconf, 0);
#endif
}