Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
process.c
1/**********************************************************************
2
3 process.c -
4
5 $Author$
6 created at: Tue Aug 10 14:30:50 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
11
12**********************************************************************/
13
14#include "ruby/internal/config.h"
15
17
18#include <ctype.h>
19#include <errno.h>
20#include <signal.h>
21#include <stdarg.h>
22#include <stdio.h>
23#include <time.h>
24
25#ifdef HAVE_STDLIB_H
26# include <stdlib.h>
27#endif
28
29#ifdef HAVE_UNISTD_H
30# include <unistd.h>
31#endif
32
33#ifdef HAVE_FCNTL_H
34# include <fcntl.h>
35#endif
36
37#ifdef HAVE_PROCESS_H
38# include <process.h>
39#endif
40
41#ifndef EXIT_SUCCESS
42# define EXIT_SUCCESS 0
43#endif
44
45#ifndef EXIT_FAILURE
46# define EXIT_FAILURE 1
47#endif
48
49#ifdef HAVE_SYS_WAIT_H
50# include <sys/wait.h>
51#endif
52
53#ifdef HAVE_SYS_RESOURCE_H
54# include <sys/resource.h>
55#endif
56
57#ifdef HAVE_VFORK_H
58# include <vfork.h>
59#endif
60
61#ifdef HAVE_SYS_PARAM_H
62# include <sys/param.h>
63#endif
64
65#ifndef MAXPATHLEN
66# define MAXPATHLEN 1024
67#endif
68
69#include <sys/stat.h>
70
71#ifdef HAVE_SYS_TIME_H
72# include <sys/time.h>
73#endif
74
75#ifdef HAVE_SYS_TIMES_H
76# include <sys/times.h>
77#endif
78
79#ifdef HAVE_PWD_H
80# include <pwd.h>
81#endif
82
83#ifdef HAVE_GRP_H
84# include <grp.h>
85# ifdef __CYGWIN__
86int initgroups(const char *, rb_gid_t);
87# endif
88#endif
89
90#ifdef HAVE_SYS_ID_H
91# include <sys/id.h>
92#endif
93
94#ifdef __APPLE__
95# include <mach/mach_time.h>
96#endif
97
98#include "dln.h"
99#include "hrtime.h"
100#include "internal.h"
101#include "internal/bits.h"
102#include "internal/dir.h"
103#include "internal/error.h"
104#include "internal/eval.h"
105#include "internal/hash.h"
106#include "internal/io.h"
107#include "internal/numeric.h"
108#include "internal/object.h"
109#include "internal/process.h"
110#include "internal/thread.h"
111#include "internal/variable.h"
112#include "internal/warnings.h"
113#include "ruby/io.h"
114#include "ruby/st.h"
115#include "ruby/thread.h"
116#include "ruby/util.h"
117#include "ractor_core.h"
118#include "vm_core.h"
119#include "vm_sync.h"
120#include "ruby/ractor.h"
121
122/* define system APIs */
123#ifdef _WIN32
124#undef open
125#define open rb_w32_uopen
126#endif
127
128#if defined(HAVE_TIMES) || defined(_WIN32)
129/*********************************************************************
130 *
131 * Document-class: Process::Tms
132 *
133 * Placeholder for rusage
134 */
135static VALUE rb_cProcessTms;
136#endif
137
138#ifndef WIFEXITED
139#define WIFEXITED(w) (((w) & 0xff) == 0)
140#endif
141#ifndef WIFSIGNALED
142#define WIFSIGNALED(w) (((w) & 0x7f) > 0 && (((w) & 0x7f) < 0x7f))
143#endif
144#ifndef WIFSTOPPED
145#define WIFSTOPPED(w) (((w) & 0xff) == 0x7f)
146#endif
147#ifndef WEXITSTATUS
148#define WEXITSTATUS(w) (((w) >> 8) & 0xff)
149#endif
150#ifndef WTERMSIG
151#define WTERMSIG(w) ((w) & 0x7f)
152#endif
153#ifndef WSTOPSIG
154#define WSTOPSIG WEXITSTATUS
155#endif
156
157#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__)
158#define HAVE_44BSD_SETUID 1
159#define HAVE_44BSD_SETGID 1
160#endif
161
162#ifdef __NetBSD__
163#undef HAVE_SETRUID
164#undef HAVE_SETRGID
165#endif
166
167#ifdef BROKEN_SETREUID
168#define setreuid ruby_setreuid
169int setreuid(rb_uid_t ruid, rb_uid_t euid);
170#endif
171#ifdef BROKEN_SETREGID
172#define setregid ruby_setregid
173int setregid(rb_gid_t rgid, rb_gid_t egid);
174#endif
175
176#if defined(HAVE_44BSD_SETUID) || defined(__APPLE__)
177#if !defined(USE_SETREUID) && !defined(BROKEN_SETREUID)
178#define OBSOLETE_SETREUID 1
179#endif
180#if !defined(USE_SETREGID) && !defined(BROKEN_SETREGID)
181#define OBSOLETE_SETREGID 1
182#endif
183#endif
184
185static void check_uid_switch(void);
186static void check_gid_switch(void);
187static int exec_async_signal_safe(const struct rb_execarg *, char *, size_t);
188
189VALUE rb_envtbl(void);
190VALUE rb_env_to_hash(void);
191
192#if 1
193#define p_uid_from_name p_uid_from_name
194#define p_gid_from_name p_gid_from_name
195#endif
196
197#if defined(HAVE_UNISTD_H)
198# if defined(HAVE_GETLOGIN_R)
199# define USE_GETLOGIN_R 1
200# define GETLOGIN_R_SIZE_DEFAULT 0x100
201# define GETLOGIN_R_SIZE_LIMIT 0x1000
202# if defined(_SC_LOGIN_NAME_MAX)
203# define GETLOGIN_R_SIZE_INIT sysconf(_SC_LOGIN_NAME_MAX)
204# else
205# define GETLOGIN_R_SIZE_INIT GETLOGIN_R_SIZE_DEFAULT
206# endif
207# elif defined(HAVE_GETLOGIN)
208# define USE_GETLOGIN 1
209# endif
210#endif
211
212#if defined(HAVE_PWD_H)
213# if defined(HAVE_GETPWUID_R)
214# define USE_GETPWUID_R 1
215# elif defined(HAVE_GETPWUID)
216# define USE_GETPWUID 1
217# endif
218# if defined(HAVE_GETPWNAM_R)
219# define USE_GETPWNAM_R 1
220# elif defined(HAVE_GETPWNAM)
221# define USE_GETPWNAM 1
222# endif
223# if defined(HAVE_GETPWNAM_R) || defined(HAVE_GETPWUID_R)
224# define GETPW_R_SIZE_DEFAULT 0x1000
225# define GETPW_R_SIZE_LIMIT 0x10000
226# if defined(_SC_GETPW_R_SIZE_MAX)
227# define GETPW_R_SIZE_INIT sysconf(_SC_GETPW_R_SIZE_MAX)
228# else
229# define GETPW_R_SIZE_INIT GETPW_R_SIZE_DEFAULT
230# endif
231# endif
232# ifdef USE_GETPWNAM_R
233# define PREPARE_GETPWNAM \
234 VALUE getpw_buf = 0
235# define FINISH_GETPWNAM \
236 (getpw_buf ? (void)rb_str_resize(getpw_buf, 0) : (void)0)
237# define OBJ2UID1(id) obj2uid((id), &getpw_buf)
238# define OBJ2UID(id) obj2uid0(id)
239static rb_uid_t obj2uid(VALUE id, VALUE *getpw_buf);
240static inline rb_uid_t
241obj2uid0(VALUE id)
242{
243 rb_uid_t uid;
244 PREPARE_GETPWNAM;
245 uid = OBJ2UID1(id);
246 FINISH_GETPWNAM;
247 return uid;
248}
249# else
250# define PREPARE_GETPWNAM /* do nothing */
251# define FINISH_GETPWNAM /* do nothing */
252# define OBJ2UID1(id) obj2uid((id))
253# define OBJ2UID(id) obj2uid((id))
254static rb_uid_t obj2uid(VALUE id);
255# endif
256#else
257# define PREPARE_GETPWNAM /* do nothing */
258# define FINISH_GETPWNAM /* do nothing */
259# define OBJ2UID1(id) NUM2UIDT(id)
260# define OBJ2UID(id) NUM2UIDT(id)
261# ifdef p_uid_from_name
262# undef p_uid_from_name
263# define p_uid_from_name rb_f_notimplement
264# endif
265#endif
266
267#if defined(HAVE_GRP_H)
268# if defined(HAVE_GETGRNAM_R) && defined(_SC_GETGR_R_SIZE_MAX)
269# define USE_GETGRNAM_R
270# define GETGR_R_SIZE_INIT sysconf(_SC_GETGR_R_SIZE_MAX)
271# define GETGR_R_SIZE_DEFAULT 0x1000
272# define GETGR_R_SIZE_LIMIT 0x10000
273# endif
274# ifdef USE_GETGRNAM_R
275# define PREPARE_GETGRNAM \
276 VALUE getgr_buf = 0
277# define FINISH_GETGRNAM \
278 (getgr_buf ? (void)rb_str_resize(getgr_buf, 0) : (void)0)
279# define OBJ2GID1(id) obj2gid((id), &getgr_buf)
280# define OBJ2GID(id) obj2gid0(id)
281static rb_gid_t obj2gid(VALUE id, VALUE *getgr_buf);
282static inline rb_gid_t
283obj2gid0(VALUE id)
284{
285 rb_gid_t gid;
286 PREPARE_GETGRNAM;
287 gid = OBJ2GID1(id);
288 FINISH_GETGRNAM;
289 return gid;
290}
291static rb_gid_t obj2gid(VALUE id, VALUE *getgr_buf);
292# else
293# define PREPARE_GETGRNAM /* do nothing */
294# define FINISH_GETGRNAM /* do nothing */
295# define OBJ2GID1(id) obj2gid((id))
296# define OBJ2GID(id) obj2gid((id))
297static rb_gid_t obj2gid(VALUE id);
298# endif
299#else
300# define PREPARE_GETGRNAM /* do nothing */
301# define FINISH_GETGRNAM /* do nothing */
302# define OBJ2GID1(id) NUM2GIDT(id)
303# define OBJ2GID(id) NUM2GIDT(id)
304# ifdef p_gid_from_name
305# undef p_gid_from_name
306# define p_gid_from_name rb_f_notimplement
307# endif
308#endif
309
310#if SIZEOF_CLOCK_T == SIZEOF_INT
311typedef unsigned int unsigned_clock_t;
312#elif SIZEOF_CLOCK_T == SIZEOF_LONG
313typedef unsigned long unsigned_clock_t;
314#elif defined(HAVE_LONG_LONG) && SIZEOF_CLOCK_T == SIZEOF_LONG_LONG
315typedef unsigned LONG_LONG unsigned_clock_t;
316#endif
317#ifndef HAVE_SIG_T
318typedef void (*sig_t) (int);
319#endif
320
321#define id_exception idException
322static ID id_in, id_out, id_err, id_pid, id_uid, id_gid;
323static ID id_close, id_child;
324#ifdef HAVE_SETPGID
325static ID id_pgroup;
326#endif
327#ifdef _WIN32
328static ID id_new_pgroup;
329#endif
330static ID id_unsetenv_others, id_chdir, id_umask, id_close_others;
331static ID id_nanosecond, id_microsecond, id_millisecond, id_second;
332static ID id_float_microsecond, id_float_millisecond, id_float_second;
333static ID id_GETTIMEOFDAY_BASED_CLOCK_REALTIME, id_TIME_BASED_CLOCK_REALTIME;
334#ifdef CLOCK_REALTIME
335static ID id_CLOCK_REALTIME;
336# define RUBY_CLOCK_REALTIME ID2SYM(id_CLOCK_REALTIME)
337#endif
338#ifdef CLOCK_MONOTONIC
339static ID id_CLOCK_MONOTONIC;
340# define RUBY_CLOCK_MONOTONIC ID2SYM(id_CLOCK_MONOTONIC)
341#endif
342#ifdef CLOCK_PROCESS_CPUTIME_ID
343static ID id_CLOCK_PROCESS_CPUTIME_ID;
344# define RUBY_CLOCK_PROCESS_CPUTIME_ID ID2SYM(id_CLOCK_PROCESS_CPUTIME_ID)
345#endif
346#ifdef CLOCK_THREAD_CPUTIME_ID
347static ID id_CLOCK_THREAD_CPUTIME_ID;
348# define RUBY_CLOCK_THREAD_CPUTIME_ID ID2SYM(id_CLOCK_THREAD_CPUTIME_ID)
349#endif
350#ifdef HAVE_TIMES
351static ID id_TIMES_BASED_CLOCK_MONOTONIC;
352static ID id_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID;
353#endif
354#ifdef RUSAGE_SELF
355static ID id_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID;
356#endif
357static ID id_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID;
358#ifdef __APPLE__
359static ID id_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC;
360# define RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC ID2SYM(id_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC)
361#endif
362static ID id_hertz;
363#ifdef HAVE_WORKING_FORK
364static ID id__fork;
365#endif
366
367static rb_pid_t cached_pid;
368
369/* execv and execl are async-signal-safe since SUSv4 (POSIX.1-2008, XPG7) */
370#if defined(__sun) && !defined(_XPG7) /* Solaris 10, 9, ... */
371#define execv(path, argv) (rb_async_bug_errno("unreachable: async-signal-unsafe execv() is called", 0))
372#define execl(path, arg0, arg1, arg2, term) do { extern char **environ; execle((path), (arg0), (arg1), (arg2), (term), (environ)); } while (0)
373#define ALWAYS_NEED_ENVP 1
374#else
375#define ALWAYS_NEED_ENVP 0
376#endif
377
378static void
379assert_close_on_exec(int fd)
380{
381#if VM_CHECK_MODE > 0
382#if defined(HAVE_FCNTL) && defined(F_GETFD) && defined(FD_CLOEXEC)
383 int flags = fcntl(fd, F_GETFD);
384 if (flags == -1) {
385 static const char m[] = "reserved FD closed unexpectedly?\n";
386 (void)!write(2, m, sizeof(m) - 1);
387 return;
388 }
389 if (flags & FD_CLOEXEC) return;
390 rb_bug("reserved FD did not have close-on-exec set");
391#else
392 rb_bug("reserved FD without close-on-exec support");
393#endif /* FD_CLOEXEC */
394#endif /* VM_CHECK_MODE */
395}
396
397static inline int
398close_unless_reserved(int fd)
399{
400 if (rb_reserved_fd_p(fd)) { /* async-signal-safe */
401 assert_close_on_exec(fd);
402 return 0;
403 }
404 return close(fd); /* async-signal-safe */
405}
406
407/*#define DEBUG_REDIRECT*/
408#if defined(DEBUG_REDIRECT)
409
410static void
411ttyprintf(const char *fmt, ...)
412{
413 va_list ap;
414 FILE *tty;
415 int save = errno;
416#ifdef _WIN32
417 tty = fopen("con", "w");
418#else
419 tty = fopen("/dev/tty", "w");
420#endif
421 if (!tty)
422 return;
423
424 va_start(ap, fmt);
425 vfprintf(tty, fmt, ap);
426 va_end(ap);
427 fclose(tty);
428 errno = save;
429}
430
431static int
432redirect_dup(int oldfd)
433{
434 int ret;
435 ret = dup(oldfd);
436 ttyprintf("dup(%d) => %d\n", oldfd, ret);
437 return ret;
438}
439
440static int
441redirect_dup2(int oldfd, int newfd)
442{
443 int ret;
444 ret = dup2(oldfd, newfd);
445 ttyprintf("dup2(%d, %d) => %d\n", oldfd, newfd, ret);
446 return ret;
447}
448
449static int
450redirect_cloexec_dup(int oldfd)
451{
452 int ret;
453 ret = rb_cloexec_dup(oldfd);
454 ttyprintf("cloexec_dup(%d) => %d\n", oldfd, ret);
455 return ret;
456}
457
458static int
459redirect_cloexec_dup2(int oldfd, int newfd)
460{
461 int ret;
462 ret = rb_cloexec_dup2(oldfd, newfd);
463 ttyprintf("cloexec_dup2(%d, %d) => %d\n", oldfd, newfd, ret);
464 return ret;
465}
466
467static int
468redirect_close(int fd)
469{
470 int ret;
471 ret = close_unless_reserved(fd);
472 ttyprintf("close(%d) => %d\n", fd, ret);
473 return ret;
474}
475
476static int
477parent_redirect_open(const char *pathname, int flags, mode_t perm)
478{
479 int ret;
480 ret = rb_cloexec_open(pathname, flags, perm);
481 ttyprintf("parent_open(\"%s\", 0x%x, 0%o) => %d\n", pathname, flags, perm, ret);
482 return ret;
483}
484
485static int
486parent_redirect_close(int fd)
487{
488 int ret;
489 ret = close_unless_reserved(fd);
490 ttyprintf("parent_close(%d) => %d\n", fd, ret);
491 return ret;
492}
493
494#else
495#define redirect_dup(oldfd) dup(oldfd)
496#define redirect_dup2(oldfd, newfd) dup2((oldfd), (newfd))
497#define redirect_cloexec_dup(oldfd) rb_cloexec_dup(oldfd)
498#define redirect_cloexec_dup2(oldfd, newfd) rb_cloexec_dup2((oldfd), (newfd))
499#define redirect_close(fd) close_unless_reserved(fd)
500#define parent_redirect_open(pathname, flags, perm) rb_cloexec_open((pathname), (flags), (perm))
501#define parent_redirect_close(fd) close_unless_reserved(fd)
502#endif
503
504static VALUE
505get_pid(void)
506{
507 if (UNLIKELY(!cached_pid)) { /* 0 is not a valid pid */
508 cached_pid = getpid();
509 }
510 /* pid should be likely POSFIXABLE() */
511 return PIDT2NUM(cached_pid);
512}
513
514#if defined HAVE_WORKING_FORK || defined HAVE_DAEMON
515static void
516clear_pid_cache(void)
517{
518 cached_pid = 0;
519}
520#endif
521
522/*
523 * call-seq:
524 * Process.pid -> integer
525 *
526 * Returns the process ID of the current process:
527 *
528 * Process.pid # => 15668
529 *
530 */
531
532static VALUE
533proc_get_pid(VALUE _)
534{
535 return get_pid();
536}
537
538static VALUE
539get_ppid(void)
540{
541 return PIDT2NUM(getppid());
542}
543
544/*
545 * call-seq:
546 * Process.ppid -> integer
547 *
548 * Returns the process ID of the parent of the current process:
549 *
550 * puts "Pid is #{Process.pid}."
551 * fork { puts "Parent pid is #{Process.ppid}." }
552 *
553 * Output:
554 *
555 * Pid is 271290.
556 * Parent pid is 271290.
557 *
558 * May not return a trustworthy value on certain platforms.
559 */
560
561static VALUE
562proc_get_ppid(VALUE _)
563{
564 return get_ppid();
565}
566
567
568/*********************************************************************
569 *
570 * Document-class: Process::Status
571 *
572 * A Process::Status contains information about a system process.
573 *
574 * Thread-local variable <tt>$?</tt> is initially +nil+.
575 * Some methods assign to it a Process::Status object
576 * that represents a system process (either running or terminated):
577 *
578 * `ruby -e "exit 99"`
579 * stat = $? # => #<Process::Status: pid 1262862 exit 99>
580 * stat.class # => Process::Status
581 * stat.to_i # => 25344
582 * stat.stopped? # => false
583 * stat.exited? # => true
584 * stat.exitstatus # => 99
585 *
586 */
587
588static VALUE rb_cProcessStatus;
589
591 rb_pid_t pid;
592 int status;
593 int error;
594};
595
596static const rb_data_type_t rb_process_status_type = {
597 .wrap_struct_name = "Process::Status",
598 .function = {
599 .dmark = NULL,
600 .dfree = RUBY_DEFAULT_FREE,
601 .dsize = NULL,
602 },
603 .flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
604};
605
606static VALUE
607rb_process_status_allocate(VALUE klass)
608{
609 struct rb_process_status *data;
610 return TypedData_Make_Struct(klass, struct rb_process_status, &rb_process_status_type, data);
611}
612
613VALUE
615{
616 return GET_THREAD()->last_status;
617}
618
619/*
620 * call-seq:
621 * Process.last_status -> Process::Status or nil
622 *
623 * Returns a Process::Status object representing the most recently exited
624 * child process in the current thread, or +nil+ if none:
625 *
626 * Process.spawn('ruby', '-e', 'exit 13')
627 * Process.wait
628 * Process.last_status # => #<Process::Status: pid 14396 exit 13>
629 *
630 * Process.spawn('ruby', '-e', 'exit 14')
631 * Process.wait
632 * Process.last_status # => #<Process::Status: pid 4692 exit 14>
633 *
634 * Process.spawn('ruby', '-e', 'exit 15')
635 * # 'exit 15' has not been reaped by #wait.
636 * Process.last_status # => #<Process::Status: pid 4692 exit 14>
637 * Process.wait
638 * Process.last_status # => #<Process::Status: pid 1380 exit 15>
639 *
640 */
641static VALUE
642proc_s_last_status(VALUE mod)
643{
644 return rb_last_status_get();
645}
646
647VALUE
648rb_process_status_new(rb_pid_t pid, int status, int error)
649{
650 VALUE last_status = rb_process_status_allocate(rb_cProcessStatus);
651 struct rb_process_status *data = RTYPEDDATA_GET_DATA(last_status);
652 data->pid = pid;
653 data->status = status;
654 data->error = error;
655
656 rb_obj_freeze(last_status);
657 return last_status;
658}
659
660static VALUE
661process_status_dump(VALUE status)
662{
663 VALUE dump = rb_class_new_instance(0, 0, rb_cObject);
664 struct rb_process_status *data;
665 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
666 if (data->pid) {
667 rb_ivar_set(dump, id_status, INT2NUM(data->status));
668 rb_ivar_set(dump, id_pid, PIDT2NUM(data->pid));
669 }
670 return dump;
671}
672
673static VALUE
674process_status_load(VALUE real_obj, VALUE load_obj)
675{
676 struct rb_process_status *data = rb_check_typeddata(real_obj, &rb_process_status_type);
677 VALUE status = rb_attr_get(load_obj, id_status);
678 VALUE pid = rb_attr_get(load_obj, id_pid);
679 data->pid = NIL_P(pid) ? 0 : NUM2PIDT(pid);
680 data->status = NIL_P(status) ? 0 : NUM2INT(status);
681 return real_obj;
682}
683
684void
685rb_last_status_set(int status, rb_pid_t pid)
686{
687 GET_THREAD()->last_status = rb_process_status_new(pid, status, 0);
688}
689
690static void
691last_status_clear(rb_thread_t *th)
692{
693 th->last_status = Qnil;
694}
695
696void
697rb_last_status_clear(void)
698{
699 last_status_clear(GET_THREAD());
700}
701
702static rb_pid_t
703pst_pid(VALUE status)
704{
705 struct rb_process_status *data;
706 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
707 return data->pid;
708}
709
710static int
711pst_status(VALUE status)
712{
713 struct rb_process_status *data;
714 TypedData_Get_Struct(status, struct rb_process_status, &rb_process_status_type, data);
715 return data->status;
716}
717
718/*
719 * call-seq:
720 * to_i -> integer
721 *
722 * Returns the system-dependent integer status of +self+:
723 *
724 * `cat /nop`
725 * $?.to_i # => 256
726 */
727
728static VALUE
729pst_to_i(VALUE self)
730{
731 int status = pst_status(self);
732 return RB_INT2NUM(status);
733}
734
735#define PST2INT(st) pst_status(st)
736
737/*
738 * call-seq:
739 * pid -> integer
740 *
741 * Returns the process ID of the process:
742 *
743 * system("false")
744 * $?.pid # => 1247002
745 *
746 */
747
748static VALUE
749pst_pid_m(VALUE self)
750{
751 rb_pid_t pid = pst_pid(self);
752 return PIDT2NUM(pid);
753}
754
755static VALUE pst_message_status(VALUE str, int status);
756
757static void
758pst_message(VALUE str, rb_pid_t pid, int status)
759{
760 rb_str_catf(str, "pid %ld", (long)pid);
761 pst_message_status(str, status);
762}
763
764static VALUE
765pst_message_status(VALUE str, int status)
766{
767 if (WIFSTOPPED(status)) {
768 int stopsig = WSTOPSIG(status);
769 const char *signame = ruby_signal_name(stopsig);
770 if (signame) {
771 rb_str_catf(str, " stopped SIG%s (signal %d)", signame, stopsig);
772 }
773 else {
774 rb_str_catf(str, " stopped signal %d", stopsig);
775 }
776 }
777 if (WIFSIGNALED(status)) {
778 int termsig = WTERMSIG(status);
779 const char *signame = ruby_signal_name(termsig);
780 if (signame) {
781 rb_str_catf(str, " SIG%s (signal %d)", signame, termsig);
782 }
783 else {
784 rb_str_catf(str, " signal %d", termsig);
785 }
786 }
787 if (WIFEXITED(status)) {
788 rb_str_catf(str, " exit %d", WEXITSTATUS(status));
789 }
790#ifdef WCOREDUMP
791 if (WCOREDUMP(status)) {
792 rb_str_cat2(str, " (core dumped)");
793 }
794#endif
795 return str;
796}
797
798
799/*
800 * call-seq:
801 * to_s -> string
802 *
803 * Returns a string representation of +self+:
804 *
805 * `cat /nop`
806 * $?.to_s # => "pid 1262141 exit 1"
807 *
808 *
809 */
810
811static VALUE
812pst_to_s(VALUE st)
813{
814 rb_pid_t pid;
815 int status;
816 VALUE str;
817
818 pid = pst_pid(st);
819 status = PST2INT(st);
820
821 str = rb_str_buf_new(0);
822 pst_message(str, pid, status);
823 return str;
824}
825
826
827/*
828 * call-seq:
829 * inspect -> string
830 *
831 * Returns a string representation of +self+:
832 *
833 * system("false")
834 * $?.inspect # => "#<Process::Status: pid 1303494 exit 1>"
835 *
836 */
837
838static VALUE
839pst_inspect(VALUE st)
840{
841 rb_pid_t pid;
842 int status;
843 VALUE str;
844
845 pid = pst_pid(st);
846 if (!pid) {
847 return rb_sprintf("#<%s: uninitialized>", rb_class2name(CLASS_OF(st)));
848 }
849 status = PST2INT(st);
850
851 str = rb_sprintf("#<%s: ", rb_class2name(CLASS_OF(st)));
852 pst_message(str, pid, status);
853 rb_str_cat2(str, ">");
854 return str;
855}
856
857
858/*
859 * call-seq:
860 * stat == other -> true or false
861 *
862 * Returns whether the value of #to_i == +other+:
863 *
864 * `cat /nop`
865 * stat = $? # => #<Process::Status: pid 1170366 exit 1>
866 * sprintf('%x', stat.to_i) # => "100"
867 * stat == 0x100 # => true
868 *
869 */
870
871static VALUE
872pst_equal(VALUE st1, VALUE st2)
873{
874 if (st1 == st2) return Qtrue;
875 return rb_equal(pst_to_i(st1), st2);
876}
877
878
879/*
880 * call-seq:
881 * stopped? -> true or false
882 *
883 * Returns +true+ if this process is stopped,
884 * and if the corresponding #wait call had the Process::WUNTRACED flag set,
885 * +false+ otherwise.
886 */
887
888static VALUE
889pst_wifstopped(VALUE st)
890{
891 int status = PST2INT(st);
892
893 return RBOOL(WIFSTOPPED(status));
894}
895
896
897/*
898 * call-seq:
899 * stopsig -> integer or nil
900 *
901 * Returns the number of the signal that caused the process to stop,
902 * or +nil+ if the process is not stopped.
903 */
904
905static VALUE
906pst_wstopsig(VALUE st)
907{
908 int status = PST2INT(st);
909
910 if (WIFSTOPPED(status))
911 return INT2NUM(WSTOPSIG(status));
912 return Qnil;
913}
914
915
916/*
917 * call-seq:
918 * signaled? -> true or false
919 *
920 * Returns +true+ if the process terminated because of an uncaught signal,
921 * +false+ otherwise.
922 */
923
924static VALUE
925pst_wifsignaled(VALUE st)
926{
927 int status = PST2INT(st);
928
929 return RBOOL(WIFSIGNALED(status));
930}
931
932
933/*
934 * call-seq:
935 * termsig -> integer or nil
936 *
937 * Returns the number of the signal that caused the process to terminate
938 * or +nil+ if the process was not terminated by an uncaught signal.
939 */
940
941static VALUE
942pst_wtermsig(VALUE st)
943{
944 int status = PST2INT(st);
945
946 if (WIFSIGNALED(status))
947 return INT2NUM(WTERMSIG(status));
948 return Qnil;
949}
950
951
952/*
953 * call-seq:
954 * exited? -> true or false
955 *
956 * Returns +true+ if the process exited normally
957 * (for example using an <code>exit()</code> call or finishing the
958 * program), +false+ if not.
959 */
960
961static VALUE
962pst_wifexited(VALUE st)
963{
964 int status = PST2INT(st);
965
966 return RBOOL(WIFEXITED(status));
967}
968
969
970/*
971 * call-seq:
972 * exitstatus -> integer or nil
973 *
974 * Returns the least significant eight bits of the return code
975 * of the process if it has exited;
976 * +nil+ otherwise:
977 *
978 * `exit 99`
979 * $?.exitstatus # => 99
980 *
981 */
982
983static VALUE
984pst_wexitstatus(VALUE st)
985{
986 int status = PST2INT(st);
987
988 if (WIFEXITED(status))
989 return INT2NUM(WEXITSTATUS(status));
990 return Qnil;
991}
992
993
994/*
995 * call-seq:
996 * success? -> true, false, or nil
997 *
998 * Returns:
999 *
1000 * - +true+ if the process has completed successfully and exited.
1001 * - +false+ if the process has completed unsuccessfully and exited.
1002 * - +nil+ if the process has not exited.
1003 *
1004 */
1005
1006static VALUE
1007pst_success_p(VALUE st)
1008{
1009 int status = PST2INT(st);
1010
1011 if (!WIFEXITED(status))
1012 return Qnil;
1013 return RBOOL(WEXITSTATUS(status) == EXIT_SUCCESS);
1014}
1015
1016
1017/*
1018 * call-seq:
1019 * coredump? -> true or false
1020 *
1021 * Returns +true+ if the process generated a coredump
1022 * when it terminated, +false+ if not.
1023 *
1024 * Not available on all platforms.
1025 */
1026
1027static VALUE
1028pst_wcoredump(VALUE st)
1029{
1030#ifdef WCOREDUMP
1031 int status = PST2INT(st);
1032
1033 return RBOOL(WCOREDUMP(status));
1034#else
1035 return Qfalse;
1036#endif
1037}
1038
1039static rb_pid_t
1040do_waitpid(rb_pid_t pid, int *st, int flags)
1041{
1042#if defined HAVE_WAITPID
1043 return waitpid(pid, st, flags);
1044#elif defined HAVE_WAIT4
1045 return wait4(pid, st, flags, NULL);
1046#else
1047# error waitpid or wait4 is required.
1048#endif
1049}
1050
1052 struct ccan_list_node wnode;
1053 rb_execution_context_t *ec;
1054 rb_nativethread_cond_t *cond;
1055 rb_pid_t ret;
1056 rb_pid_t pid;
1057 int status;
1058 int options;
1059 int errnum;
1060};
1061
1062static void
1063waitpid_state_init(struct waitpid_state *w, rb_pid_t pid, int options)
1064{
1065 w->ret = 0;
1066 w->pid = pid;
1067 w->options = options;
1068 w->errnum = 0;
1069 w->status = 0;
1070}
1071
1072static void *
1073waitpid_blocking_no_SIGCHLD(void *x)
1074{
1075 struct waitpid_state *w = x;
1076
1077 w->ret = do_waitpid(w->pid, &w->status, w->options);
1078
1079 return 0;
1080}
1081
1082static void
1083waitpid_no_SIGCHLD(struct waitpid_state *w)
1084{
1085 if (w->options & WNOHANG) {
1086 w->ret = do_waitpid(w->pid, &w->status, w->options);
1087 }
1088 else {
1089 do {
1090 rb_thread_call_without_gvl(waitpid_blocking_no_SIGCHLD, w, RUBY_UBF_PROCESS, 0);
1091 } while (w->ret < 0 && errno == EINTR && (RUBY_VM_CHECK_INTS(w->ec),1));
1092 }
1093 if (w->ret == -1)
1094 w->errnum = errno;
1095}
1096
1097VALUE
1098rb_process_status_wait(rb_pid_t pid, int flags)
1099{
1100 // We only enter the scheduler if we are "blocking":
1101 if (!(flags & WNOHANG)) {
1102 VALUE scheduler = rb_fiber_scheduler_current();
1103 if (scheduler != Qnil) {
1104 VALUE result = rb_fiber_scheduler_process_wait(scheduler, pid, flags);
1105 if (!UNDEF_P(result)) return result;
1106 }
1107 }
1108
1110
1111 waitpid_state_init(&waitpid_state, pid, flags);
1112 waitpid_state.ec = GET_EC();
1113
1114 waitpid_no_SIGCHLD(&waitpid_state);
1115
1116 if (waitpid_state.ret == 0) return Qnil;
1117
1118 return rb_process_status_new(waitpid_state.ret, waitpid_state.status, waitpid_state.errnum);
1119}
1120
1121/*
1122 * call-seq:
1123 * Process::Status.wait(pid = -1, flags = 0) -> Process::Status
1124 *
1125 * Like Process.wait, but returns a Process::Status object
1126 * (instead of an integer pid or nil);
1127 * see Process.wait for the values of +pid+ and +flags+.
1128 *
1129 * If there are child processes,
1130 * waits for a child process to exit and returns a Process::Status object
1131 * containing information on that process;
1132 * sets thread-local variable <tt>$?</tt>:
1133 *
1134 * Process.spawn('cat /nop') # => 1155880
1135 * Process::Status.wait # => #<Process::Status: pid 1155880 exit 1>
1136 * $? # => #<Process::Status: pid 1155508 exit 1>
1137 *
1138 * If there is no child process,
1139 * returns an "empty" Process::Status object
1140 * that does not represent an actual process;
1141 * does not set thread-local variable <tt>$?</tt>:
1142 *
1143 * Process::Status.wait # => #<Process::Status: pid -1 exit 0>
1144 * $? # => #<Process::Status: pid 1155508 exit 1> # Unchanged.
1145 *
1146 * May invoke the scheduler hook Fiber::Scheduler#process_wait.
1147 *
1148 * Not available on all platforms.
1149 */
1150
1151static VALUE
1152rb_process_status_waitv(int argc, VALUE *argv, VALUE _)
1153{
1154 rb_check_arity(argc, 0, 2);
1155
1156 rb_pid_t pid = -1;
1157 int flags = 0;
1158
1159 if (argc >= 1) {
1160 pid = NUM2PIDT(argv[0]);
1161 }
1162
1163 if (argc >= 2) {
1164 flags = RB_NUM2INT(argv[1]);
1165 }
1166
1167 return rb_process_status_wait(pid, flags);
1168}
1169
1170rb_pid_t
1171rb_waitpid(rb_pid_t pid, int *st, int flags)
1172{
1173 VALUE status = rb_process_status_wait(pid, flags);
1174 if (NIL_P(status)) return 0;
1175
1176 struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);
1177 pid = data->pid;
1178
1179 if (st) *st = data->status;
1180
1181 if (pid == -1) {
1182 errno = data->error;
1183 }
1184 else {
1185 GET_THREAD()->last_status = status;
1186 }
1187
1188 return pid;
1189}
1190
1191static VALUE
1192proc_wait(int argc, VALUE *argv)
1193{
1194 rb_pid_t pid;
1195 int flags, status;
1196
1197 flags = 0;
1198 if (rb_check_arity(argc, 0, 2) == 0) {
1199 pid = -1;
1200 }
1201 else {
1202 VALUE vflags;
1203 pid = NUM2PIDT(argv[0]);
1204 if (argc == 2 && !NIL_P(vflags = argv[1])) {
1205 flags = NUM2UINT(vflags);
1206 }
1207 }
1208
1209 if ((pid = rb_waitpid(pid, &status, flags)) < 0)
1210 rb_sys_fail(0);
1211
1212 if (pid == 0) {
1213 rb_last_status_clear();
1214 return Qnil;
1215 }
1216
1217 return PIDT2NUM(pid);
1218}
1219
1220/* [MG]:FIXME: I wasn't sure how this should be done, since ::wait()
1221 has historically been documented as if it didn't take any arguments
1222 despite the fact that it's just an alias for ::waitpid(). The way I
1223 have it below is more truthful, but a little confusing.
1224
1225 I also took the liberty of putting in the pid values, as they're
1226 pretty useful, and it looked as if the original 'ri' output was
1227 supposed to contain them after "[...]depending on the value of
1228 aPid:".
1229
1230 The 'ansi' and 'bs' formats of the ri output don't display the
1231 definition list for some reason, but the plain text one does.
1232 */
1233
1234/*
1235 * call-seq:
1236 * Process.wait(pid = -1, flags = 0) -> integer
1237 *
1238 * Waits for a suitable child process to exit, returns its process ID,
1239 * and sets <tt>$?</tt> to a Process::Status object
1240 * containing information on that process.
1241 * Which child it waits for depends on the value of the given +pid+:
1242 *
1243 * - Positive integer: Waits for the child process whose process ID is +pid+:
1244 *
1245 * pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 230866
1246 * pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 230891
1247 * Process.wait(pid0) # => 230866
1248 * $? # => #<Process::Status: pid 230866 exit 13>
1249 * Process.wait(pid1) # => 230891
1250 * $? # => #<Process::Status: pid 230891 exit 14>
1251 * Process.wait(pid0) # Raises Errno::ECHILD
1252 *
1253 * - <tt>0</tt>: Waits for any child process whose group ID
1254 * is the same as that of the current process:
1255 *
1256 * parent_pgpid = Process.getpgid(Process.pid)
1257 * puts "Parent process group ID is #{parent_pgpid}."
1258 * child0_pid = fork do
1259 * puts "Child 0 pid is #{Process.pid}"
1260 * child0_pgid = Process.getpgid(Process.pid)
1261 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1262 * end
1263 * child1_pid = fork do
1264 * puts "Child 1 pid is #{Process.pid}"
1265 * Process.setpgid(0, Process.pid)
1266 * child1_pgid = Process.getpgid(Process.pid)
1267 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1268 * end
1269 * retrieved_pid = Process.wait(0)
1270 * puts "Process.wait(0) returned pid #{retrieved_pid}, which is child 0 pid."
1271 * begin
1272 * Process.wait(0)
1273 * rescue Errno::ECHILD => x
1274 * puts "Raised #{x.class}, because child 1 process group ID differs from parent process group ID."
1275 * end
1276 *
1277 * Output:
1278 *
1279 * Parent process group ID is 225764.
1280 * Child 0 pid is 225788
1281 * Child 0 process group ID is 225764 (same as parent's).
1282 * Child 1 pid is 225789
1283 * Child 1 process group ID is 225789 (different from parent's).
1284 * Process.wait(0) returned pid 225788, which is child 0 pid.
1285 * Raised Errno::ECHILD, because child 1 process group ID differs from parent process group ID.
1286 *
1287 * - <tt>-1</tt> (default): Waits for any child process:
1288 *
1289 * parent_pgpid = Process.getpgid(Process.pid)
1290 * puts "Parent process group ID is #{parent_pgpid}."
1291 * child0_pid = fork do
1292 * puts "Child 0 pid is #{Process.pid}"
1293 * child0_pgid = Process.getpgid(Process.pid)
1294 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1295 * end
1296 * child1_pid = fork do
1297 * puts "Child 1 pid is #{Process.pid}"
1298 * Process.setpgid(0, Process.pid)
1299 * child1_pgid = Process.getpgid(Process.pid)
1300 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1301 * sleep 3 # To force child 1 to exit later than child 0 exit.
1302 * end
1303 * child_pids = [child0_pid, child1_pid]
1304 * retrieved_pid = Process.wait(-1)
1305 * puts child_pids.include?(retrieved_pid)
1306 * retrieved_pid = Process.wait(-1)
1307 * puts child_pids.include?(retrieved_pid)
1308 *
1309 * Output:
1310 *
1311 * Parent process group ID is 228736.
1312 * Child 0 pid is 228758
1313 * Child 0 process group ID is 228736 (same as parent's).
1314 * Child 1 pid is 228759
1315 * Child 1 process group ID is 228759 (different from parent's).
1316 * true
1317 * true
1318 *
1319 * - Less than <tt>-1</tt>: Waits for any child whose process group ID is <tt>-pid</tt>:
1320 *
1321 * parent_pgpid = Process.getpgid(Process.pid)
1322 * puts "Parent process group ID is #{parent_pgpid}."
1323 * child0_pid = fork do
1324 * puts "Child 0 pid is #{Process.pid}"
1325 * child0_pgid = Process.getpgid(Process.pid)
1326 * puts "Child 0 process group ID is #{child0_pgid} (same as parent's)."
1327 * end
1328 * child1_pid = fork do
1329 * puts "Child 1 pid is #{Process.pid}"
1330 * Process.setpgid(0, Process.pid)
1331 * child1_pgid = Process.getpgid(Process.pid)
1332 * puts "Child 1 process group ID is #{child1_pgid} (different from parent's)."
1333 * end
1334 * sleep 1
1335 * retrieved_pid = Process.wait(-child1_pid)
1336 * puts "Process.wait(-child1_pid) returned pid #{retrieved_pid}, which is child 1 pid."
1337 * begin
1338 * Process.wait(-child1_pid)
1339 * rescue Errno::ECHILD => x
1340 * puts "Raised #{x.class}, because there's no longer a child with process group id #{child1_pid}."
1341 * end
1342 *
1343 * Output:
1344 *
1345 * Parent process group ID is 230083.
1346 * Child 0 pid is 230108
1347 * Child 0 process group ID is 230083 (same as parent's).
1348 * Child 1 pid is 230109
1349 * Child 1 process group ID is 230109 (different from parent's).
1350 * Process.wait(-child1_pid) returned pid 230109, which is child 1 pid.
1351 * Raised Errno::ECHILD, because there's no longer a child with process group id 230109.
1352 *
1353 * Argument +flags+ should be given as one of the following constants,
1354 * or as the logical OR of both:
1355 *
1356 * - Process::WNOHANG: Does not block if no child process is available.
1357 * - Process::WUNTRACED: May return a stopped child process, even if not yet reported.
1358 *
1359 * Not all flags are available on all platforms.
1360 *
1361 * Raises Errno::ECHILD if there is no suitable child process.
1362 *
1363 * Not available on all platforms.
1364 *
1365 * Process.waitpid is an alias for Process.wait.
1366 */
1367static VALUE
1368proc_m_wait(int c, VALUE *v, VALUE _)
1369{
1370 return proc_wait(c, v);
1371}
1372
1373/*
1374 * call-seq:
1375 * Process.wait2(pid = -1, flags = 0) -> [pid, status]
1376 *
1377 * Like Process.waitpid, but returns an array
1378 * containing the child process +pid+ and Process::Status +status+:
1379 *
1380 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 309581
1381 * Process.wait2(pid)
1382 * # => [309581, #<Process::Status: pid 309581 exit 13>]
1383 *
1384 * Process.waitpid2 is an alias for Process.wait2.
1385 */
1386
1387static VALUE
1388proc_wait2(int argc, VALUE *argv, VALUE _)
1389{
1390 VALUE pid = proc_wait(argc, argv);
1391 if (NIL_P(pid)) return Qnil;
1392 return rb_assoc_new(pid, rb_last_status_get());
1393}
1394
1395
1396/*
1397 * call-seq:
1398 * Process.waitall -> array
1399 *
1400 * Waits for all children, returns an array of 2-element arrays;
1401 * each subarray contains the integer pid and Process::Status status
1402 * for one of the reaped child processes:
1403 *
1404 * pid0 = Process.spawn('ruby', '-e', 'exit 13') # => 325470
1405 * pid1 = Process.spawn('ruby', '-e', 'exit 14') # => 325495
1406 * Process.waitall
1407 * # => [[325470, #<Process::Status: pid 325470 exit 13>], [325495, #<Process::Status: pid 325495 exit 14>]]
1408 *
1409 */
1410
1411static VALUE
1412proc_waitall(VALUE _)
1413{
1414 VALUE result;
1415 rb_pid_t pid;
1416 int status;
1417
1418 result = rb_ary_new();
1419 rb_last_status_clear();
1420
1421 for (pid = -1;;) {
1422 pid = rb_waitpid(-1, &status, 0);
1423 if (pid == -1) {
1424 int e = errno;
1425 if (e == ECHILD)
1426 break;
1427 rb_syserr_fail(e, 0);
1428 }
1430 }
1431 return result;
1432}
1433
1434static VALUE rb_cWaiter;
1435
1436static VALUE
1437detach_process_pid(VALUE thread)
1438{
1439 return rb_thread_local_aref(thread, id_pid);
1440}
1441
1442static VALUE
1443detach_process_watcher(void *arg)
1444{
1445 rb_pid_t cpid, pid = (rb_pid_t)(VALUE)arg;
1446 int status;
1447
1448 while ((cpid = rb_waitpid(pid, &status, 0)) == 0) {
1449 /* wait while alive */
1450 }
1451 return rb_last_status_get();
1452}
1453
1454VALUE
1456{
1457 VALUE watcher = rb_thread_create(detach_process_watcher, (void*)(VALUE)pid);
1458 rb_thread_local_aset(watcher, id_pid, PIDT2NUM(pid));
1459 RBASIC_SET_CLASS(watcher, rb_cWaiter);
1460 return watcher;
1461}
1462
1463
1464/*
1465 * call-seq:
1466 * Process.detach(pid) -> thread
1467 *
1468 * Avoids the potential for a child process to become a
1469 * {zombie process}[https://en.wikipedia.org/wiki/Zombie_process].
1470 * Process.detach prevents this by setting up a separate Ruby thread
1471 * whose sole job is to reap the status of the process _pid_ when it terminates.
1472 *
1473 * This method is needed only when the parent process will never wait
1474 * for the child process.
1475 *
1476 * This example does not reap the second child process;
1477 * that process appears as a zombie in the process status (+ps+) output:
1478 *
1479 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 312691
1480 * sleep(1)
1481 * # Find zombies.
1482 * system("ps -ho pid,state -p #{pid}")
1483 *
1484 * Output:
1485 *
1486 * 312716 Z
1487 *
1488 * This example also does not reap the second child process,
1489 * but it does detach the process so that it does not become a zombie:
1490 *
1491 * pid = Process.spawn('ruby', '-e', 'exit 13') # => 313213
1492 * thread = Process.detach(pid)
1493 * sleep(1)
1494 * # => #<Process::Waiter:0x00007f038f48b838 run>
1495 * system("ps -ho pid,state -p #{pid}") # Finds no zombies.
1496 *
1497 * The waiting thread can return the pid of the detached child process:
1498 *
1499 * thread.join.pid # => 313262
1500 *
1501 */
1502
1503static VALUE
1504proc_detach(VALUE obj, VALUE pid)
1505{
1506 return rb_detach_process(NUM2PIDT(pid));
1507}
1508
1509/* This function should be async-signal-safe. Actually it is. */
1510static void
1511before_exec_async_signal_safe(void)
1512{
1513}
1514
1515static void
1516before_exec_non_async_signal_safe(void)
1517{
1518 /*
1519 * On Mac OS X 10.5.x (Leopard) or earlier, exec() may return ENOTSUP
1520 * if the process have multiple threads. Therefore we have to kill
1521 * internal threads temporary. [ruby-core:10583]
1522 * This is also true on Haiku. It returns Errno::EPERM against exec()
1523 * in multiple threads.
1524 *
1525 * Nowadays, we always stop the timer thread completely to allow redirects.
1526 */
1527 rb_thread_stop_timer_thread();
1528}
1529
1530#define WRITE_CONST(fd, str) (void)(write((fd),(str),sizeof(str)-1)<0)
1531#ifdef _WIN32
1532int rb_w32_set_nonblock2(int fd, int nonblock);
1533#endif
1534
1535static int
1536set_blocking(int fd)
1537{
1538#ifdef _WIN32
1539 return rb_w32_set_nonblock2(fd, 0);
1540#elif defined(F_GETFL) && defined(F_SETFL)
1541 int fl = fcntl(fd, F_GETFL); /* async-signal-safe */
1542
1543 /* EBADF ought to be possible */
1544 if (fl == -1) return fl;
1545 if (fl & O_NONBLOCK) {
1546 fl &= ~O_NONBLOCK;
1547 return fcntl(fd, F_SETFL, fl);
1548 }
1549 return 0;
1550#endif
1551}
1552
1553static void
1554stdfd_clear_nonblock(void)
1555{
1556 /* many programs cannot deal with non-blocking stdin/stdout/stderr */
1557 int fd;
1558 for (fd = 0; fd < 3; fd++) {
1559 (void)set_blocking(fd); /* can't do much about errors anyhow */
1560 }
1561}
1562
1563static void
1564before_exec(void)
1565{
1566 before_exec_non_async_signal_safe();
1567 before_exec_async_signal_safe();
1568}
1569
1570static void
1571after_exec(void)
1572{
1573 rb_thread_reset_timer_thread();
1574 rb_thread_start_timer_thread();
1575}
1576
1577#if defined HAVE_WORKING_FORK || defined HAVE_DAEMON
1578static void
1579before_fork_ruby(void)
1580{
1581 before_exec();
1582 rb_gc_before_fork();
1583}
1584
1585static void
1586after_fork_ruby(rb_pid_t pid)
1587{
1588 rb_gc_after_fork(pid);
1589
1590 if (pid == 0) {
1591 // child
1592 clear_pid_cache();
1594 }
1595 else {
1596 // parent
1597 after_exec();
1598 }
1599}
1600
1601static void
1602release_fork_lock_after_fork(rb_pid_t pid)
1603{
1604 if (pid == 0) {
1605 rb_thread_reset_fork_lock();
1606 }
1607 else {
1608 rb_thread_release_fork_lock();
1609 }
1610}
1611#endif
1612
1613#if defined(HAVE_WORKING_FORK)
1614
1615COMPILER_WARNING_PUSH
1616#if __has_warning("-Wdeprecated-declarations") || RBIMPL_COMPILER_IS(GCC)
1617COMPILER_WARNING_IGNORED(-Wdeprecated-declarations)
1618#endif
1619static inline rb_pid_t
1620rb_fork(void)
1621{
1622 return fork();
1623}
1624COMPILER_WARNING_POP
1625
1626/* try_with_sh and exec_with_sh should be async-signal-safe. Actually it is.*/
1627#define try_with_sh(err, prog, argv, envp) ((err == ENOEXEC) ? exec_with_sh((prog), (argv), (envp)) : (void)0)
1628static void
1629exec_with_sh(const char *prog, char **argv, char **envp)
1630{
1631 *argv = (char *)prog;
1632 *--argv = (char *)"sh";
1633 if (envp)
1634 execve("/bin/sh", argv, envp); /* async-signal-safe */
1635 else
1636 execv("/bin/sh", argv); /* async-signal-safe (since SUSv4) */
1637}
1638
1639#else
1640#define try_with_sh(err, prog, argv, envp) (void)0
1641#endif
1642
1643/* This function should be async-signal-safe. Actually it is. */
1644static int
1645proc_exec_cmd(const char *prog, VALUE argv_str, VALUE envp_str)
1646{
1647 char **argv;
1648#ifndef _WIN32
1649 char **envp;
1650 int err;
1651#endif
1652
1653 argv = ARGVSTR2ARGV(argv_str);
1654
1655 if (!prog) {
1656 return ENOENT;
1657 }
1658
1659#ifdef _WIN32
1660 rb_w32_uaspawn(P_OVERLAY, prog, argv);
1661 return errno;
1662#else
1663 envp = envp_str ? RB_IMEMO_TMPBUF_PTR(envp_str) : NULL;
1664 if (envp_str)
1665 execve(prog, argv, envp); /* async-signal-safe */
1666 else
1667 execv(prog, argv); /* async-signal-safe (since SUSv4) */
1668 err = errno;
1669 try_with_sh(err, prog, argv, envp); /* try_with_sh() is async-signal-safe. */
1670 return err;
1671#endif
1672}
1673
1674/* This function should be async-signal-safe. Actually it is. */
1675static int
1676proc_exec_sh(const char *str, VALUE envp_str)
1677{
1678 const char *s;
1679
1680 s = str;
1681 while (*s == ' ' || *s == '\t' || *s == '\n')
1682 s++;
1683
1684 if (!*s) {
1685 return ENOENT;
1686 }
1687
1688#ifdef _WIN32
1689 rb_w32_uspawn(P_OVERLAY, (char *)str, 0);
1690#elif defined(__CYGWIN32__)
1691 {
1692 char fbuf[MAXPATHLEN];
1693 char *shell = dln_find_exe_r("sh", 0, fbuf, sizeof(fbuf));
1694 int status = -1;
1695 if (shell)
1696 execl(shell, "sh", "-c", str, (char *) NULL);
1697 else
1698 status = system(str);
1699 if (status != -1)
1700 exit(status);
1701 }
1702#else
1703 if (envp_str)
1704 execle("/bin/sh", "sh", "-c", str, (char *)NULL, RB_IMEMO_TMPBUF_PTR(envp_str)); /* async-signal-safe */
1705 else
1706 execl("/bin/sh", "sh", "-c", str, (char *)NULL); /* async-signal-safe (since SUSv4) */
1707#endif /* _WIN32 */
1708 return errno;
1709}
1710
1711int
1712rb_proc_exec(const char *str)
1713{
1714 int ret;
1715 before_exec();
1716 ret = proc_exec_sh(str, Qfalse);
1717 after_exec();
1718 errno = ret;
1719 return -1;
1720}
1721
1722static void
1723mark_exec_arg(void *ptr)
1724{
1725 struct rb_execarg *eargp = ptr;
1726 if (eargp->use_shell)
1727 rb_gc_mark(eargp->invoke.sh.shell_script);
1728 else {
1729 rb_gc_mark(eargp->invoke.cmd.command_name);
1730 rb_gc_mark(eargp->invoke.cmd.command_abspath);
1731 rb_gc_mark(eargp->invoke.cmd.argv_str);
1732 rb_gc_mark(eargp->invoke.cmd.argv_buf);
1733 }
1734 rb_gc_mark(eargp->redirect_fds);
1735 rb_gc_mark(eargp->envp_str);
1736 rb_gc_mark(eargp->envp_buf);
1737 rb_gc_mark(eargp->dup2_tmpbuf);
1738 rb_gc_mark(eargp->rlimit_limits);
1739 rb_gc_mark(eargp->fd_dup2);
1740 rb_gc_mark(eargp->fd_close);
1741 rb_gc_mark(eargp->fd_open);
1742 rb_gc_mark(eargp->fd_dup2_child);
1743 rb_gc_mark(eargp->env_modification);
1744 rb_gc_mark(eargp->path_env);
1745 rb_gc_mark(eargp->chdir_dir);
1746}
1747
1748static size_t
1749memsize_exec_arg(const void *ptr)
1750{
1751 return sizeof(struct rb_execarg);
1752}
1753
1754static const rb_data_type_t exec_arg_data_type = {
1755 "exec_arg",
1756 {mark_exec_arg, RUBY_TYPED_DEFAULT_FREE, memsize_exec_arg},
1757 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
1758};
1759
1760#ifdef _WIN32
1761# define DEFAULT_PROCESS_ENCODING rb_utf8_encoding()
1762#endif
1763#ifdef DEFAULT_PROCESS_ENCODING
1764# define EXPORT_STR(str) rb_str_export_to_enc((str), DEFAULT_PROCESS_ENCODING)
1765# define EXPORT_DUP(str) export_dup(str)
1766static VALUE
1767export_dup(VALUE str)
1768{
1769 VALUE newstr = EXPORT_STR(str);
1770 if (newstr == str) newstr = rb_str_dup(str);
1771 return newstr;
1772}
1773#else
1774# define EXPORT_STR(str) (str)
1775# define EXPORT_DUP(str) rb_str_dup(str)
1776#endif
1777
1778#if !defined(HAVE_WORKING_FORK) && defined(HAVE_SPAWNV)
1779# define USE_SPAWNV 1
1780#else
1781# define USE_SPAWNV 0
1782#endif
1783#ifndef P_NOWAIT
1784# define P_NOWAIT _P_NOWAIT
1785#endif
1786
1787#if USE_SPAWNV
1788#if defined(_WIN32)
1789#define proc_spawn_cmd_internal(argv, prog) rb_w32_uaspawn(P_NOWAIT, (prog), (argv))
1790#else
1791static rb_pid_t
1792proc_spawn_cmd_internal(char **argv, char *prog)
1793{
1794 char fbuf[MAXPATHLEN];
1795 rb_pid_t status;
1796
1797 if (!prog)
1798 prog = argv[0];
1799 prog = dln_find_exe_r(prog, 0, fbuf, sizeof(fbuf));
1800 if (!prog)
1801 return -1;
1802
1803 before_exec();
1804 status = spawnv(P_NOWAIT, prog, (const char **)argv);
1805 if (status == -1 && errno == ENOEXEC) {
1806 *argv = (char *)prog;
1807 *--argv = (char *)"sh";
1808 status = spawnv(P_NOWAIT, "/bin/sh", (const char **)argv);
1809 after_exec();
1810 if (status == -1) errno = ENOEXEC;
1811 }
1812 return status;
1813}
1814#endif
1815
1816static rb_pid_t
1817proc_spawn_cmd(char **argv, VALUE prog, struct rb_execarg *eargp)
1818{
1819 rb_pid_t pid = -1;
1820
1821 if (argv[0]) {
1822#if defined(_WIN32)
1823 DWORD flags = 0;
1824 if (eargp->new_pgroup_given && eargp->new_pgroup_flag) {
1825 flags = CREATE_NEW_PROCESS_GROUP;
1826 }
1827 pid = rb_w32_uaspawn_flags(P_NOWAIT, prog ? RSTRING_PTR(prog) : 0, argv, flags);
1828#else
1829 pid = proc_spawn_cmd_internal(argv, prog ? RSTRING_PTR(prog) : 0);
1830#endif
1831 }
1832 return pid;
1833}
1834
1835#if defined(_WIN32)
1836#define proc_spawn_sh(str) rb_w32_uspawn(P_NOWAIT, (str), 0)
1837#else
1838static rb_pid_t
1839proc_spawn_sh(char *str)
1840{
1841 char fbuf[MAXPATHLEN];
1842 rb_pid_t status;
1843
1844 char *shell = dln_find_exe_r("sh", 0, fbuf, sizeof(fbuf));
1845 before_exec();
1846 status = spawnl(P_NOWAIT, (shell ? shell : "/bin/sh"), "sh", "-c", str, (char*)NULL);
1847 after_exec();
1848 return status;
1849}
1850#endif
1851#endif
1852
1853static VALUE
1854hide_obj(VALUE obj)
1855{
1856 RBASIC_CLEAR_CLASS(obj);
1857 return obj;
1858}
1859
1860static VALUE
1861check_exec_redirect_fd(VALUE v, int iskey)
1862{
1863 VALUE tmp;
1864 int fd;
1865 if (FIXNUM_P(v)) {
1866 fd = FIX2INT(v);
1867 }
1868 else if (SYMBOL_P(v)) {
1869 ID id = rb_check_id(&v);
1870 if (id == id_in)
1871 fd = 0;
1872 else if (id == id_out)
1873 fd = 1;
1874 else if (id == id_err)
1875 fd = 2;
1876 else
1877 goto wrong;
1878 }
1879 else if (!NIL_P(tmp = rb_io_check_io(v))) {
1880 rb_io_t *fptr;
1881 GetOpenFile(tmp, fptr);
1882 if (fptr->tied_io_for_writing)
1883 rb_raise(rb_eArgError, "duplex IO redirection");
1884 fd = fptr->fd;
1885 }
1886 else {
1887 goto wrong;
1888 }
1889 if (fd < 0) {
1890 rb_raise(rb_eArgError, "negative file descriptor");
1891 }
1892#ifdef _WIN32
1893 else if (fd >= 3 && iskey) {
1894 rb_raise(rb_eArgError, "wrong file descriptor (%d)", fd);
1895 }
1896#endif
1897 return INT2FIX(fd);
1898
1899 wrong:
1900 rb_raise(rb_eArgError, "wrong exec redirect");
1902}
1903
1904static VALUE
1905check_exec_redirect1(VALUE ary, VALUE key, VALUE param)
1906{
1907 if (ary == Qfalse) {
1908 ary = hide_obj(rb_ary_new());
1909 }
1910 if (!RB_TYPE_P(key, T_ARRAY)) {
1911 VALUE fd = check_exec_redirect_fd(key, !NIL_P(param));
1912 rb_ary_push(ary, hide_obj(rb_assoc_new(fd, param)));
1913 }
1914 else {
1915 int i;
1916 for (i = 0 ; i < RARRAY_LEN(key); i++) {
1917 VALUE v = RARRAY_AREF(key, i);
1918 VALUE fd = check_exec_redirect_fd(v, !NIL_P(param));
1919 rb_ary_push(ary, hide_obj(rb_assoc_new(fd, param)));
1920 }
1921 }
1922 return ary;
1923}
1924
1925static void
1926check_exec_redirect(VALUE key, VALUE val, struct rb_execarg *eargp)
1927{
1928 VALUE param;
1929 VALUE path, flags, perm;
1930 VALUE tmp;
1931 ID id;
1932
1933 switch (TYPE(val)) {
1934 case T_SYMBOL:
1935 id = rb_check_id(&val);
1936 if (id == id_close) {
1937 param = Qnil;
1938 eargp->fd_close = check_exec_redirect1(eargp->fd_close, key, param);
1939 }
1940 else if (id == id_in) {
1941 param = INT2FIX(0);
1942 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1943 }
1944 else if (id == id_out) {
1945 param = INT2FIX(1);
1946 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1947 }
1948 else if (id == id_err) {
1949 param = INT2FIX(2);
1950 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1951 }
1952 else {
1953 rb_raise(rb_eArgError, "wrong exec redirect symbol: %"PRIsVALUE,
1954 val);
1955 }
1956 break;
1957
1958 case T_FILE:
1959 io:
1960 val = check_exec_redirect_fd(val, 0);
1961 /* fall through */
1962 case T_FIXNUM:
1963 param = val;
1964 eargp->fd_dup2 = check_exec_redirect1(eargp->fd_dup2, key, param);
1965 break;
1966
1967 case T_ARRAY:
1968 path = rb_ary_entry(val, 0);
1969 if (RARRAY_LEN(val) == 2 && SYMBOL_P(path) &&
1970 path == ID2SYM(id_child)) {
1971 param = check_exec_redirect_fd(rb_ary_entry(val, 1), 0);
1972 eargp->fd_dup2_child = check_exec_redirect1(eargp->fd_dup2_child, key, param);
1973 }
1974 else {
1975 FilePathValue(path);
1976 flags = rb_ary_entry(val, 1);
1977 if (NIL_P(flags))
1978 flags = INT2NUM(O_RDONLY);
1979 else if (RB_TYPE_P(flags, T_STRING))
1981 else
1982 flags = rb_to_int(flags);
1983 perm = rb_ary_entry(val, 2);
1984 perm = NIL_P(perm) ? INT2FIX(0644) : rb_to_int(perm);
1985 param = hide_obj(rb_ary_new3(4, hide_obj(EXPORT_DUP(path)),
1986 flags, perm, Qnil));
1987 eargp->fd_open = check_exec_redirect1(eargp->fd_open, key, param);
1988 }
1989 break;
1990
1991 case T_STRING:
1992 path = val;
1993 FilePathValue(path);
1994 if (RB_TYPE_P(key, T_FILE))
1995 key = check_exec_redirect_fd(key, 1);
1996 if (FIXNUM_P(key) && (FIX2INT(key) == 1 || FIX2INT(key) == 2))
1997 flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC);
1998 else if (RB_TYPE_P(key, T_ARRAY)) {
1999 int i;
2000 for (i = 0; i < RARRAY_LEN(key); i++) {
2001 VALUE v = RARRAY_AREF(key, i);
2002 VALUE fd = check_exec_redirect_fd(v, 1);
2003 if (FIX2INT(fd) != 1 && FIX2INT(fd) != 2) break;
2004 }
2005 if (i == RARRAY_LEN(key))
2006 flags = INT2NUM(O_WRONLY|O_CREAT|O_TRUNC);
2007 else
2008 flags = INT2NUM(O_RDONLY);
2009 }
2010 else
2011 flags = INT2NUM(O_RDONLY);
2012 perm = INT2FIX(0644);
2013 param = hide_obj(rb_ary_new3(4, hide_obj(EXPORT_DUP(path)),
2014 flags, perm, Qnil));
2015 eargp->fd_open = check_exec_redirect1(eargp->fd_open, key, param);
2016 break;
2017
2018 default:
2019 tmp = val;
2020 val = rb_io_check_io(tmp);
2021 if (!NIL_P(val)) goto io;
2022 rb_raise(rb_eArgError, "wrong exec redirect action");
2023 }
2024
2025}
2026
2027#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
2028static int rlimit_type_by_sym(VALUE key);
2029
2030static void
2031rb_execarg_addopt_rlimit(struct rb_execarg *eargp, int rtype, VALUE val)
2032{
2033 VALUE ary = eargp->rlimit_limits;
2034 VALUE tmp, softlim, hardlim;
2035 if (eargp->rlimit_limits == Qfalse)
2036 ary = eargp->rlimit_limits = hide_obj(rb_ary_new());
2037 else
2038 ary = eargp->rlimit_limits;
2039 tmp = rb_check_array_type(val);
2040 if (!NIL_P(tmp)) {
2041 if (RARRAY_LEN(tmp) == 1)
2042 softlim = hardlim = rb_to_int(rb_ary_entry(tmp, 0));
2043 else if (RARRAY_LEN(tmp) == 2) {
2044 softlim = rb_to_int(rb_ary_entry(tmp, 0));
2045 hardlim = rb_to_int(rb_ary_entry(tmp, 1));
2046 }
2047 else {
2048 rb_raise(rb_eArgError, "wrong exec rlimit option");
2049 }
2050 }
2051 else {
2052 softlim = hardlim = rb_to_int(val);
2053 }
2054 tmp = hide_obj(rb_ary_new3(3, INT2NUM(rtype), softlim, hardlim));
2055 rb_ary_push(ary, tmp);
2056}
2057#endif
2058
2059#define TO_BOOL(val, name) (NIL_P(val) ? 0 : rb_bool_expected((val), name, TRUE))
2060int
2061rb_execarg_addopt(VALUE execarg_obj, VALUE key, VALUE val)
2062{
2063 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2064
2065 ID id;
2066
2067 switch (TYPE(key)) {
2068 case T_SYMBOL:
2069#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
2070 {
2071 int rtype = rlimit_type_by_sym(key);
2072 if (rtype != -1) {
2073 rb_execarg_addopt_rlimit(eargp, rtype, val);
2074 RB_GC_GUARD(execarg_obj);
2075 return ST_CONTINUE;
2076 }
2077 }
2078#endif
2079 if (!(id = rb_check_id(&key))) return ST_STOP;
2080#ifdef HAVE_SETPGID
2081 if (id == id_pgroup) {
2082 rb_pid_t pgroup;
2083 if (eargp->pgroup_given) {
2084 rb_raise(rb_eArgError, "pgroup option specified twice");
2085 }
2086 if (!RTEST(val))
2087 pgroup = -1; /* asis(-1) means "don't call setpgid()". */
2088 else if (val == Qtrue)
2089 pgroup = 0; /* new process group. */
2090 else {
2091 pgroup = NUM2PIDT(val);
2092 if (pgroup < 0) {
2093 rb_raise(rb_eArgError, "negative process group ID : %ld", (long)pgroup);
2094 }
2095 }
2096 eargp->pgroup_given = 1;
2097 eargp->pgroup_pgid = pgroup;
2098 }
2099 else
2100#endif
2101#ifdef _WIN32
2102 if (id == id_new_pgroup) {
2103 if (eargp->new_pgroup_given) {
2104 rb_raise(rb_eArgError, "new_pgroup option specified twice");
2105 }
2106 eargp->new_pgroup_given = 1;
2107 eargp->new_pgroup_flag = TO_BOOL(val, "new_pgroup");
2108 }
2109 else
2110#endif
2111 if (id == id_unsetenv_others) {
2112 if (eargp->unsetenv_others_given) {
2113 rb_raise(rb_eArgError, "unsetenv_others option specified twice");
2114 }
2115 eargp->unsetenv_others_given = 1;
2116 eargp->unsetenv_others_do = TO_BOOL(val, "unsetenv_others");
2117 }
2118 else if (id == id_chdir) {
2119 if (eargp->chdir_given) {
2120 rb_raise(rb_eArgError, "chdir option specified twice");
2121 }
2122 FilePathValue(val);
2123 val = rb_str_encode_ospath(val);
2124 eargp->chdir_given = 1;
2125 eargp->chdir_dir = hide_obj(EXPORT_DUP(val));
2126 }
2127 else if (id == id_umask) {
2128 mode_t cmask = NUM2MODET(val);
2129 if (eargp->umask_given) {
2130 rb_raise(rb_eArgError, "umask option specified twice");
2131 }
2132 eargp->umask_given = 1;
2133 eargp->umask_mask = cmask;
2134 }
2135 else if (id == id_close_others) {
2136 if (eargp->close_others_given) {
2137 rb_raise(rb_eArgError, "close_others option specified twice");
2138 }
2139 eargp->close_others_given = 1;
2140 eargp->close_others_do = TO_BOOL(val, "close_others");
2141 }
2142 else if (id == id_in) {
2143 key = INT2FIX(0);
2144 goto redirect;
2145 }
2146 else if (id == id_out) {
2147 key = INT2FIX(1);
2148 goto redirect;
2149 }
2150 else if (id == id_err) {
2151 key = INT2FIX(2);
2152 goto redirect;
2153 }
2154 else if (id == id_uid) {
2155#ifdef HAVE_SETUID
2156 if (eargp->uid_given) {
2157 rb_raise(rb_eArgError, "uid option specified twice");
2158 }
2159 check_uid_switch();
2160 {
2161 eargp->uid = OBJ2UID(val);
2162 eargp->uid_given = 1;
2163 }
2164#else
2165 rb_raise(rb_eNotImpError,
2166 "uid option is unimplemented on this machine");
2167#endif
2168 }
2169 else if (id == id_gid) {
2170#ifdef HAVE_SETGID
2171 if (eargp->gid_given) {
2172 rb_raise(rb_eArgError, "gid option specified twice");
2173 }
2174 check_gid_switch();
2175 {
2176 eargp->gid = OBJ2GID(val);
2177 eargp->gid_given = 1;
2178 }
2179#else
2180 rb_raise(rb_eNotImpError,
2181 "gid option is unimplemented on this machine");
2182#endif
2183 }
2184 else if (id == id_exception) {
2185 if (eargp->exception_given) {
2186 rb_raise(rb_eArgError, "exception option specified twice");
2187 }
2188 eargp->exception_given = 1;
2189 eargp->exception = TO_BOOL(val, "exception");
2190 }
2191 else {
2192 return ST_STOP;
2193 }
2194 break;
2195
2196 case T_FIXNUM:
2197 case T_FILE:
2198 case T_ARRAY:
2199redirect:
2200 check_exec_redirect(key, val, eargp);
2201 break;
2202
2203 default:
2204 return ST_STOP;
2205 }
2206
2207 RB_GC_GUARD(execarg_obj);
2208 return ST_CONTINUE;
2209}
2210
2211static int
2212check_exec_options_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2213{
2214 VALUE key = (VALUE)st_key;
2215 VALUE val = (VALUE)st_val;
2216 VALUE execarg_obj = (VALUE)arg;
2217 if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) {
2218 if (SYMBOL_P(key))
2219 rb_raise(rb_eArgError, "wrong exec option symbol: % "PRIsVALUE,
2220 key);
2221 rb_raise(rb_eArgError, "wrong exec option");
2222 }
2223 return ST_CONTINUE;
2224}
2225
2226static int
2227check_exec_options_i_extract(st_data_t st_key, st_data_t st_val, st_data_t arg)
2228{
2229 VALUE key = (VALUE)st_key;
2230 VALUE val = (VALUE)st_val;
2231 VALUE *args = (VALUE *)arg;
2232 VALUE execarg_obj = args[0];
2233 if (rb_execarg_addopt(execarg_obj, key, val) != ST_CONTINUE) {
2234 VALUE nonopts = args[1];
2235 if (NIL_P(nonopts)) args[1] = nonopts = rb_hash_new();
2236 rb_hash_aset(nonopts, key, val);
2237 }
2238 return ST_CONTINUE;
2239}
2240
2241static int
2242check_exec_fds_1(struct rb_execarg *eargp, VALUE h, int maxhint, VALUE ary)
2243{
2244 long i;
2245
2246 if (ary != Qfalse) {
2247 for (i = 0; i < RARRAY_LEN(ary); i++) {
2248 VALUE elt = RARRAY_AREF(ary, i);
2249 int fd = FIX2INT(RARRAY_AREF(elt, 0));
2250 if (RTEST(rb_hash_lookup(h, INT2FIX(fd)))) {
2251 rb_raise(rb_eArgError, "fd %d specified twice", fd);
2252 }
2253 if (ary == eargp->fd_dup2)
2254 rb_hash_aset(h, INT2FIX(fd), Qtrue);
2255 else if (ary == eargp->fd_dup2_child)
2256 rb_hash_aset(h, INT2FIX(fd), RARRAY_AREF(elt, 1));
2257 else /* ary == eargp->fd_close */
2258 rb_hash_aset(h, INT2FIX(fd), INT2FIX(-1));
2259 if (maxhint < fd)
2260 maxhint = fd;
2261 if (ary == eargp->fd_dup2 || ary == eargp->fd_dup2_child) {
2262 fd = FIX2INT(RARRAY_AREF(elt, 1));
2263 if (maxhint < fd)
2264 maxhint = fd;
2265 }
2266 }
2267 }
2268 return maxhint;
2269}
2270
2271static VALUE
2272check_exec_fds(struct rb_execarg *eargp)
2273{
2274 VALUE h = rb_hash_new();
2275 VALUE ary;
2276 int maxhint = -1;
2277 long i;
2278
2279 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_dup2);
2280 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_close);
2281 maxhint = check_exec_fds_1(eargp, h, maxhint, eargp->fd_dup2_child);
2282
2283 if (eargp->fd_dup2_child) {
2284 ary = eargp->fd_dup2_child;
2285 for (i = 0; i < RARRAY_LEN(ary); i++) {
2286 VALUE elt = RARRAY_AREF(ary, i);
2287 int newfd = FIX2INT(RARRAY_AREF(elt, 0));
2288 int oldfd = FIX2INT(RARRAY_AREF(elt, 1));
2289 int lastfd = oldfd;
2290 VALUE val = rb_hash_lookup(h, INT2FIX(lastfd));
2291 long depth = 0;
2292 while (FIXNUM_P(val) && 0 <= FIX2INT(val)) {
2293 lastfd = FIX2INT(val);
2294 val = rb_hash_lookup(h, val);
2295 if (RARRAY_LEN(ary) < depth)
2296 rb_raise(rb_eArgError, "cyclic child fd redirection from %d", oldfd);
2297 depth++;
2298 }
2299 if (val != Qtrue)
2300 rb_raise(rb_eArgError, "child fd %d is not redirected", oldfd);
2301 if (oldfd != lastfd) {
2302 VALUE val2;
2303 rb_ary_store(elt, 1, INT2FIX(lastfd));
2304 rb_hash_aset(h, INT2FIX(newfd), INT2FIX(lastfd));
2305 val = INT2FIX(oldfd);
2306 while (FIXNUM_P(val2 = rb_hash_lookup(h, val))) {
2307 rb_hash_aset(h, val, INT2FIX(lastfd));
2308 val = val2;
2309 }
2310 }
2311 }
2312 }
2313
2314 eargp->close_others_maxhint = maxhint;
2315 return h;
2316}
2317
2318static void
2319rb_check_exec_options(VALUE opthash, VALUE execarg_obj)
2320{
2321 if (RHASH_EMPTY_P(opthash))
2322 return;
2323 rb_hash_stlike_foreach(opthash, check_exec_options_i, (st_data_t)execarg_obj);
2324}
2325
2326VALUE
2327rb_execarg_extract_options(VALUE execarg_obj, VALUE opthash)
2328{
2329 VALUE args[2];
2330 if (RHASH_EMPTY_P(opthash))
2331 return Qnil;
2332 args[0] = execarg_obj;
2333 args[1] = Qnil;
2334 rb_hash_stlike_foreach(opthash, check_exec_options_i_extract, (st_data_t)args);
2335 return args[1];
2336}
2337
2338#ifdef ENV_IGNORECASE
2339#define ENVMATCH(s1, s2) (STRCASECMP((s1), (s2)) == 0)
2340#else
2341#define ENVMATCH(n1, n2) (strcmp((n1), (n2)) == 0)
2342#endif
2343
2344static int
2345check_exec_env_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2346{
2347 VALUE key = (VALUE)st_key;
2348 VALUE val = (VALUE)st_val;
2349 VALUE env = ((VALUE *)arg)[0];
2350 VALUE *path = &((VALUE *)arg)[1];
2351 char *k;
2352
2353 k = StringValueCStr(key);
2354 if (strchr(k, '='))
2355 rb_raise(rb_eArgError, "environment name contains a equal : %"PRIsVALUE, key);
2356
2357 if (!NIL_P(val))
2358 StringValueCStr(val);
2359
2360 key = EXPORT_STR(key);
2361 if (!NIL_P(val)) val = EXPORT_STR(val);
2362
2363 if (ENVMATCH(k, PATH_ENV)) {
2364 *path = val;
2365 }
2366 rb_ary_push(env, hide_obj(rb_assoc_new(key, val)));
2367
2368 return ST_CONTINUE;
2369}
2370
2371static VALUE
2372rb_check_exec_env(VALUE hash, VALUE *path)
2373{
2374 VALUE env[2];
2375
2376 env[0] = hide_obj(rb_ary_new());
2377 env[1] = Qfalse;
2378 rb_hash_stlike_foreach(hash, check_exec_env_i, (st_data_t)env);
2379 *path = env[1];
2380
2381 return env[0];
2382}
2383
2384static VALUE
2385rb_check_argv(int argc, VALUE *argv)
2386{
2387 VALUE tmp, prog;
2388 int i;
2389
2390 rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
2391
2392 prog = 0;
2393 tmp = rb_check_array_type(argv[0]);
2394 if (!NIL_P(tmp)) {
2395 if (RARRAY_LEN(tmp) != 2) {
2396 rb_raise(rb_eArgError, "wrong first argument");
2397 }
2398 prog = RARRAY_AREF(tmp, 0);
2399 argv[0] = RARRAY_AREF(tmp, 1);
2400 StringValue(prog);
2401 StringValueCStr(prog);
2402 prog = rb_str_new_frozen(prog);
2403 }
2404 for (i = 0; i < argc; i++) {
2405 StringValue(argv[i]);
2406 argv[i] = rb_str_new_frozen(argv[i]);
2407 StringValueCStr(argv[i]);
2408 }
2409 return prog;
2410}
2411
2412static VALUE
2413check_hash(VALUE obj)
2414{
2415 if (RB_SPECIAL_CONST_P(obj)) return Qnil;
2416 switch (RB_BUILTIN_TYPE(obj)) {
2417 case T_STRING:
2418 case T_ARRAY:
2419 return Qnil;
2420 default:
2421 break;
2422 }
2423 return rb_check_hash_type(obj);
2424}
2425
2426static VALUE
2427rb_exec_getargs(int *argc_p, VALUE **argv_p, int accept_shell, VALUE *env_ret, VALUE *opthash_ret)
2428{
2429 VALUE hash, prog;
2430
2431 if (0 < *argc_p) {
2432 hash = check_hash((*argv_p)[*argc_p-1]);
2433 if (!NIL_P(hash)) {
2434 *opthash_ret = hash;
2435 (*argc_p)--;
2436 }
2437 }
2438
2439 if (0 < *argc_p) {
2440 hash = check_hash((*argv_p)[0]);
2441 if (!NIL_P(hash)) {
2442 *env_ret = hash;
2443 (*argc_p)--;
2444 (*argv_p)++;
2445 }
2446 }
2447 prog = rb_check_argv(*argc_p, *argv_p);
2448 if (!prog) {
2449 prog = (*argv_p)[0];
2450 if (accept_shell && *argc_p == 1) {
2451 *argc_p = 0;
2452 *argv_p = 0;
2453 }
2454 }
2455 return prog;
2456}
2457
2458#ifndef _WIN32
2460 const char *ptr;
2461 size_t len;
2462};
2463
2464static int
2465compare_posix_sh(const void *key, const void *el)
2466{
2467 const struct string_part *word = key;
2468 int ret = strncmp(word->ptr, el, word->len);
2469 if (!ret && ((const char *)el)[word->len]) ret = -1;
2470 return ret;
2471}
2472#endif
2473
2474static void
2475rb_exec_fillarg(VALUE prog, int argc, VALUE *argv, VALUE env, VALUE opthash, VALUE execarg_obj)
2476{
2477 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2478 char fbuf[MAXPATHLEN];
2479
2480 MEMZERO(eargp, struct rb_execarg, 1);
2481
2482 if (!NIL_P(opthash)) {
2483 rb_check_exec_options(opthash, execarg_obj);
2484 }
2485 if (!NIL_P(env)) {
2486 env = rb_check_exec_env(env, &eargp->path_env);
2487 eargp->env_modification = env;
2488 }
2489
2490 prog = EXPORT_STR(prog);
2491 eargp->use_shell = argc == 0;
2492 if (eargp->use_shell)
2493 eargp->invoke.sh.shell_script = prog;
2494 else
2495 eargp->invoke.cmd.command_name = prog;
2496
2497#ifndef _WIN32
2498 if (eargp->use_shell) {
2499 static const char posix_sh_cmds[][9] = {
2500 "!", /* reserved */
2501 ".", /* special built-in */
2502 ":", /* special built-in */
2503 "break", /* special built-in */
2504 "case", /* reserved */
2505 "continue", /* special built-in */
2506 "do", /* reserved */
2507 "done", /* reserved */
2508 "elif", /* reserved */
2509 "else", /* reserved */
2510 "esac", /* reserved */
2511 "eval", /* special built-in */
2512 "exec", /* special built-in */
2513 "exit", /* special built-in */
2514 "export", /* special built-in */
2515 "fi", /* reserved */
2516 "for", /* reserved */
2517 "if", /* reserved */
2518 "in", /* reserved */
2519 "readonly", /* special built-in */
2520 "return", /* special built-in */
2521 "set", /* special built-in */
2522 "shift", /* special built-in */
2523 "then", /* reserved */
2524 "times", /* special built-in */
2525 "trap", /* special built-in */
2526 "unset", /* special built-in */
2527 "until", /* reserved */
2528 "while", /* reserved */
2529 };
2530 const char *p;
2531 struct string_part first = {0, 0};
2532 int has_meta = 0;
2533 /*
2534 * meta characters:
2535 *
2536 * * Pathname Expansion
2537 * ? Pathname Expansion
2538 * {} Grouping Commands
2539 * [] Pathname Expansion
2540 * <> Redirection
2541 * () Grouping Commands
2542 * ~ Tilde Expansion
2543 * & AND Lists, Asynchronous Lists
2544 * | OR Lists, Pipelines
2545 * \ Escape Character
2546 * $ Parameter Expansion
2547 * ; Sequential Lists
2548 * ' Single-Quotes
2549 * ` Command Substitution
2550 * " Double-Quotes
2551 * \n Lists
2552 *
2553 * # Comment
2554 * = Assignment preceding command name
2555 * % (used in Parameter Expansion)
2556 */
2557 for (p = RSTRING_PTR(prog); *p; p++) {
2558 if (*p == ' ' || *p == '\t') {
2559 if (first.ptr && !first.len) first.len = p - first.ptr;
2560 }
2561 else {
2562 if (!first.ptr) first.ptr = p;
2563 }
2564 if (!has_meta && strchr("*?{}[]<>()~&|\\$;'`\"\n#", *p))
2565 has_meta = 1;
2566 if (!first.len) {
2567 if (*p == '=') {
2568 has_meta = 1;
2569 }
2570 else if (*p == '/') {
2571 first.len = 0x100; /* longer than any posix_sh_cmds */
2572 }
2573 }
2574 if (has_meta)
2575 break;
2576 }
2577 if (!has_meta && first.ptr) {
2578 if (!first.len) first.len = p - first.ptr;
2579 if (first.len > 0 && first.len <= sizeof(posix_sh_cmds[0]) &&
2580 bsearch(&first, posix_sh_cmds, numberof(posix_sh_cmds), sizeof(posix_sh_cmds[0]), compare_posix_sh))
2581 has_meta = 1;
2582 }
2583 if (!has_meta) {
2584 /* avoid shell since no shell meta character found. */
2585 eargp->use_shell = 0;
2586 }
2587 if (!eargp->use_shell) {
2588 VALUE argv_buf;
2589 argv_buf = hide_obj(rb_str_buf_new(0));
2590 p = RSTRING_PTR(prog);
2591 while (*p) {
2592 while (*p == ' ' || *p == '\t')
2593 p++;
2594 if (*p) {
2595 const char *w = p;
2596 while (*p && *p != ' ' && *p != '\t')
2597 p++;
2598 rb_str_buf_cat(argv_buf, w, p-w);
2599 rb_str_buf_cat(argv_buf, "", 1); /* append '\0' */
2600 }
2601 }
2602 eargp->invoke.cmd.argv_buf = argv_buf;
2603 eargp->invoke.cmd.command_name =
2604 hide_obj(rb_str_subseq(argv_buf, 0, strlen(RSTRING_PTR(argv_buf))));
2605 rb_enc_copy(eargp->invoke.cmd.command_name, prog);
2606 }
2607 }
2608#endif
2609
2610 if (!eargp->use_shell) {
2611 const char *abspath;
2612 const char *path_env = 0;
2613 if (RTEST(eargp->path_env)) path_env = RSTRING_PTR(eargp->path_env);
2614 abspath = dln_find_exe_r(RSTRING_PTR(eargp->invoke.cmd.command_name),
2615 path_env, fbuf, sizeof(fbuf));
2616 if (abspath)
2617 eargp->invoke.cmd.command_abspath = rb_str_new_cstr(abspath);
2618 else
2619 eargp->invoke.cmd.command_abspath = Qnil;
2620 }
2621
2622 if (!eargp->use_shell && !eargp->invoke.cmd.argv_buf) {
2623 int i;
2624 VALUE argv_buf;
2625 argv_buf = rb_str_buf_new(0);
2626 hide_obj(argv_buf);
2627 for (i = 0; i < argc; i++) {
2628 VALUE arg = argv[i];
2629 const char *s = StringValueCStr(arg);
2630#ifdef DEFAULT_PROCESS_ENCODING
2631 arg = EXPORT_STR(arg);
2632 s = RSTRING_PTR(arg);
2633#endif
2634 rb_str_buf_cat(argv_buf, s, RSTRING_LEN(arg) + 1); /* include '\0' */
2635 }
2636 eargp->invoke.cmd.argv_buf = argv_buf;
2637 }
2638
2639 if (!eargp->use_shell) {
2640 const char *p, *ep, *null=NULL;
2641 VALUE argv_str;
2642 argv_str = hide_obj(rb_str_buf_new(sizeof(char*) * (argc + 2)));
2643 rb_str_buf_cat(argv_str, (char *)&null, sizeof(null)); /* place holder for /bin/sh of try_with_sh. */
2644 p = RSTRING_PTR(eargp->invoke.cmd.argv_buf);
2645 ep = p + RSTRING_LEN(eargp->invoke.cmd.argv_buf);
2646 while (p < ep) {
2647 rb_str_buf_cat(argv_str, (char *)&p, sizeof(p));
2648 p += strlen(p) + 1;
2649 }
2650 rb_str_buf_cat(argv_str, (char *)&null, sizeof(null)); /* terminator for execve. */
2651 eargp->invoke.cmd.argv_str =
2652 rb_imemo_tmpbuf_new_from_an_RString(argv_str);
2653 }
2654 RB_GC_GUARD(execarg_obj);
2655}
2656
2657struct rb_execarg *
2658rb_execarg_get(VALUE execarg_obj)
2659{
2660 struct rb_execarg *eargp;
2661 TypedData_Get_Struct(execarg_obj, struct rb_execarg, &exec_arg_data_type, eargp);
2662 return eargp;
2663}
2664
2665static VALUE
2666rb_execarg_init(int argc, const VALUE *orig_argv, int accept_shell, VALUE execarg_obj)
2667{
2668 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2669 VALUE prog, ret;
2670 VALUE env = Qnil, opthash = Qnil;
2671 VALUE argv_buf;
2672 VALUE *argv = ALLOCV_N(VALUE, argv_buf, argc);
2673 MEMCPY(argv, orig_argv, VALUE, argc);
2674 prog = rb_exec_getargs(&argc, &argv, accept_shell, &env, &opthash);
2675 rb_exec_fillarg(prog, argc, argv, env, opthash, execarg_obj);
2676 ALLOCV_END(argv_buf);
2677 ret = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
2678 RB_GC_GUARD(execarg_obj);
2679 return ret;
2680}
2681
2682VALUE
2683rb_execarg_new(int argc, const VALUE *argv, int accept_shell, int allow_exc_opt)
2684{
2685 VALUE execarg_obj;
2686 struct rb_execarg *eargp;
2687 execarg_obj = TypedData_Make_Struct(0, struct rb_execarg, &exec_arg_data_type, eargp);
2688 rb_execarg_init(argc, argv, accept_shell, execarg_obj);
2689 if (!allow_exc_opt && eargp->exception_given) {
2690 rb_raise(rb_eArgError, "exception option is not allowed");
2691 }
2692 return execarg_obj;
2693}
2694
2695void
2696rb_execarg_setenv(VALUE execarg_obj, VALUE env)
2697{
2698 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2699 env = !NIL_P(env) ? rb_check_exec_env(env, &eargp->path_env) : Qfalse;
2700 eargp->env_modification = env;
2701 RB_GC_GUARD(execarg_obj);
2702}
2703
2704static int
2705fill_envp_buf_i(st_data_t st_key, st_data_t st_val, st_data_t arg)
2706{
2707 VALUE key = (VALUE)st_key;
2708 VALUE val = (VALUE)st_val;
2709 VALUE envp_buf = (VALUE)arg;
2710
2711 rb_str_buf_cat2(envp_buf, StringValueCStr(key));
2712 rb_str_buf_cat2(envp_buf, "=");
2713 rb_str_buf_cat2(envp_buf, StringValueCStr(val));
2714 rb_str_buf_cat(envp_buf, "", 1); /* append '\0' */
2715
2716 return ST_CONTINUE;
2717}
2718
2719
2720static long run_exec_dup2_tmpbuf_size(long n);
2721
2723 VALUE fname;
2724 int oflags;
2725 mode_t perm;
2726 int ret;
2727 int err;
2728};
2729
2730static void *
2731open_func(void *ptr)
2732{
2733 struct open_struct *data = ptr;
2734 const char *fname = RSTRING_PTR(data->fname);
2735 data->ret = parent_redirect_open(fname, data->oflags, data->perm);
2736 data->err = errno;
2737 return NULL;
2738}
2739
2740static void
2741rb_execarg_allocate_dup2_tmpbuf(struct rb_execarg *eargp, long len)
2742{
2743 VALUE tmpbuf = rb_imemo_tmpbuf_new();
2744 rb_imemo_tmpbuf_set_ptr(tmpbuf, ruby_xmalloc(run_exec_dup2_tmpbuf_size(len)));
2745 eargp->dup2_tmpbuf = tmpbuf;
2746}
2747
2748static VALUE
2749rb_execarg_parent_start1(VALUE execarg_obj)
2750{
2751 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2752 int unsetenv_others;
2753 VALUE envopts;
2754 VALUE ary;
2755
2756 ary = eargp->fd_open;
2757 if (ary != Qfalse) {
2758 long i;
2759 for (i = 0; i < RARRAY_LEN(ary); i++) {
2760 VALUE elt = RARRAY_AREF(ary, i);
2761 int fd = FIX2INT(RARRAY_AREF(elt, 0));
2762 VALUE param = RARRAY_AREF(elt, 1);
2763 VALUE vpath = RARRAY_AREF(param, 0);
2764 int flags = NUM2INT(RARRAY_AREF(param, 1));
2765 mode_t perm = NUM2MODET(RARRAY_AREF(param, 2));
2766 VALUE fd2v = RARRAY_AREF(param, 3);
2767 int fd2;
2768 if (NIL_P(fd2v)) {
2769 struct open_struct open_data;
2770 again:
2771 open_data.fname = vpath;
2772 open_data.oflags = flags;
2773 open_data.perm = perm;
2774 open_data.ret = -1;
2775 open_data.err = EINTR;
2776 rb_thread_call_without_gvl2(open_func, (void *)&open_data, RUBY_UBF_IO, 0);
2777 if (open_data.ret == -1) {
2778 if (open_data.err == EINTR) {
2780 goto again;
2781 }
2782 rb_syserr_fail_str(open_data.err, vpath);
2783 }
2784 fd2 = open_data.ret;
2785 rb_update_max_fd(fd2);
2786 RARRAY_ASET(param, 3, INT2FIX(fd2));
2788 }
2789 else {
2790 fd2 = NUM2INT(fd2v);
2791 }
2792 rb_execarg_addopt(execarg_obj, INT2FIX(fd), INT2FIX(fd2));
2793 }
2794 }
2795
2796 eargp->redirect_fds = check_exec_fds(eargp);
2797
2798 ary = eargp->fd_dup2;
2799 if (ary != Qfalse) {
2800 rb_execarg_allocate_dup2_tmpbuf(eargp, RARRAY_LEN(ary));
2801 }
2802
2803 unsetenv_others = eargp->unsetenv_others_given && eargp->unsetenv_others_do;
2804 envopts = eargp->env_modification;
2805 if (ALWAYS_NEED_ENVP || unsetenv_others || envopts != Qfalse) {
2806 VALUE envtbl, envp_str, envp_buf;
2807 char *p, *ep;
2808 if (unsetenv_others) {
2809 envtbl = rb_hash_new();
2810 }
2811 else {
2812 envtbl = rb_env_to_hash();
2813 }
2814 hide_obj(envtbl);
2815 if (envopts != Qfalse) {
2816 st_table *stenv = RHASH_TBL_RAW(envtbl);
2817 long i;
2818 for (i = 0; i < RARRAY_LEN(envopts); i++) {
2819 VALUE pair = RARRAY_AREF(envopts, i);
2820 VALUE key = RARRAY_AREF(pair, 0);
2821 VALUE val = RARRAY_AREF(pair, 1);
2822 if (NIL_P(val)) {
2823 st_data_t stkey = (st_data_t)key;
2824 st_delete(stenv, &stkey, NULL);
2825 }
2826 else {
2827 st_insert(stenv, (st_data_t)key, (st_data_t)val);
2828 RB_OBJ_WRITTEN(envtbl, Qundef, key);
2829 RB_OBJ_WRITTEN(envtbl, Qundef, val);
2830 }
2831 }
2832 }
2833 envp_buf = rb_str_buf_new(0);
2834 hide_obj(envp_buf);
2835 rb_hash_stlike_foreach(envtbl, fill_envp_buf_i, (st_data_t)envp_buf);
2836 envp_str = rb_str_buf_new(sizeof(char*) * (RHASH_SIZE(envtbl) + 1));
2837 hide_obj(envp_str);
2838 p = RSTRING_PTR(envp_buf);
2839 ep = p + RSTRING_LEN(envp_buf);
2840 while (p < ep) {
2841 rb_str_buf_cat(envp_str, (char *)&p, sizeof(p));
2842 p += strlen(p) + 1;
2843 }
2844 p = NULL;
2845 rb_str_buf_cat(envp_str, (char *)&p, sizeof(p));
2846 eargp->envp_str =
2847 rb_imemo_tmpbuf_new_from_an_RString(envp_str);
2848 eargp->envp_buf = envp_buf;
2849
2850 /*
2851 char **tmp_envp = (char **)RSTRING_PTR(envp_str);
2852 while (*tmp_envp) {
2853 printf("%s\n", *tmp_envp);
2854 tmp_envp++;
2855 }
2856 */
2857 }
2858
2859 RB_GC_GUARD(execarg_obj);
2860 return Qnil;
2861}
2862
2863void
2864rb_execarg_parent_start(VALUE execarg_obj)
2865{
2866 int state;
2867 rb_protect(rb_execarg_parent_start1, execarg_obj, &state);
2868 if (state) {
2869 rb_execarg_parent_end(execarg_obj);
2870 rb_jump_tag(state);
2871 }
2872}
2873
2874static VALUE
2875execarg_parent_end(VALUE execarg_obj)
2876{
2877 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
2878 int err = errno;
2879 VALUE ary;
2880
2881 ary = eargp->fd_open;
2882 if (ary != Qfalse) {
2883 long i;
2884 for (i = 0; i < RARRAY_LEN(ary); i++) {
2885 VALUE elt = RARRAY_AREF(ary, i);
2886 VALUE param = RARRAY_AREF(elt, 1);
2887 VALUE fd2v;
2888 int fd2;
2889 fd2v = RARRAY_AREF(param, 3);
2890 if (!NIL_P(fd2v)) {
2891 fd2 = FIX2INT(fd2v);
2892 parent_redirect_close(fd2);
2893 RARRAY_ASET(param, 3, Qnil);
2894 }
2895 }
2896 }
2897
2898 errno = err;
2899 RB_GC_GUARD(execarg_obj);
2900 return execarg_obj;
2901}
2902
2903void
2904rb_execarg_parent_end(VALUE execarg_obj)
2905{
2906 execarg_parent_end(execarg_obj);
2907 RB_GC_GUARD(execarg_obj);
2908}
2909
2910static void
2911rb_exec_fail(struct rb_execarg *eargp, int err, const char *errmsg)
2912{
2913 if (!errmsg || !*errmsg) return;
2914 if (strcmp(errmsg, "chdir") == 0) {
2915 rb_sys_fail_str(eargp->chdir_dir);
2916 }
2917 rb_sys_fail(errmsg);
2918}
2919
2920#if 0
2921void
2922rb_execarg_fail(VALUE execarg_obj, int err, const char *errmsg)
2923{
2924 if (!errmsg || !*errmsg) return;
2925 rb_exec_fail(rb_execarg_get(execarg_obj), err, errmsg);
2926 RB_GC_GUARD(execarg_obj);
2927}
2928#endif
2929
2930VALUE
2931rb_f_exec(int argc, const VALUE *argv)
2932{
2933 VALUE execarg_obj, fail_str;
2934 struct rb_execarg *eargp;
2935#define CHILD_ERRMSG_BUFLEN 80
2936 char errmsg[CHILD_ERRMSG_BUFLEN] = { '\0' };
2937 int err, state;
2938
2939 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
2940 eargp = rb_execarg_get(execarg_obj);
2941 before_exec(); /* stop timer thread before redirects */
2942
2943 rb_protect(rb_execarg_parent_start1, execarg_obj, &state);
2944 if (state) {
2945 execarg_parent_end(execarg_obj);
2946 after_exec(); /* restart timer thread */
2947 rb_jump_tag(state);
2948 }
2949
2950 fail_str = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
2951
2952 err = exec_async_signal_safe(eargp, errmsg, sizeof(errmsg));
2953 after_exec(); /* restart timer thread */
2954
2955 rb_exec_fail(eargp, err, errmsg);
2956 RB_GC_GUARD(execarg_obj);
2957 rb_syserr_fail_str(err, fail_str);
2959}
2960
2961NORETURN(static VALUE f_exec(int c, const VALUE *a, VALUE _));
2962
2963/*
2964 * call-seq:
2965 * exec([env, ] command_line, options = {})
2966 * exec([env, ] exe_path, *args, options = {})
2967 *
2968 * Replaces the current process by doing one of the following:
2969 *
2970 * - Passing string +command_line+ to the shell.
2971 * - Invoking the executable at +exe_path+.
2972 *
2973 * This method has potential security vulnerabilities if called with untrusted input;
2974 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
2975 *
2976 * The new process is created using the
2977 * {exec system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/execve.html];
2978 * it may inherit some of its environment from the calling program
2979 * (possibly including open file descriptors).
2980 *
2981 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
2982 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
2983 *
2984 * Argument +options+ is a hash of options for the new process;
2985 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
2986 *
2987 * The first required argument is one of the following:
2988 *
2989 * - +command_line+ if it is a string,
2990 * and if it begins with a shell reserved word or special built-in,
2991 * or if it contains one or more meta characters.
2992 * - +exe_path+ otherwise.
2993 *
2994 * <b>Argument +command_line+</b>
2995 *
2996 * \String argument +command_line+ is a command line to be passed to a shell;
2997 * it must begin with a shell reserved word, begin with a special built-in,
2998 * or contain meta characters:
2999 *
3000 * exec('if true; then echo "Foo"; fi') # Shell reserved word.
3001 * exec('exit') # Built-in.
3002 * exec('date > date.tmp') # Contains meta character.
3003 *
3004 * The command line may also contain arguments and options for the command:
3005 *
3006 * exec('echo "Foo"')
3007 *
3008 * Output:
3009 *
3010 * Foo
3011 *
3012 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
3013 *
3014 * Raises an exception if the new process could not execute.
3015 *
3016 * <b>Argument +exe_path+</b>
3017 *
3018 * Argument +exe_path+ is one of the following:
3019 *
3020 * - The string path to an executable to be called.
3021 * - A 2-element array containing the path to an executable
3022 * and the string to be used as the name of the executing process.
3023 *
3024 * Example:
3025 *
3026 * exec('/usr/bin/date')
3027 *
3028 * Output:
3029 *
3030 * Sat Aug 26 09:38:00 AM CDT 2023
3031 *
3032 * Ruby invokes the executable directly.
3033 * This form does not use the shell;
3034 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
3035 *
3036 * exec('doesnt_exist') # Raises Errno::ENOENT
3037 *
3038 * If one or more +args+ is given, each is an argument or option
3039 * to be passed to the executable:
3040 *
3041 * exec('echo', 'C*')
3042 * exec('echo', 'hello', 'world')
3043 *
3044 * Output:
3045 *
3046 * C*
3047 * hello world
3048 *
3049 * Raises an exception if the new process could not execute.
3050 */
3051
3052static VALUE
3053f_exec(int c, const VALUE *a, VALUE _)
3054{
3055 rb_f_exec(c, a);
3057}
3058
3059#define ERRMSG(str) \
3060 ((errmsg && 0 < errmsg_buflen) ? \
3061 (void)strlcpy(errmsg, (str), errmsg_buflen) : (void)0)
3062
3063#define ERRMSG_FMT(...) \
3064 ((errmsg && 0 < errmsg_buflen) ? \
3065 (void)snprintf(errmsg, errmsg_buflen, __VA_ARGS__) : (void)0)
3066
3067static int fd_get_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
3068static int fd_set_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
3069static int fd_clear_cloexec(int fd, char *errmsg, size_t errmsg_buflen);
3070
3071static int
3072save_redirect_fd(int fd, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3073{
3074 if (sargp) {
3075 VALUE newary, redirection;
3076 int save_fd = redirect_cloexec_dup(fd), cloexec;
3077 if (save_fd == -1) {
3078 if (errno == EBADF)
3079 return 0;
3080 ERRMSG("dup");
3081 return -1;
3082 }
3083 rb_update_max_fd(save_fd);
3084 newary = sargp->fd_dup2;
3085 if (newary == Qfalse) {
3086 newary = hide_obj(rb_ary_new());
3087 sargp->fd_dup2 = newary;
3088 }
3089 cloexec = fd_get_cloexec(fd, errmsg, errmsg_buflen);
3090 redirection = hide_obj(rb_assoc_new(INT2FIX(fd), INT2FIX(save_fd)));
3091 if (cloexec) rb_ary_push(redirection, Qtrue);
3092 rb_ary_push(newary, redirection);
3093
3094 newary = sargp->fd_close;
3095 if (newary == Qfalse) {
3096 newary = hide_obj(rb_ary_new());
3097 sargp->fd_close = newary;
3098 }
3099 rb_ary_push(newary, hide_obj(rb_assoc_new(INT2FIX(save_fd), Qnil)));
3100 }
3101
3102 return 0;
3103}
3104
3105static int
3106intcmp(const void *a, const void *b)
3107{
3108 return *(int*)a - *(int*)b;
3109}
3110
3111static int
3112intrcmp(const void *a, const void *b)
3113{
3114 return *(int*)b - *(int*)a;
3115}
3116
3118 int oldfd;
3119 int newfd;
3120 long older_index;
3121 long num_newer;
3122 int cloexec;
3123};
3124
3125static long
3126run_exec_dup2_tmpbuf_size(long n)
3127{
3128 return sizeof(struct run_exec_dup2_fd_pair) * n;
3129}
3130
3131/* This function should be async-signal-safe. Actually it is. */
3132static int
3133fd_get_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3134{
3135#ifdef F_GETFD
3136 int ret = 0;
3137 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3138 if (ret == -1) {
3139 ERRMSG("fcntl(F_GETFD)");
3140 return -1;
3141 }
3142 if (ret & FD_CLOEXEC) return 1;
3143#endif
3144 return 0;
3145}
3146
3147/* This function should be async-signal-safe. Actually it is. */
3148static int
3149fd_set_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3150{
3151#ifdef F_GETFD
3152 int ret = 0;
3153 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3154 if (ret == -1) {
3155 ERRMSG("fcntl(F_GETFD)");
3156 return -1;
3157 }
3158 if (!(ret & FD_CLOEXEC)) {
3159 ret |= FD_CLOEXEC;
3160 ret = fcntl(fd, F_SETFD, ret); /* async-signal-safe */
3161 if (ret == -1) {
3162 ERRMSG("fcntl(F_SETFD)");
3163 return -1;
3164 }
3165 }
3166#endif
3167 return 0;
3168}
3169
3170/* This function should be async-signal-safe. Actually it is. */
3171static int
3172fd_clear_cloexec(int fd, char *errmsg, size_t errmsg_buflen)
3173{
3174#ifdef F_GETFD
3175 int ret;
3176 ret = fcntl(fd, F_GETFD); /* async-signal-safe */
3177 if (ret == -1) {
3178 ERRMSG("fcntl(F_GETFD)");
3179 return -1;
3180 }
3181 if (ret & FD_CLOEXEC) {
3182 ret &= ~FD_CLOEXEC;
3183 ret = fcntl(fd, F_SETFD, ret); /* async-signal-safe */
3184 if (ret == -1) {
3185 ERRMSG("fcntl(F_SETFD)");
3186 return -1;
3187 }
3188 }
3189#endif
3190 return 0;
3191}
3192
3193/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3194static int
3195run_exec_dup2(VALUE ary, VALUE tmpbuf, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3196{
3197 long n, i;
3198 int ret;
3199 int extra_fd = -1;
3200 struct rb_imemo_tmpbuf_struct *buf = (void *)tmpbuf;
3201 struct run_exec_dup2_fd_pair *pairs = (void *)buf->ptr;
3202
3203 n = RARRAY_LEN(ary);
3204
3205 /* initialize oldfd and newfd: O(n) */
3206 for (i = 0; i < n; i++) {
3207 VALUE elt = RARRAY_AREF(ary, i);
3208 pairs[i].oldfd = FIX2INT(RARRAY_AREF(elt, 1));
3209 pairs[i].newfd = FIX2INT(RARRAY_AREF(elt, 0)); /* unique */
3210 pairs[i].cloexec = RARRAY_LEN(elt) > 2 && RTEST(RARRAY_AREF(elt, 2));
3211 pairs[i].older_index = -1;
3212 }
3213
3214 /* sort the table by oldfd: O(n log n) */
3215 if (!sargp)
3216 qsort(pairs, n, sizeof(struct run_exec_dup2_fd_pair), intcmp); /* hopefully async-signal-safe */
3217 else
3218 qsort(pairs, n, sizeof(struct run_exec_dup2_fd_pair), intrcmp);
3219
3220 /* initialize older_index and num_newer: O(n log n) */
3221 for (i = 0; i < n; i++) {
3222 int newfd = pairs[i].newfd;
3223 struct run_exec_dup2_fd_pair key, *found;
3224 key.oldfd = newfd;
3225 found = bsearch(&key, pairs, n, sizeof(struct run_exec_dup2_fd_pair), intcmp); /* hopefully async-signal-safe */
3226 pairs[i].num_newer = 0;
3227 if (found) {
3228 while (pairs < found && (found-1)->oldfd == newfd)
3229 found--;
3230 while (found < pairs+n && found->oldfd == newfd) {
3231 pairs[i].num_newer++;
3232 found->older_index = i;
3233 found++;
3234 }
3235 }
3236 }
3237
3238 /* non-cyclic redirection: O(n) */
3239 for (i = 0; i < n; i++) {
3240 long j = i;
3241 while (j != -1 && pairs[j].oldfd != -1 && pairs[j].num_newer == 0) {
3242 if (save_redirect_fd(pairs[j].newfd, sargp, errmsg, errmsg_buflen) < 0) /* async-signal-safe */
3243 goto fail;
3244 ret = redirect_dup2(pairs[j].oldfd, pairs[j].newfd); /* async-signal-safe */
3245 if (ret == -1) {
3246 ERRMSG("dup2");
3247 goto fail;
3248 }
3249 if (pairs[j].cloexec &&
3250 fd_set_cloexec(pairs[j].newfd, errmsg, errmsg_buflen)) {
3251 goto fail;
3252 }
3253 rb_update_max_fd(pairs[j].newfd); /* async-signal-safe but don't need to call it in a child process. */
3254 pairs[j].oldfd = -1;
3255 j = pairs[j].older_index;
3256 if (j != -1)
3257 pairs[j].num_newer--;
3258 }
3259 }
3260
3261 /* cyclic redirection: O(n) */
3262 for (i = 0; i < n; i++) {
3263 long j;
3264 if (pairs[i].oldfd == -1)
3265 continue;
3266 if (pairs[i].oldfd == pairs[i].newfd) { /* self cycle */
3267 if (fd_clear_cloexec(pairs[i].oldfd, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3268 goto fail;
3269 pairs[i].oldfd = -1;
3270 continue;
3271 }
3272 if (extra_fd == -1) {
3273 extra_fd = redirect_dup(pairs[i].oldfd); /* async-signal-safe */
3274 if (extra_fd == -1) {
3275 ERRMSG("dup");
3276 goto fail;
3277 }
3278 // without this, kqueue timer_th.event_fd fails with a reserved FD did not have close-on-exec
3279 // in #assert_close_on_exec because the FD_CLOEXEC is not dup'd by default
3280 if (fd_get_cloexec(pairs[i].oldfd, errmsg, errmsg_buflen)) {
3281 if (fd_set_cloexec(extra_fd, errmsg, errmsg_buflen)) {
3282 close(extra_fd);
3283 goto fail;
3284 }
3285 }
3286 rb_update_max_fd(extra_fd);
3287 }
3288 else {
3289 ret = redirect_dup2(pairs[i].oldfd, extra_fd); /* async-signal-safe */
3290 if (ret == -1) {
3291 ERRMSG("dup2");
3292 goto fail;
3293 }
3294 rb_update_max_fd(extra_fd);
3295 }
3296 pairs[i].oldfd = extra_fd;
3297 j = pairs[i].older_index;
3298 pairs[i].older_index = -1;
3299 while (j != -1) {
3300 ret = redirect_dup2(pairs[j].oldfd, pairs[j].newfd); /* async-signal-safe */
3301 if (ret == -1) {
3302 ERRMSG("dup2");
3303 goto fail;
3304 }
3305 rb_update_max_fd(ret);
3306 pairs[j].oldfd = -1;
3307 j = pairs[j].older_index;
3308 }
3309 }
3310 if (extra_fd != -1) {
3311 ret = redirect_close(extra_fd); /* async-signal-safe */
3312 if (ret == -1) {
3313 ERRMSG("close");
3314 goto fail;
3315 }
3316 }
3317
3318 return 0;
3319
3320 fail:
3321 return -1;
3322}
3323
3324/* This function should be async-signal-safe. Actually it is. */
3325static int
3326run_exec_close(VALUE ary, char *errmsg, size_t errmsg_buflen)
3327{
3328 long i;
3329 int ret;
3330
3331 for (i = 0; i < RARRAY_LEN(ary); i++) {
3332 VALUE elt = RARRAY_AREF(ary, i);
3333 int fd = FIX2INT(RARRAY_AREF(elt, 0));
3334 ret = redirect_close(fd); /* async-signal-safe */
3335 if (ret == -1) {
3336 ERRMSG("close");
3337 return -1;
3338 }
3339 }
3340 return 0;
3341}
3342
3343/* This function should be async-signal-safe when sargp is NULL. Actually it is. */
3344static int
3345run_exec_dup2_child(VALUE ary, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3346{
3347 long i;
3348 int ret;
3349
3350 for (i = 0; i < RARRAY_LEN(ary); i++) {
3351 VALUE elt = RARRAY_AREF(ary, i);
3352 int newfd = FIX2INT(RARRAY_AREF(elt, 0));
3353 int oldfd = FIX2INT(RARRAY_AREF(elt, 1));
3354
3355 if (save_redirect_fd(newfd, sargp, errmsg, errmsg_buflen) < 0) /* async-signal-safe */
3356 return -1;
3357 ret = redirect_dup2(oldfd, newfd); /* async-signal-safe */
3358 if (ret == -1) {
3359 ERRMSG("dup2");
3360 return -1;
3361 }
3362 rb_update_max_fd(newfd);
3363 }
3364 return 0;
3365}
3366
3367#ifdef HAVE_SETPGID
3368/* This function should be async-signal-safe when sargp is NULL. Actually it is. */
3369static int
3370run_exec_pgroup(const struct rb_execarg *eargp, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3371{
3372 /*
3373 * If FD_CLOEXEC is available, rb_fork_async_signal_safe waits the child's execve.
3374 * So setpgid is done in the child when rb_fork_async_signal_safe is returned in
3375 * the parent.
3376 * No race condition, even without setpgid from the parent.
3377 * (Is there an environment which has setpgid but no FD_CLOEXEC?)
3378 */
3379 int ret;
3380 rb_pid_t pgroup;
3381
3382 pgroup = eargp->pgroup_pgid;
3383 if (pgroup == -1)
3384 return 0;
3385
3386 if (sargp) {
3387 /* maybe meaningless with no fork environment... */
3388 sargp->pgroup_given = 1;
3389 sargp->pgroup_pgid = getpgrp();
3390 }
3391
3392 if (pgroup == 0) {
3393 pgroup = getpid(); /* async-signal-safe */
3394 }
3395 ret = setpgid(getpid(), pgroup); /* async-signal-safe */
3396 if (ret == -1) ERRMSG("setpgid");
3397 return ret;
3398}
3399#endif
3400
3401#if defined(HAVE_SETRLIMIT) && defined(RLIM2NUM)
3402/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3403static int
3404run_exec_rlimit(VALUE ary, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3405{
3406 long i;
3407 for (i = 0; i < RARRAY_LEN(ary); i++) {
3408 VALUE elt = RARRAY_AREF(ary, i);
3409 int rtype = NUM2INT(RARRAY_AREF(elt, 0));
3410 struct rlimit rlim;
3411 if (sargp) {
3412 VALUE tmp, newary;
3413 if (getrlimit(rtype, &rlim) == -1) {
3414 ERRMSG("getrlimit");
3415 return -1;
3416 }
3417 tmp = hide_obj(rb_ary_new3(3, RARRAY_AREF(elt, 0),
3418 RLIM2NUM(rlim.rlim_cur),
3419 RLIM2NUM(rlim.rlim_max)));
3420 if (sargp->rlimit_limits == Qfalse)
3421 newary = sargp->rlimit_limits = hide_obj(rb_ary_new());
3422 else
3423 newary = sargp->rlimit_limits;
3424 rb_ary_push(newary, tmp);
3425 }
3426 rlim.rlim_cur = NUM2RLIM(RARRAY_AREF(elt, 1));
3427 rlim.rlim_max = NUM2RLIM(RARRAY_AREF(elt, 2));
3428 if (setrlimit(rtype, &rlim) == -1) { /* hopefully async-signal-safe */
3429 ERRMSG("setrlimit");
3430 return -1;
3431 }
3432 }
3433 return 0;
3434}
3435#endif
3436
3437#if !defined(HAVE_WORKING_FORK)
3438static VALUE
3439save_env_i(RB_BLOCK_CALL_FUNC_ARGLIST(i, ary))
3440{
3441 rb_ary_push(ary, hide_obj(rb_ary_dup(argv[0])));
3442 return Qnil;
3443}
3444
3445static void
3446save_env(struct rb_execarg *sargp)
3447{
3448 if (!sargp)
3449 return;
3450 if (sargp->env_modification == Qfalse) {
3451 VALUE env = rb_envtbl();
3452 if (RTEST(env)) {
3453 VALUE ary = hide_obj(rb_ary_new());
3454 rb_block_call(env, idEach, 0, 0, save_env_i,
3455 (VALUE)ary);
3456 sargp->env_modification = ary;
3457 }
3458 sargp->unsetenv_others_given = 1;
3459 sargp->unsetenv_others_do = 1;
3460 }
3461}
3462#endif
3463
3464#ifdef _WIN32
3465#undef chdir
3466#define chdir(p) rb_w32_uchdir(p)
3467#endif
3468
3469/* This function should be async-signal-safe when sargp is NULL. Hopefully it is. */
3470int
3471rb_execarg_run_options(const struct rb_execarg *eargp, struct rb_execarg *sargp, char *errmsg, size_t errmsg_buflen)
3472{
3473 VALUE obj;
3474
3475 if (sargp) {
3476 /* assume that sargp is always NULL on fork-able environments */
3477 MEMZERO(sargp, struct rb_execarg, 1);
3478 sargp->redirect_fds = Qnil;
3479 }
3480
3481#ifdef HAVE_SETPGID
3482 if (eargp->pgroup_given) {
3483 if (run_exec_pgroup(eargp, sargp, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3484 return -1;
3485 }
3486#endif
3487
3488#if defined(HAVE_SETRLIMIT) && defined(RLIM2NUM)
3489 obj = eargp->rlimit_limits;
3490 if (obj != Qfalse) {
3491 if (run_exec_rlimit(obj, sargp, errmsg, errmsg_buflen) == -1) /* hopefully async-signal-safe */
3492 return -1;
3493 }
3494#endif
3495
3496#if !defined(HAVE_WORKING_FORK)
3497 if (eargp->unsetenv_others_given && eargp->unsetenv_others_do) {
3498 save_env(sargp);
3499 rb_env_clear();
3500 }
3501
3502 obj = eargp->env_modification;
3503 if (obj != Qfalse) {
3504 long i;
3505 save_env(sargp);
3506 for (i = 0; i < RARRAY_LEN(obj); i++) {
3507 VALUE pair = RARRAY_AREF(obj, i);
3508 VALUE key = RARRAY_AREF(pair, 0);
3509 VALUE val = RARRAY_AREF(pair, 1);
3510 if (NIL_P(val))
3511 ruby_setenv(StringValueCStr(key), 0);
3512 else
3513 ruby_setenv(StringValueCStr(key), StringValueCStr(val));
3514 }
3515 }
3516#endif
3517
3518 if (eargp->umask_given) {
3519 mode_t mask = eargp->umask_mask;
3520 mode_t oldmask = umask(mask); /* never fail */ /* async-signal-safe */
3521 if (sargp) {
3522 sargp->umask_given = 1;
3523 sargp->umask_mask = oldmask;
3524 }
3525 }
3526
3527 if (sargp && (eargp->fd_dup2 != Qfalse || eargp->fd_dup2_child != Qfalse)) {
3528 long n = 0;
3529 if (eargp->fd_dup2 != Qfalse) n += RARRAY_LEN(eargp->fd_dup2);
3530 if (eargp->fd_dup2_child != Qfalse) n += RARRAY_LEN(eargp->fd_dup2_child);
3531 rb_execarg_allocate_dup2_tmpbuf(sargp, n);
3532 }
3533
3534 obj = eargp->fd_dup2;
3535 if (obj != Qfalse) {
3536 if (run_exec_dup2(obj, eargp->dup2_tmpbuf, sargp, errmsg, errmsg_buflen) == -1) /* hopefully async-signal-safe */
3537 return -1;
3538 }
3539
3540 obj = eargp->fd_close;
3541 if (obj != Qfalse) {
3542 if (sargp)
3543 rb_warn("cannot close fd before spawn");
3544 else {
3545 if (run_exec_close(obj, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3546 return -1;
3547 }
3548 }
3549
3550#ifdef HAVE_WORKING_FORK
3551 if (eargp->close_others_do) {
3552 rb_close_before_exec(3, eargp->close_others_maxhint, eargp->redirect_fds); /* async-signal-safe */
3553 }
3554#endif
3555
3556 obj = eargp->fd_dup2_child;
3557 if (obj != Qfalse) {
3558 if (run_exec_dup2_child(obj, sargp, errmsg, errmsg_buflen) == -1) /* async-signal-safe */
3559 return -1;
3560 }
3561
3562 if (eargp->chdir_given) {
3563 if (sargp) {
3564 sargp->chdir_given = 1;
3565 sargp->chdir_dir = hide_obj(rb_dir_getwd_ospath());
3566 }
3567 if (chdir(RSTRING_PTR(eargp->chdir_dir)) == -1) { /* async-signal-safe */
3568 ERRMSG("chdir");
3569 return -1;
3570 }
3571 }
3572
3573#ifdef HAVE_SETGID
3574 if (eargp->gid_given) {
3575 if (setgid(eargp->gid) < 0) {
3576 ERRMSG("setgid");
3577 return -1;
3578 }
3579 }
3580#endif
3581#ifdef HAVE_SETUID
3582 if (eargp->uid_given) {
3583 if (setuid(eargp->uid) < 0) {
3584 ERRMSG("setuid");
3585 return -1;
3586 }
3587 }
3588#endif
3589
3590 {
3591 int preserve = errno;
3592 stdfd_clear_nonblock();
3593 errno = preserve;
3594 }
3595
3596 return 0;
3597}
3598#if !defined(HAVE_WORKING_FORK)
3599# define execarg_restore(sargp) rb_execarg_run_options((sargp), NULL, errmsg, errmsg_buflen)
3600#else
3601# define execarg_restore(sargp) (void)0
3602#endif
3603
3604/* This function should be async-signal-safe. Hopefully it is. */
3605int
3606rb_exec_async_signal_safe(const struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
3607{
3608 errno = exec_async_signal_safe(eargp, errmsg, errmsg_buflen);
3609 return -1;
3610}
3611
3612static int
3613exec_async_signal_safe(const struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
3614{
3615#if !defined(HAVE_WORKING_FORK)
3616 struct rb_execarg sarg, *const sargp = &sarg;
3617#else
3618 struct rb_execarg *const sargp = NULL;
3619#endif
3620 int err;
3621
3622 if (rb_execarg_run_options(eargp, sargp, errmsg, errmsg_buflen) < 0) { /* hopefully async-signal-safe */
3623 err = errno;
3624 execarg_restore(sargp);
3625 return err;
3626 }
3627
3628 if (eargp->use_shell) {
3629 err = proc_exec_sh(RSTRING_PTR(eargp->invoke.sh.shell_script), eargp->envp_str); /* async-signal-safe */
3630 }
3631 else {
3632 char *abspath = NULL;
3633 if (!NIL_P(eargp->invoke.cmd.command_abspath))
3634 abspath = RSTRING_PTR(eargp->invoke.cmd.command_abspath);
3635 err = proc_exec_cmd(abspath, eargp->invoke.cmd.argv_str, eargp->envp_str); /* async-signal-safe */
3636 }
3637 execarg_restore(sargp);
3638
3639 return err;
3640}
3641
3642#ifdef HAVE_WORKING_FORK
3643/* This function should be async-signal-safe. Hopefully it is. */
3644static int
3645rb_exec_atfork(void* arg, char *errmsg, size_t errmsg_buflen)
3646{
3647 return rb_exec_async_signal_safe(arg, errmsg, errmsg_buflen); /* hopefully async-signal-safe */
3648}
3649
3650static VALUE
3651proc_syswait(VALUE pid)
3652{
3653 rb_syswait((rb_pid_t)pid);
3654 return Qnil;
3655}
3656
3657static int
3658move_fds_to_avoid_crash(int *fdp, int n, VALUE fds)
3659{
3660 int min = 0;
3661 int i;
3662 for (i = 0; i < n; i++) {
3663 int ret;
3664 while (RTEST(rb_hash_lookup(fds, INT2FIX(fdp[i])))) {
3665 if (min <= fdp[i])
3666 min = fdp[i]+1;
3667 while (RTEST(rb_hash_lookup(fds, INT2FIX(min))))
3668 min++;
3669 ret = rb_cloexec_fcntl_dupfd(fdp[i], min);
3670 if (ret == -1)
3671 return -1;
3672 rb_update_max_fd(ret);
3673 close(fdp[i]);
3674 fdp[i] = ret;
3675 }
3676 }
3677 return 0;
3678}
3679
3680static int
3681pipe_nocrash(int filedes[2], VALUE fds)
3682{
3683 int ret;
3684 ret = rb_pipe(filedes);
3685 if (ret == -1)
3686 return -1;
3687 if (RTEST(fds)) {
3688 int save = errno;
3689 if (move_fds_to_avoid_crash(filedes, 2, fds) == -1) {
3690 close(filedes[0]);
3691 close(filedes[1]);
3692 return -1;
3693 }
3694 errno = save;
3695 }
3696 return ret;
3697}
3698
3699#ifndef O_BINARY
3700#define O_BINARY 0
3701#endif
3702
3703static VALUE
3704rb_thread_sleep_that_takes_VALUE_as_sole_argument(VALUE n)
3705{
3707 return Qundef;
3708}
3709
3710static int
3711handle_fork_error(int err, struct rb_process_status *status, int *ep, volatile int *try_gc_p)
3712{
3713 int state = 0;
3714
3715 switch (err) {
3716 case ENOMEM:
3717 if ((*try_gc_p)-- > 0 && !rb_during_gc()) {
3718 rb_gc();
3719 return 0;
3720 }
3721 break;
3722 case EAGAIN:
3723#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
3724 case EWOULDBLOCK:
3725#endif
3726 if (!status && !ep) {
3727 rb_thread_sleep(1);
3728 return 0;
3729 }
3730 else {
3731 rb_protect(rb_thread_sleep_that_takes_VALUE_as_sole_argument, INT2FIX(1), &state);
3732 if (status) status->status = state;
3733 if (!state) return 0;
3734 }
3735 break;
3736 }
3737 if (ep) {
3738 close(ep[0]);
3739 close(ep[1]);
3740 errno = err;
3741 }
3742 if (state && !status) rb_jump_tag(state);
3743 return -1;
3744}
3745
3746/* Flush the current Ractor's own stdio: taking the write_lock of an IO owned
3747 * by another Ractor can block on a thread that rb_check_deadlock can't see. */
3748#define prefork() ( \
3749 rb_io_flush(rb_ractor_stdout()), \
3750 rb_io_flush(rb_ractor_stderr()) \
3751 )
3752
3753/*
3754 * Forks child process, and returns the process ID in the parent
3755 * process.
3756 *
3757 * If +status+ is given, protects from any exceptions and sets the
3758 * jump status to it, and returns -1. If failed to fork new process
3759 * but no exceptions occurred, sets 0 to it. Otherwise, if forked
3760 * successfully, the value of +status+ is undetermined.
3761 *
3762 * In the child process, just returns 0 if +chfunc+ is +NULL+.
3763 * Otherwise +chfunc+ will be called with +charg+, and then the child
3764 * process exits with +EXIT_SUCCESS+ when it returned zero.
3765 *
3766 * In the case of the function is called and returns non-zero value,
3767 * the child process exits with non-+EXIT_SUCCESS+ value (normally
3768 * 127). And, on the platforms where +FD_CLOEXEC+ is available,
3769 * +errno+ is propagated to the parent process, and this function
3770 * returns -1 in the parent process. On the other platforms, just
3771 * returns pid.
3772 *
3773 * If fds is not Qnil, internal pipe for the errno propagation is
3774 * arranged to avoid conflicts of the hash keys in +fds+.
3775 *
3776 * +chfunc+ must not raise any exceptions.
3777 */
3778
3779static ssize_t
3780write_retry(int fd, const void *buf, size_t len)
3781{
3782 ssize_t w;
3783
3784 do {
3785 w = write(fd, buf, len);
3786 } while (w < 0 && errno == EINTR);
3787
3788 return w;
3789}
3790
3791static ssize_t
3792read_retry(int fd, void *buf, size_t len)
3793{
3794 ssize_t r;
3795
3796 if (set_blocking(fd) != 0) {
3797#ifndef _WIN32
3798 rb_async_bug_errno("set_blocking failed reading child error", errno);
3799#endif
3800 }
3801
3802 do {
3803 r = read(fd, buf, len);
3804 } while (r < 0 && errno == EINTR);
3805
3806 return r;
3807}
3808
3809static void
3810send_child_error(int fd, char *errmsg, size_t errmsg_buflen)
3811{
3812 int err;
3813
3814 err = errno;
3815 if (write_retry(fd, &err, sizeof(err)) < 0) err = errno;
3816 if (errmsg && 0 < errmsg_buflen) {
3817 errmsg[errmsg_buflen-1] = '\0';
3818 errmsg_buflen = strlen(errmsg);
3819 if (errmsg_buflen > 0 && write_retry(fd, errmsg, errmsg_buflen) < 0)
3820 err = errno;
3821 }
3822}
3823
3824static int
3825recv_child_error(int fd, int *errp, char *errmsg, size_t errmsg_buflen)
3826{
3827 int err;
3828 ssize_t size;
3829 if ((size = read_retry(fd, &err, sizeof(err))) < 0) {
3830 err = errno;
3831 }
3832 *errp = err;
3833 if (size == sizeof(err) &&
3834 errmsg && 0 < errmsg_buflen) {
3835 ssize_t ret = read_retry(fd, errmsg, errmsg_buflen-1);
3836 if (0 <= ret) {
3837 errmsg[ret] = '\0';
3838 }
3839 }
3840 close(fd);
3841 return size != 0;
3842}
3843
3844#ifdef HAVE_WORKING_VFORK
3845#if !defined(HAVE_GETRESUID) && defined(HAVE_GETUIDX)
3846/* AIX 7.1 */
3847static int
3848getresuid(rb_uid_t *ruid, rb_uid_t *euid, rb_uid_t *suid)
3849{
3850 rb_uid_t ret;
3851
3852 *ruid = getuid();
3853 *euid = geteuid();
3854 ret = getuidx(ID_SAVED);
3855 if (ret == (rb_uid_t)-1)
3856 return -1;
3857 *suid = ret;
3858 return 0;
3859}
3860#define HAVE_GETRESUID
3861#endif
3862
3863#if !defined(HAVE_GETRESGID) && defined(HAVE_GETGIDX)
3864/* AIX 7.1 */
3865static int
3866getresgid(rb_gid_t *rgid, rb_gid_t *egid, rb_gid_t *sgid)
3867{
3868 rb_gid_t ret;
3869
3870 *rgid = getgid();
3871 *egid = getegid();
3872 ret = getgidx(ID_SAVED);
3873 if (ret == (rb_gid_t)-1)
3874 return -1;
3875 *sgid = ret;
3876 return 0;
3877}
3878#define HAVE_GETRESGID
3879#endif
3880
3881static int
3882has_privilege(void)
3883{
3884 /*
3885 * has_privilege() is used to choose vfork() or fork().
3886 *
3887 * If the process has privilege, the parent process or
3888 * the child process can change UID/GID.
3889 * If vfork() is used to create the child process and
3890 * the parent or child process change effective UID/GID,
3891 * different privileged processes shares memory.
3892 * It is a bad situation.
3893 * So, fork() should be used.
3894 */
3895
3896 rb_uid_t ruid, euid;
3897 rb_gid_t rgid, egid;
3898
3899#if defined HAVE_ISSETUGID
3900 if (issetugid())
3901 return 1;
3902#endif
3903
3904#ifdef HAVE_GETRESUID
3905 {
3906 int ret;
3907 rb_uid_t suid;
3908 ret = getresuid(&ruid, &euid, &suid);
3909 if (ret == -1)
3910 rb_sys_fail("getresuid(2)");
3911 if (euid != suid)
3912 return 1;
3913 }
3914#else
3915 ruid = getuid();
3916 euid = geteuid();
3917#endif
3918
3919 if (euid == 0 || euid != ruid)
3920 return 1;
3921
3922#ifdef HAVE_GETRESGID
3923 {
3924 int ret;
3925 rb_gid_t sgid;
3926 ret = getresgid(&rgid, &egid, &sgid);
3927 if (ret == -1)
3928 rb_sys_fail("getresgid(2)");
3929 if (egid != sgid)
3930 return 1;
3931 }
3932#else
3933 rgid = getgid();
3934 egid = getegid();
3935#endif
3936
3937 if (egid != rgid)
3938 return 1;
3939
3940 return 0;
3941}
3942#endif
3943
3944struct child_handler_disabler_state
3945{
3946 sigset_t sigmask;
3947};
3948
3949static void
3950disable_child_handler_before_fork(struct child_handler_disabler_state *old)
3951{
3952#ifdef HAVE_PTHREAD_SIGMASK
3953 int ret;
3954 sigset_t all;
3955
3956 ret = sigfillset(&all);
3957 if (ret == -1)
3958 rb_sys_fail("sigfillset");
3959
3960 ret = pthread_sigmask(SIG_SETMASK, &all, &old->sigmask); /* not async-signal-safe */
3961 if (ret != 0) {
3962 rb_syserr_fail(ret, "pthread_sigmask");
3963 }
3964#else
3965# pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous"
3966#endif
3967}
3968
3969static void
3970disable_child_handler_fork_parent(struct child_handler_disabler_state *old)
3971{
3972#ifdef HAVE_PTHREAD_SIGMASK
3973 int ret;
3974
3975 ret = pthread_sigmask(SIG_SETMASK, &old->sigmask, NULL); /* not async-signal-safe */
3976 if (ret != 0) {
3977 rb_syserr_fail(ret, "pthread_sigmask");
3978 }
3979#else
3980# pragma GCC warning "pthread_sigmask on fork is not available. potentially dangerous"
3981#endif
3982}
3983
3984/* This function should be async-signal-safe. Actually it is. */
3985static int
3986disable_child_handler_fork_child(struct child_handler_disabler_state *old, char *errmsg, size_t errmsg_buflen)
3987{
3988 int sig;
3989 int ret;
3990
3991 for (sig = 1; sig < NSIG; sig++) {
3992 sig_t handler = signal(sig, SIG_DFL);
3993
3994 if (handler == SIG_ERR && errno == EINVAL) {
3995 continue; /* Ignore invalid signal number */
3996 }
3997 if (handler == SIG_ERR) {
3998 ERRMSG("signal to obtain old action");
3999 return -1;
4000 }
4001#ifdef SIGPIPE
4002 if (sig == SIGPIPE) {
4003 continue;
4004 }
4005#endif
4006 /* it will be reset to SIG_DFL at execve time, instead */
4007 if (handler == SIG_IGN) {
4008 signal(sig, SIG_IGN);
4009 }
4010 }
4011
4012 /* non-Ruby child process, ensure cmake can see SIGCHLD */
4013 sigemptyset(&old->sigmask);
4014 ret = sigprocmask(SIG_SETMASK, &old->sigmask, NULL); /* async-signal-safe */
4015 if (ret != 0) {
4016 ERRMSG("sigprocmask");
4017 return -1;
4018 }
4019 return 0;
4020}
4021
4022static rb_pid_t
4023retry_fork_async_signal_safe(struct rb_process_status *status, int *ep,
4024 int (*chfunc)(void*, char *, size_t), void *charg,
4025 char *errmsg, size_t errmsg_buflen,
4026 struct waitpid_state *w)
4027{
4028 rb_pid_t pid;
4029 volatile int try_gc = 1;
4030 struct child_handler_disabler_state old;
4031 int err;
4032
4033 while (1) {
4034 prefork();
4035 disable_child_handler_before_fork(&old);
4036
4037 // Older versions of ASAN does not work with vfork
4038 // See https://github.com/google/sanitizers/issues/925
4039#if defined(HAVE_WORKING_VFORK) && !defined(RUBY_ASAN_ENABLED)
4040 if (!has_privilege())
4041 pid = vfork();
4042 else
4043 pid = rb_fork();
4044#else
4045 pid = rb_fork();
4046#endif
4047 if (pid == 0) {/* fork succeed, child process */
4048 int ret;
4049 close(ep[0]);
4050 ret = disable_child_handler_fork_child(&old, errmsg, errmsg_buflen); /* async-signal-safe */
4051 if (ret == 0) {
4052 ret = chfunc(charg, errmsg, errmsg_buflen);
4053 if (!ret) _exit(EXIT_SUCCESS);
4054 }
4055 send_child_error(ep[1], errmsg, errmsg_buflen);
4056#if EXIT_SUCCESS == 127
4057 _exit(EXIT_FAILURE);
4058#else
4059 _exit(127);
4060#endif
4061 }
4062 err = errno;
4063 disable_child_handler_fork_parent(&old);
4064 if (0 < pid) /* fork succeed, parent process */
4065 return pid;
4066 /* fork failed */
4067 if (handle_fork_error(err, status, ep, &try_gc))
4068 return -1;
4069 }
4070}
4071
4072static rb_pid_t
4073fork_check_err(struct rb_process_status *status, int (*chfunc)(void*, char *, size_t), void *charg,
4074 VALUE fds, char *errmsg, size_t errmsg_buflen,
4075 struct rb_execarg *eargp)
4076{
4077 rb_pid_t pid;
4078 int err;
4079 int ep[2];
4080 int error_occurred;
4081
4082 struct waitpid_state *w = eargp && eargp->waitpid_state ? eargp->waitpid_state : 0;
4083
4084 if (status) status->status = 0;
4085
4086 if (pipe_nocrash(ep, fds)) return -1;
4087
4088 pid = retry_fork_async_signal_safe(status, ep, chfunc, charg, errmsg, errmsg_buflen, w);
4089
4090 if (status) status->pid = pid;
4091
4092 if (pid < 0) {
4093 if (status) status->error = errno;
4094
4095 return pid;
4096 }
4097
4098 close(ep[1]);
4099
4100 error_occurred = recv_child_error(ep[0], &err, errmsg, errmsg_buflen);
4101
4102 if (error_occurred) {
4103 if (status) {
4104 int state = 0;
4105 status->error = err;
4106
4107 VM_ASSERT((w == 0) && "only used by extensions");
4108 rb_protect(proc_syswait, (VALUE)pid, &state);
4109
4110 status->status = state;
4111 }
4112 else if (!w) {
4113 rb_syswait(pid);
4114 }
4115
4116 errno = err;
4117 return -1;
4118 }
4119
4120 return pid;
4121}
4122
4123/*
4124 * The "async_signal_safe" name is a lie, but it is used by pty.c and
4125 * maybe other exts. fork() is not async-signal-safe due to pthread_atfork
4126 * and future POSIX revisions will remove it from a list of signal-safe
4127 * functions. rb_waitpid is not async-signal-safe.
4128 * For our purposes, we do not need async-signal-safety, here
4129 */
4130rb_pid_t
4131rb_fork_async_signal_safe(int *status,
4132 int (*chfunc)(void*, char *, size_t), void *charg,
4133 VALUE fds, char *errmsg, size_t errmsg_buflen)
4134{
4135 struct rb_process_status process_status;
4136
4137 rb_pid_t result = fork_check_err(&process_status, chfunc, charg, fds, errmsg, errmsg_buflen, 0);
4138
4139 if (status) {
4140 *status = process_status.status;
4141 }
4142
4143 return result;
4144}
4145
4146rb_pid_t
4147rb_fork_ruby(int *status)
4148{
4149 if (UNLIKELY(!rb_ractor_main_p())) {
4150 rb_raise(rb_eRactorIsolationError, "can not fork from non-main Ractors");
4151 }
4152
4153 struct rb_process_status child = {.status = 0};
4154 rb_pid_t pid;
4155 int try_gc = 1, err = 0;
4156 struct child_handler_disabler_state old;
4157
4158 do {
4159 prefork();
4160
4161 before_fork_ruby();
4162 rb_thread_acquire_fork_lock();
4163 disable_child_handler_before_fork(&old);
4164
4165 RB_VM_LOCKING() {
4166 child.pid = pid = rb_fork();
4167 child.error = err = errno;
4168 }
4169
4170 disable_child_handler_fork_parent(&old); /* yes, bad name */
4171 release_fork_lock_after_fork(pid);
4172 after_fork_ruby(pid);
4173
4174 /* repeat while fork failed but retryable */
4175 } while (pid < 0 && handle_fork_error(err, &child, NULL, &try_gc) == 0);
4176
4177 if (status) *status = child.status;
4178
4179 return pid;
4180}
4181
4182static rb_pid_t
4183proc_fork_pid(void)
4184{
4185 rb_pid_t pid = rb_fork_ruby(NULL);
4186
4187 if (pid == -1) {
4188 rb_sys_fail("fork(2)");
4189 }
4190
4191 return pid;
4192}
4193
4194static VALUE
4195call_proc__fork_protected(VALUE arg)
4196{
4197 VALUE ret = rb_funcall(rb_mProcess, id__fork, 0);
4198 *(rb_pid_t *)arg = NUM2PIDT(ret);
4199 /* discard the returned object itself */
4200 return Qtrue;
4201}
4202
4203rb_pid_t
4204rb_call_proc__fork(void)
4205{
4206 if (rb_method_basic_definition_p(CLASS_OF(rb_mProcess), id__fork)) {
4207 return proc_fork_pid();
4208 }
4209 else {
4210 rb_pid_t parent = getpid(), pid;
4211 int state;
4212
4213 if (NIL_P(rb_protect(call_proc__fork_protected, (VALUE)&pid, &state))) {
4214 if (getpid() != parent) {
4215 ruby_stop(state);
4216 }
4217 rb_jump_tag(state);
4218 }
4219 return pid;
4220 }
4221}
4222#endif
4223
4224#if defined(HAVE_WORKING_FORK) && !defined(CANNOT_FORK_WITH_PTHREAD)
4225/*
4226 * call-seq:
4227 * Process._fork -> integer
4228 *
4229 * An internal API for fork. Do not call this method directly.
4230 * Currently, this is called via Kernel#fork, Process.fork, and
4231 * IO.popen with <tt>"-"</tt>.
4232 *
4233 * This method is not for casual code but for application monitoring
4234 * libraries. You can add custom code before and after fork events
4235 * by overriding this method.
4236 *
4237 * Note: Process.daemon may be implemented using fork(2) BUT does not go
4238 * through this method.
4239 * Thus, depending on your reason to hook into this method, you
4240 * may also want to hook into that one.
4241 * See {this issue}[https://bugs.ruby-lang.org/issues/18911] for a
4242 * more detailed discussion of this.
4243 */
4244VALUE
4245rb_proc__fork(VALUE _obj)
4246{
4247 rb_pid_t pid = proc_fork_pid();
4248 return PIDT2NUM(pid);
4249}
4250
4251/*
4252 * call-seq:
4253 * Process.fork { ... } -> integer or nil
4254 * Process.fork -> integer or nil
4255 *
4256 * Creates a child process.
4257 *
4258 * With a block given, runs the block in the child process;
4259 * on block exit, the child terminates with a status of zero:
4260 *
4261 * puts "Before the fork: #{Process.pid}"
4262 * fork do
4263 * puts "In the child process: #{Process.pid}"
4264 * end # => 382141
4265 * puts "After the fork: #{Process.pid}"
4266 *
4267 * Output:
4268 *
4269 * Before the fork: 420496
4270 * After the fork: 420496
4271 * In the child process: 420520
4272 *
4273 * With no block given, the +fork+ call returns twice:
4274 *
4275 * - Once in the parent process, returning the pid of the child process.
4276 * - Once in the child process, returning +nil+.
4277 *
4278 * Example:
4279 *
4280 * puts "This is the first line before the fork (pid #{Process.pid})"
4281 * puts fork
4282 * puts "This is the second line after the fork (pid #{Process.pid})"
4283 *
4284 * Output:
4285 *
4286 * This is the first line before the fork (pid 420199)
4287 * 420223
4288 * This is the second line after the fork (pid 420199)
4289 *
4290 * This is the second line after the fork (pid 420223)
4291 *
4292 * In either case, the child process may exit using
4293 * Kernel.exit! to avoid the call to Kernel#at_exit.
4294 *
4295 * To avoid zombie processes, the parent process should call either:
4296 *
4297 * - Process.wait, to collect the termination statuses of its children.
4298 * - Process.detach, to register disinterest in their status.
4299 *
4300 * The thread calling +fork+ is the only thread in the created child process;
4301 * +fork+ doesn't copy other threads.
4302 *
4303 * Note that method +fork+ is available on some platforms,
4304 * but not on others:
4305 *
4306 * Process.respond_to?(:fork) # => true # Would be false on some.
4307 *
4308 * If not, you may use ::spawn instead of +fork+.
4309 */
4310
4311static VALUE
4312rb_f_fork(VALUE obj)
4313{
4314 rb_pid_t pid;
4315
4316 pid = rb_call_proc__fork();
4317
4318 if (pid == 0) {
4319 if (rb_block_given_p()) {
4320 int status;
4321 rb_protect(rb_yield, Qundef, &status);
4322 ruby_stop(status);
4323 }
4324 return Qnil;
4325 }
4326
4327 return PIDT2NUM(pid);
4328}
4329#else
4330#define rb_proc__fork rb_f_notimplement
4331#define rb_f_fork rb_f_notimplement
4332#endif
4333
4334static int
4335exit_status_code(VALUE status)
4336{
4337 int istatus;
4338
4339 switch (status) {
4340 case Qtrue:
4341 istatus = EXIT_SUCCESS;
4342 break;
4343 case Qfalse:
4344 istatus = EXIT_FAILURE;
4345 break;
4346 default:
4347 istatus = NUM2INT(status);
4348#if EXIT_SUCCESS != 0
4349 if (istatus == 0)
4350 istatus = EXIT_SUCCESS;
4351#endif
4352 break;
4353 }
4354 return istatus;
4355}
4356
4357NORETURN(static VALUE rb_f_exit_bang(int argc, VALUE *argv, VALUE obj));
4358/*
4359 * call-seq:
4360 * exit!(status = false)
4361 * Process.exit!(status = false)
4362 *
4363 * Exits the process immediately; no exit handlers are called.
4364 * Returns exit status +status+ to the underlying operating system.
4365 *
4366 * Process.exit!(true)
4367 *
4368 * Values +true+ and +false+ for argument +status+
4369 * indicate, respectively, success and failure;
4370 * The meanings of integer values are system-dependent.
4371 *
4372 */
4373
4374static VALUE
4375rb_f_exit_bang(int argc, VALUE *argv, VALUE obj)
4376{
4377 int istatus;
4378
4379 if (rb_check_arity(argc, 0, 1) == 1) {
4380 istatus = exit_status_code(argv[0]);
4381 }
4382 else {
4383 istatus = EXIT_FAILURE;
4384 }
4385 _exit(istatus);
4386
4388}
4389
4390void
4391rb_exit(int status)
4392{
4393 if (GET_EC()->tag) {
4394 VALUE args[2];
4395
4396 args[0] = INT2NUM(status);
4397 args[1] = rb_str_new2("exit");
4399 }
4400 ruby_stop(status);
4401}
4402
4403VALUE
4404rb_f_exit(int argc, const VALUE *argv)
4405{
4406 int istatus;
4407
4408 if (rb_check_arity(argc, 0, 1) == 1) {
4409 istatus = exit_status_code(argv[0]);
4410 }
4411 else {
4412 istatus = EXIT_SUCCESS;
4413 }
4414 rb_exit(istatus);
4415
4417}
4418
4419NORETURN(static VALUE f_exit(int c, const VALUE *a, VALUE _));
4420/*
4421 * call-seq:
4422 * exit(status = true)
4423 * Process.exit(status = true)
4424 *
4425 * Initiates termination of the Ruby script by raising SystemExit;
4426 * the exception may be caught.
4427 * Returns exit status +status+ to the underlying operating system.
4428 *
4429 * Values +true+ and +false+ for argument +status+
4430 * indicate, respectively, success and failure;
4431 * The meanings of integer values are system-dependent.
4432 *
4433 * Example:
4434 *
4435 * begin
4436 * exit
4437 * puts 'Never get here.'
4438 * rescue SystemExit
4439 * puts 'Rescued a SystemExit exception.'
4440 * end
4441 * puts 'After begin block.'
4442 *
4443 * Output:
4444 *
4445 * Rescued a SystemExit exception.
4446 * After begin block.
4447 *
4448 * Just prior to final termination,
4449 * Ruby executes any at-exit procedures (see Kernel::at_exit)
4450 * and any object finalizers (see ObjectSpace::define_finalizer).
4451 *
4452 * Example:
4453 *
4454 * at_exit { puts 'In at_exit function.' }
4455 * ObjectSpace.define_finalizer('string', proc { puts 'In finalizer.' })
4456 * exit
4457 *
4458 * Output:
4459 *
4460 * In at_exit function.
4461 * In finalizer.
4462 *
4463 */
4464
4465static VALUE
4466f_exit(int c, const VALUE *a, VALUE _)
4467{
4468 rb_f_exit(c, a);
4470}
4471
4472VALUE
4473rb_f_abort(int argc, const VALUE *argv)
4474{
4475 rb_check_arity(argc, 0, 1);
4476 if (argc == 0) {
4477 rb_execution_context_t *ec = GET_EC();
4478 VALUE errinfo = rb_ec_get_errinfo(ec);
4479 if (!NIL_P(errinfo)) {
4480 rb_ec_error_print(ec, errinfo);
4481 }
4482 rb_exit(EXIT_FAILURE);
4483 }
4484 else {
4485 VALUE args[2];
4486
4487 args[1] = args[0] = argv[0];
4488 StringValue(args[0]);
4489 rb_io_puts(1, args, rb_ractor_stderr());
4490 args[0] = INT2NUM(EXIT_FAILURE);
4492 }
4493
4495}
4496
4497NORETURN(static VALUE f_abort(int c, const VALUE *a, VALUE _));
4498
4499/*
4500 * call-seq:
4501 * abort
4502 * Process.abort(msg = nil)
4503 *
4504 * Terminates execution immediately, effectively by calling
4505 * <tt>Kernel.exit(false)</tt>.
4506 *
4507 * If string argument +msg+ is given,
4508 * it is written to STDERR prior to termination;
4509 * otherwise, if an exception was raised,
4510 * prints its message and backtrace.
4511 */
4512
4513static VALUE
4514f_abort(int c, const VALUE *a, VALUE _)
4515{
4516 rb_f_abort(c, a);
4518}
4519
4520void
4521rb_syswait(rb_pid_t pid)
4522{
4523 int status;
4524
4525 rb_waitpid(pid, &status, 0);
4526}
4527
4528#if !defined HAVE_WORKING_FORK && !defined HAVE_SPAWNV && !defined __EMSCRIPTEN__
4529char *
4530rb_execarg_commandline(const struct rb_execarg *eargp, VALUE *prog)
4531{
4532 VALUE cmd = *prog;
4533 if (eargp && !eargp->use_shell) {
4534 VALUE str = eargp->invoke.cmd.argv_str;
4535 VALUE buf = eargp->invoke.cmd.argv_buf;
4536 char *p, **argv = ARGVSTR2ARGV(str);
4537 long i, argc = ARGVSTR2ARGC(str);
4538 const char *start = RSTRING_PTR(buf);
4539 cmd = rb_str_new(start, RSTRING_LEN(buf));
4540 p = RSTRING_PTR(cmd);
4541 for (i = 1; i < argc; ++i) {
4542 p[argv[i] - start - 1] = ' ';
4543 }
4544 *prog = cmd;
4545 return p;
4546 }
4547 return StringValueCStr(*prog);
4548}
4549#endif
4550
4551static rb_pid_t
4552rb_spawn_process(struct rb_execarg *eargp, char *errmsg, size_t errmsg_buflen)
4553{
4554 rb_pid_t pid;
4555#if !defined HAVE_WORKING_FORK || USE_SPAWNV
4556 VALUE prog;
4557 struct rb_execarg sarg;
4558# if !defined HAVE_SPAWNV
4559 int status;
4560# endif
4561#endif
4562
4563#if defined HAVE_WORKING_FORK && !USE_SPAWNV
4564 pid = fork_check_err(eargp->status, rb_exec_atfork, eargp, eargp->redirect_fds, errmsg, errmsg_buflen, eargp);
4565#else
4566 prog = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
4567
4568 if (rb_execarg_run_options(eargp, &sarg, errmsg, errmsg_buflen) < 0) {
4569 execarg_restore(&sarg);
4570 return -1;
4571 }
4572
4573 if (prog && !eargp->use_shell) {
4574 char **argv = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
4575 argv[0] = RSTRING_PTR(prog);
4576 }
4577# if defined HAVE_SPAWNV
4578 if (eargp->use_shell) {
4579 pid = proc_spawn_sh(RSTRING_PTR(prog));
4580 }
4581 else {
4582 char **argv = ARGVSTR2ARGV(eargp->invoke.cmd.argv_str);
4583 pid = proc_spawn_cmd(argv, prog, eargp);
4584 }
4585
4586 if (pid == -1) {
4587 rb_last_status_set(0x7f << 8, pid);
4588 }
4589# else
4590 status = system(rb_execarg_commandline(eargp, &prog));
4591 pid = 1; /* dummy */
4592 rb_last_status_set((status & 0xff) << 8, pid);
4593# endif
4594
4595 if (eargp->waitpid_state) {
4596 eargp->waitpid_state->pid = pid;
4597 }
4598
4599 execarg_restore(&sarg);
4600#endif
4601
4602 return pid;
4603}
4604
4606 VALUE execarg;
4607 struct {
4608 char *ptr;
4609 size_t buflen;
4610 } errmsg;
4611};
4612
4613static VALUE
4614do_spawn_process(VALUE arg)
4615{
4616 struct spawn_args *argp = (struct spawn_args *)arg;
4617
4618 rb_execarg_parent_start1(argp->execarg);
4619
4620 return (VALUE)rb_spawn_process(rb_execarg_get(argp->execarg),
4621 argp->errmsg.ptr, argp->errmsg.buflen);
4622}
4623
4624NOINLINE(static rb_pid_t
4625 rb_execarg_spawn(VALUE execarg_obj, char *errmsg, size_t errmsg_buflen));
4626
4627static rb_pid_t
4628rb_execarg_spawn(VALUE execarg_obj, char *errmsg, size_t errmsg_buflen)
4629{
4630 struct spawn_args args;
4631
4632 args.execarg = execarg_obj;
4633 args.errmsg.ptr = errmsg;
4634 args.errmsg.buflen = errmsg_buflen;
4635
4636 rb_pid_t r = (rb_pid_t)rb_ensure(do_spawn_process, (VALUE)&args,
4637 execarg_parent_end, execarg_obj);
4638 return r;
4639}
4640
4641static rb_pid_t
4642rb_spawn_internal(int argc, const VALUE *argv, char *errmsg, size_t errmsg_buflen)
4643{
4644 VALUE execarg_obj;
4645
4646 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
4647 return rb_execarg_spawn(execarg_obj, errmsg, errmsg_buflen);
4648}
4649
4650rb_pid_t
4651rb_spawn_err(int argc, const VALUE *argv, char *errmsg, size_t errmsg_buflen)
4652{
4653 return rb_spawn_internal(argc, argv, errmsg, errmsg_buflen);
4654}
4655
4656rb_pid_t
4657rb_spawn(int argc, const VALUE *argv)
4658{
4659 return rb_spawn_internal(argc, argv, NULL, 0);
4660}
4661
4662/*
4663 * call-seq:
4664 * system([env, ] command_line, options = {}, exception: false) -> true, false, or nil
4665 * system([env, ] exe_path, *args, options = {}, exception: false) -> true, false, or nil
4666 *
4667 * Creates a new child process by doing one of the following
4668 * in that process:
4669 *
4670 * - Passing string +command_line+ to the shell.
4671 * - Invoking the executable at +exe_path+.
4672 *
4673 * This method has potential security vulnerabilities if called with untrusted input;
4674 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
4675 *
4676 * Returns:
4677 *
4678 * - +true+ if the command exits with status zero.
4679 * - +false+ if the exit status is a non-zero integer.
4680 * - +nil+ if the command could not execute.
4681 *
4682 * Raises an exception (instead of returning +false+ or +nil+)
4683 * if keyword argument +exception+ is set to +true+.
4684 *
4685 * Assigns the command's error status to <tt>$?</tt>.
4686 *
4687 * The new process is created using the
4688 * {system system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/system.html];
4689 * it may inherit some of its environment from the calling program
4690 * (possibly including open file descriptors).
4691 *
4692 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
4693 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
4694 *
4695 * Argument +options+ is a hash of options for the new process;
4696 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
4697 *
4698 * The first required argument is one of the following:
4699 *
4700 * - +command_line+ if it is a string,
4701 * and if it begins with a shell reserved word or special built-in,
4702 * or if it contains one or more meta characters.
4703 * - +exe_path+ otherwise.
4704 *
4705 * <b>Argument +command_line+</b>
4706 *
4707 * \String argument +command_line+ is a command line to be passed to a shell;
4708 * it must begin with a shell reserved word, begin with a special built-in,
4709 * or contain meta characters:
4710 *
4711 * system('if true; then echo "Foo"; fi') # => true # Shell reserved word.
4712 * system('exit') # => true # Built-in.
4713 * system('date > /tmp/date.tmp') # => true # Contains meta character.
4714 * system('date > /nop/date.tmp') # => false
4715 * system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
4716 *
4717 * Assigns the command's error status to <tt>$?</tt>:
4718 *
4719 * system('exit') # => true # Built-in.
4720 * $? # => #<Process::Status: pid 640610 exit 0>
4721 * system('date > /nop/date.tmp') # => false
4722 * $? # => #<Process::Status: pid 640742 exit 2>
4723 *
4724 * The command line may also contain arguments and options for the command:
4725 *
4726 * system('echo "Foo"') # => true
4727 *
4728 * Output:
4729 *
4730 * Foo
4731 *
4732 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
4733 *
4734 * Raises an exception if the new process could not execute.
4735 *
4736 * <b>Argument +exe_path+</b>
4737 *
4738 * Argument +exe_path+ is one of the following:
4739 *
4740 * - The string path to an executable to be called.
4741 * - A 2-element array containing the path to an executable
4742 * and the string to be used as the name of the executing process.
4743 *
4744 * Example:
4745 *
4746 * system('/usr/bin/date') # => true # Path to date on Unix-style system.
4747 * system('foo') # => nil # Command failed.
4748 *
4749 * Output:
4750 *
4751 * Mon Aug 28 11:43:10 AM CDT 2023
4752 *
4753 * Assigns the command's error status to <tt>$?</tt>:
4754 *
4755 * system('/usr/bin/date') # => true
4756 * $? # => #<Process::Status: pid 645605 exit 0>
4757 * system('foo') # => nil
4758 * $? # => #<Process::Status: pid 645608 exit 127>
4759 *
4760 * Ruby invokes the executable directly.
4761 * This form does not use the shell;
4762 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
4763 *
4764 * system('doesnt_exist') # => nil
4765 *
4766 * If one or more +args+ is given, each is an argument or option
4767 * to be passed to the executable:
4768 *
4769 * system('echo', 'C*') # => true
4770 * system('echo', 'hello', 'world') # => true
4771 *
4772 * Output:
4773 *
4774 * C*
4775 * hello world
4776 *
4777 * Raises an exception if the new process could not execute.
4778 */
4779
4780static VALUE
4781rb_f_system(int argc, VALUE *argv, VALUE _)
4782{
4783 rb_thread_t *th = GET_THREAD();
4784 VALUE execarg_obj = rb_execarg_new(argc, argv, TRUE, TRUE);
4785 struct rb_execarg *eargp = rb_execarg_get(execarg_obj);
4786
4787 struct rb_process_status status = {0};
4788 eargp->status = &status;
4789
4790 last_status_clear(th);
4791
4792 // This function can set the thread's last status.
4793 // May be different from waitpid_state.pid on exec failure.
4794 rb_pid_t pid = rb_execarg_spawn(execarg_obj, 0, 0);
4795
4796 if (pid > 0) {
4797 VALUE status = rb_process_status_wait(pid, 0);
4798 struct rb_process_status *data = rb_check_typeddata(status, &rb_process_status_type);
4799 // Set the last status:
4800 rb_obj_freeze(status);
4801 th->last_status = status;
4802
4803 if (data->status == EXIT_SUCCESS) {
4804 return Qtrue;
4805 }
4806
4807 if (data->error != 0) {
4808 if (eargp->exception) {
4809 VALUE command = eargp->invoke.sh.shell_script;
4810 RB_GC_GUARD(execarg_obj);
4811 rb_syserr_fail_str(data->error, command);
4812 }
4813 else {
4814 return Qnil;
4815 }
4816 }
4817 else if (eargp->exception) {
4818 VALUE command = eargp->invoke.sh.shell_script;
4819 VALUE str = rb_str_new_cstr("Command failed with");
4820 rb_str_cat_cstr(pst_message_status(str, data->status), ": ");
4821 rb_str_append(str, command);
4822 RB_GC_GUARD(execarg_obj);
4824 }
4825 else {
4826 return Qfalse;
4827 }
4828
4829 RB_GC_GUARD(status);
4830 }
4831
4832 if (eargp->exception) {
4833 VALUE command = eargp->invoke.sh.shell_script;
4834 RB_GC_GUARD(execarg_obj);
4835 rb_syserr_fail_str(errno, command);
4836 }
4837 else {
4838 return Qnil;
4839 }
4840}
4841
4842/*
4843 * call-seq:
4844 * spawn([env, ] command_line, options = {}) -> pid
4845 * spawn([env, ] exe_path, *args, options = {}) -> pid
4846 *
4847 * Creates a new child process by doing one of the following
4848 * in that process:
4849 *
4850 * - Passing string +command_line+ to the shell.
4851 * - Invoking the executable at +exe_path+.
4852 *
4853 * This method has potential security vulnerabilities if called with untrusted input;
4854 * see {Command Injection}[rdoc-ref:security/command_injection.rdoc].
4855 *
4856 * Returns the process ID (pid) of the new process,
4857 * without waiting for it to complete.
4858 *
4859 * To avoid zombie processes, the parent process should call either:
4860 *
4861 * - Process.wait, to collect the termination statuses of its children.
4862 * - Process.detach, to register disinterest in their status.
4863 *
4864 * The new process is created using the
4865 * {exec system call}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/functions/execve.html];
4866 * it may inherit some of its environment from the calling program
4867 * (possibly including open file descriptors).
4868 *
4869 * Argument +env+, if given, is a hash that affects +ENV+ for the new process;
4870 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
4871 *
4872 * Argument +options+ is a hash of options for the new process;
4873 * see {Execution Options}[rdoc-ref:Process@Execution+Options].
4874 *
4875 * The first required argument is one of the following:
4876 *
4877 * - +command_line+ if it is a string,
4878 * and if it begins with a shell reserved word or special built-in,
4879 * or if it contains one or more meta characters.
4880 * - +exe_path+ otherwise.
4881 *
4882 * <b>Argument +command_line+</b>
4883 *
4884 * \String argument +command_line+ is a command line to be passed to a shell;
4885 * it must begin with a shell reserved word, begin with a special built-in,
4886 * or contain meta characters:
4887 *
4888 * spawn('if true; then echo "Foo"; fi') # => 798847 # Shell reserved word.
4889 * Process.wait # => 798847
4890 * spawn('exit') # => 798848 # Built-in.
4891 * Process.wait # => 798848
4892 * spawn('date > /tmp/date.tmp') # => 798879 # Contains meta character.
4893 * Process.wait # => 798849
4894 * spawn('date > /nop/date.tmp') # => 798882 # Issues error message.
4895 * Process.wait # => 798882
4896 *
4897 * The command line may also contain arguments and options for the command:
4898 *
4899 * spawn('echo "Foo"') # => 799031
4900 * Process.wait # => 799031
4901 *
4902 * Output:
4903 *
4904 * Foo
4905 *
4906 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
4907 *
4908 * Raises an exception if the new process could not execute.
4909 *
4910 * <b>Argument +exe_path+</b>
4911 *
4912 * Argument +exe_path+ is one of the following:
4913 *
4914 * - The string path to an executable to be called.
4915 * - A 2-element array containing the path to an executable to be called,
4916 * and the string to be used as the name of the executing process.
4917 *
4918 * spawn('/usr/bin/date') # Path to date on Unix-style system.
4919 * Process.wait
4920 *
4921 * Output:
4922 *
4923 * Mon Aug 28 11:43:10 AM CDT 2023
4924 *
4925 * Ruby invokes the executable directly.
4926 * This form does not use the shell;
4927 * see {Arguments args}[rdoc-ref:Process@Arguments+args] for caveats.
4928 *
4929 * If one or more +args+ is given, each is an argument or option
4930 * to be passed to the executable:
4931 *
4932 * spawn('echo', 'C*') # => 799392
4933 * Process.wait # => 799392
4934 * spawn('echo', 'hello', 'world') # => 799393
4935 * Process.wait # => 799393
4936 *
4937 * Output:
4938 *
4939 * C*
4940 * hello world
4941 *
4942 * Raises an exception if the new process could not execute.
4943 */
4944
4945static VALUE
4946rb_f_spawn(int argc, VALUE *argv, VALUE _)
4947{
4948 rb_pid_t pid;
4949 char errmsg[CHILD_ERRMSG_BUFLEN] = { '\0' };
4950 VALUE execarg_obj, fail_str;
4951 struct rb_execarg *eargp;
4952
4953 execarg_obj = rb_execarg_new(argc, argv, TRUE, FALSE);
4954 eargp = rb_execarg_get(execarg_obj);
4955 fail_str = eargp->use_shell ? eargp->invoke.sh.shell_script : eargp->invoke.cmd.command_name;
4956
4957 pid = rb_execarg_spawn(execarg_obj, errmsg, sizeof(errmsg));
4958
4959 if (pid == -1) {
4960 int err = errno;
4961 rb_exec_fail(eargp, err, errmsg);
4962 RB_GC_GUARD(execarg_obj);
4963 rb_syserr_fail_str(err, fail_str);
4964 }
4965#if defined(HAVE_WORKING_FORK) || defined(HAVE_SPAWNV)
4966 return PIDT2NUM(pid);
4967#else
4968 return Qnil;
4969#endif
4970}
4971
4972/*
4973 * call-seq:
4974 * sleep(secs = nil) -> slept_secs
4975 *
4976 * Suspends execution of the current thread for the number of seconds
4977 * specified by numeric argument +secs+, or forever if +secs+ is +nil+;
4978 * returns the integer number of seconds suspended (rounded).
4979 *
4980 * Time.new # => 2008-03-08 19:56:19 +0900
4981 * sleep 1.2 # => 1
4982 * Time.new # => 2008-03-08 19:56:20 +0900
4983 * sleep 1.9 # => 2
4984 * Time.new # => 2008-03-08 19:56:22 +0900
4985 *
4986 */
4987
4988static VALUE
4989rb_f_sleep(int argc, VALUE *argv, VALUE _)
4990{
4991 time_t beg = time(0);
4992 VALUE scheduler = rb_fiber_scheduler_current();
4993
4994 if (scheduler != Qnil) {
4995 rb_fiber_scheduler_kernel_sleepv(scheduler, argc, argv);
4996 }
4997 else {
4998 if (argc == 0 || (argc == 1 && NIL_P(argv[0]))) {
5000 }
5001 else {
5002 rb_check_arity(argc, 0, 1);
5004 }
5005 }
5006
5007 time_t end = time(0) - beg;
5008
5009 return TIMET2NUM(end);
5010}
5011
5012
5013#if (defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)) || defined(HAVE_GETPGID)
5014/*
5015 * call-seq:
5016 * Process.getpgrp -> integer
5017 *
5018 * Returns the process group ID for the current process:
5019 *
5020 * Process.getpgid(0) # => 25527
5021 * Process.getpgrp # => 25527
5022 *
5023 */
5024
5025static VALUE
5026proc_getpgrp(VALUE _)
5027{
5028 rb_pid_t pgrp;
5029
5030#if defined(HAVE_GETPGRP) && defined(GETPGRP_VOID)
5031 pgrp = getpgrp();
5032 if (pgrp < 0) rb_sys_fail(0);
5033 return PIDT2NUM(pgrp);
5034#else /* defined(HAVE_GETPGID) */
5035 pgrp = getpgid(0);
5036 if (pgrp < 0) rb_sys_fail(0);
5037 return PIDT2NUM(pgrp);
5038#endif
5039}
5040#else
5041#define proc_getpgrp rb_f_notimplement
5042#endif
5043
5044
5045#if defined(HAVE_SETPGID) || (defined(HAVE_SETPGRP) && defined(SETPGRP_VOID))
5046/*
5047 * call-seq:
5048 * Process.setpgrp -> 0
5049 *
5050 * Equivalent to <tt>setpgid(0, 0)</tt>.
5051 *
5052 * Not available on all platforms.
5053 */
5054
5055static VALUE
5056proc_setpgrp(VALUE _)
5057{
5058 /* check for posix setpgid() first; this matches the posix */
5059 /* getpgrp() above. It appears that configure will set SETPGRP_VOID */
5060 /* even though setpgrp(0,0) would be preferred. The posix call avoids */
5061 /* this confusion. */
5062#ifdef HAVE_SETPGID
5063 if (setpgid(0,0) < 0) rb_sys_fail(0);
5064#elif defined(HAVE_SETPGRP) && defined(SETPGRP_VOID)
5065 if (setpgrp() < 0) rb_sys_fail(0);
5066#endif
5067 return INT2FIX(0);
5068}
5069#else
5070#define proc_setpgrp rb_f_notimplement
5071#endif
5072
5073
5074#if defined(HAVE_GETPGID)
5075/*
5076 * call-seq:
5077 * Process.getpgid(pid) -> integer
5078 *
5079 * Returns the process group ID for the given process ID +pid+:
5080 *
5081 * Process.getpgid(Process.ppid) # => 25527
5082 *
5083 * Not available on all platforms.
5084 */
5085
5086static VALUE
5087proc_getpgid(VALUE obj, VALUE pid)
5088{
5089 rb_pid_t i;
5090
5091 i = getpgid(NUM2PIDT(pid));
5092 if (i < 0) rb_sys_fail(0);
5093 return PIDT2NUM(i);
5094}
5095#else
5096#define proc_getpgid rb_f_notimplement
5097#endif
5098
5099
5100#ifdef HAVE_SETPGID
5101/*
5102 * call-seq:
5103 * Process.setpgid(pid, pgid) -> 0
5104 *
5105 * Sets the process group ID for the process given by process ID +pid+
5106 * to +pgid+.
5107 *
5108 * Not available on all platforms.
5109 */
5110
5111static VALUE
5112proc_setpgid(VALUE obj, VALUE pid, VALUE pgrp)
5113{
5114 rb_pid_t ipid, ipgrp;
5115
5116 ipid = NUM2PIDT(pid);
5117 ipgrp = NUM2PIDT(pgrp);
5118
5119 if (setpgid(ipid, ipgrp) < 0) rb_sys_fail(0);
5120 return INT2FIX(0);
5121}
5122#else
5123#define proc_setpgid rb_f_notimplement
5124#endif
5125
5126
5127#ifdef HAVE_GETSID
5128/*
5129 * call-seq:
5130 * Process.getsid(pid = nil) -> integer
5131 *
5132 * Returns the session ID of the given process ID +pid+,
5133 * or of the current process if not given:
5134 *
5135 * Process.getsid # => 27422
5136 * Process.getsid(0) # => 27422
5137 * Process.getsid(Process.pid()) # => 27422
5138 *
5139 * Not available on all platforms.
5140 */
5141static VALUE
5142proc_getsid(int argc, VALUE *argv, VALUE _)
5143{
5144 rb_pid_t sid;
5145 rb_pid_t pid = 0;
5146
5147 if (rb_check_arity(argc, 0, 1) == 1 && !NIL_P(argv[0]))
5148 pid = NUM2PIDT(argv[0]);
5149
5150 sid = getsid(pid);
5151 if (sid < 0) rb_sys_fail(0);
5152 return PIDT2NUM(sid);
5153}
5154#else
5155#define proc_getsid rb_f_notimplement
5156#endif
5157
5158
5159#if defined(HAVE_SETSID) || (defined(HAVE_SETPGRP) && defined(TIOCNOTTY))
5160#if !defined(HAVE_SETSID)
5161static rb_pid_t ruby_setsid(void);
5162#define setsid() ruby_setsid()
5163#endif
5164/*
5165 * call-seq:
5166 * Process.setsid -> integer
5167 *
5168 * Establishes the current process as a new session and process group leader,
5169 * with no controlling tty;
5170 * returns the session ID:
5171 *
5172 * Process.setsid # => 27422
5173 *
5174 * Not available on all platforms.
5175 */
5176
5177static VALUE
5178proc_setsid(VALUE _)
5179{
5180 rb_pid_t pid;
5181
5182 pid = setsid();
5183 if (pid < 0) rb_sys_fail(0);
5184 return PIDT2NUM(pid);
5185}
5186
5187#if !defined(HAVE_SETSID)
5188#define HAVE_SETSID 1
5189static rb_pid_t
5190ruby_setsid(void)
5191{
5192 rb_pid_t pid;
5193 int ret, fd;
5194
5195 pid = getpid();
5196#if defined(SETPGRP_VOID)
5197 ret = setpgrp();
5198 /* If `pid_t setpgrp(void)' is equivalent to setsid(),
5199 `ret' will be the same value as `pid', and following open() will fail.
5200 In Linux, `int setpgrp(void)' is equivalent to setpgid(0, 0). */
5201#else
5202 ret = setpgrp(0, pid);
5203#endif
5204 if (ret == -1) return -1;
5205
5206 if ((fd = rb_cloexec_open("/dev/tty", O_RDWR, 0)) >= 0) {
5207 rb_update_max_fd(fd);
5208 ioctl(fd, TIOCNOTTY, NULL);
5209 close(fd);
5210 }
5211 return pid;
5212}
5213#endif
5214#else
5215#define proc_setsid rb_f_notimplement
5216#endif
5217
5218
5219#ifdef HAVE_GETPRIORITY
5220/*
5221 * call-seq:
5222 * Process.getpriority(kind, id) -> integer
5223 *
5224 * Returns the scheduling priority for specified process, process group,
5225 * or user.
5226 *
5227 * Argument +kind+ is one of:
5228 *
5229 * - Process::PRIO_PROCESS: return priority for process.
5230 * - Process::PRIO_PGRP: return priority for process group.
5231 * - Process::PRIO_USER: return priority for user.
5232 *
5233 * Argument +id+ is the ID for the process, process group, or user;
5234 * zero specified the current ID for +kind+.
5235 *
5236 * Examples:
5237 *
5238 * Process.getpriority(Process::PRIO_USER, 0) # => 19
5239 * Process.getpriority(Process::PRIO_PROCESS, 0) # => 19
5240 *
5241 * Not available on all platforms.
5242 */
5243
5244static VALUE
5245proc_getpriority(VALUE obj, VALUE which, VALUE who)
5246{
5247 int prio, iwhich, iwho;
5248
5249 iwhich = NUM2INT(which);
5250 iwho = NUM2INT(who);
5251
5252 errno = 0;
5253 prio = getpriority(iwhich, iwho);
5254 if (errno) rb_sys_fail(0);
5255 return INT2FIX(prio);
5256}
5257#else
5258#define proc_getpriority rb_f_notimplement
5259#endif
5260
5261
5262#ifdef HAVE_GETPRIORITY
5263/*
5264 * call-seq:
5265 * Process.setpriority(kind, integer, priority) -> 0
5266 *
5267 * See Process.getpriority.
5268 *
5269 * Examples:
5270 *
5271 * Process.setpriority(Process::PRIO_USER, 0, 19) # => 0
5272 * Process.setpriority(Process::PRIO_PROCESS, 0, 19) # => 0
5273 * Process.getpriority(Process::PRIO_USER, 0) # => 19
5274 * Process.getpriority(Process::PRIO_PROCESS, 0) # => 19
5275 *
5276 * Not available on all platforms.
5277 */
5278
5279static VALUE
5280proc_setpriority(VALUE obj, VALUE which, VALUE who, VALUE prio)
5281{
5282 int iwhich, iwho, iprio;
5283
5284 iwhich = NUM2INT(which);
5285 iwho = NUM2INT(who);
5286 iprio = NUM2INT(prio);
5287
5288 if (setpriority(iwhich, iwho, iprio) < 0)
5289 rb_sys_fail(0);
5290 return INT2FIX(0);
5291}
5292#else
5293#define proc_setpriority rb_f_notimplement
5294#endif
5295
5296#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
5297static int
5298rlimit_resource_name2int(const char *name, long len, int casetype)
5299{
5300 int resource;
5301 const char *p;
5302#define RESCHECK(r) \
5303 do { \
5304 if (len == rb_strlen_lit(#r) && STRCASECMP(name, #r) == 0) { \
5305 resource = RLIMIT_##r; \
5306 goto found; \
5307 } \
5308 } while (0)
5309
5310 switch (TOUPPER(*name)) {
5311 case 'A':
5312#ifdef RLIMIT_AS
5313 RESCHECK(AS);
5314#endif
5315 break;
5316
5317 case 'C':
5318#ifdef RLIMIT_CORE
5319 RESCHECK(CORE);
5320#endif
5321#ifdef RLIMIT_CPU
5322 RESCHECK(CPU);
5323#endif
5324 break;
5325
5326 case 'D':
5327#ifdef RLIMIT_DATA
5328 RESCHECK(DATA);
5329#endif
5330 break;
5331
5332 case 'F':
5333#ifdef RLIMIT_FSIZE
5334 RESCHECK(FSIZE);
5335#endif
5336 break;
5337
5338 case 'M':
5339#ifdef RLIMIT_MEMLOCK
5340 RESCHECK(MEMLOCK);
5341#endif
5342#ifdef RLIMIT_MSGQUEUE
5343 RESCHECK(MSGQUEUE);
5344#endif
5345 break;
5346
5347 case 'N':
5348#ifdef RLIMIT_NOFILE
5349 RESCHECK(NOFILE);
5350#endif
5351#ifdef RLIMIT_NPROC
5352 RESCHECK(NPROC);
5353#endif
5354#ifdef RLIMIT_NPTS
5355 RESCHECK(NPTS);
5356#endif
5357#ifdef RLIMIT_NICE
5358 RESCHECK(NICE);
5359#endif
5360 break;
5361
5362 case 'R':
5363#ifdef RLIMIT_RSS
5364 RESCHECK(RSS);
5365#endif
5366#ifdef RLIMIT_RTPRIO
5367 RESCHECK(RTPRIO);
5368#endif
5369#ifdef RLIMIT_RTTIME
5370 RESCHECK(RTTIME);
5371#endif
5372 break;
5373
5374 case 'S':
5375#ifdef RLIMIT_STACK
5376 RESCHECK(STACK);
5377#endif
5378#ifdef RLIMIT_SBSIZE
5379 RESCHECK(SBSIZE);
5380#endif
5381#ifdef RLIMIT_SIGPENDING
5382 RESCHECK(SIGPENDING);
5383#endif
5384 break;
5385 }
5386 return -1;
5387
5388 found:
5389 switch (casetype) {
5390 case 0:
5391 for (p = name; *p; p++)
5392 if (!ISUPPER(*p))
5393 return -1;
5394 break;
5395
5396 case 1:
5397 for (p = name; *p; p++)
5398 if (!ISLOWER(*p))
5399 return -1;
5400 break;
5401
5402 default:
5403 rb_bug("unexpected casetype");
5404 }
5405 return resource;
5406#undef RESCHECK
5407}
5408
5409static int
5410rlimit_type_by_hname(const char *name, long len)
5411{
5412 return rlimit_resource_name2int(name, len, 0);
5413}
5414
5415static int
5416rlimit_type_by_lname(const char *name, long len)
5417{
5418 return rlimit_resource_name2int(name, len, 1);
5419}
5420
5421static int
5422rlimit_type_by_sym(VALUE key)
5423{
5424 VALUE name = rb_sym2str(key);
5425 const char *rname = RSTRING_PTR(name);
5426 long len = RSTRING_LEN(name);
5427 int rtype = -1;
5428 static const char prefix[] = "rlimit_";
5429 enum {prefix_len = sizeof(prefix)-1};
5430
5431 if (len > prefix_len && strncmp(prefix, rname, prefix_len) == 0) {
5432 rtype = rlimit_type_by_lname(rname + prefix_len, len - prefix_len);
5433 }
5434
5435 RB_GC_GUARD(key);
5436 return rtype;
5437}
5438
5439static int
5440rlimit_resource_type(VALUE rtype)
5441{
5442 const char *name;
5443 long len;
5444 VALUE v;
5445 int r;
5446
5447 switch (TYPE(rtype)) {
5448 case T_SYMBOL:
5449 v = rb_sym2str(rtype);
5450 name = RSTRING_PTR(v);
5451 len = RSTRING_LEN(v);
5452 break;
5453
5454 default:
5455 v = rb_check_string_type(rtype);
5456 if (!NIL_P(v)) {
5457 rtype = v;
5458 case T_STRING:
5459 name = StringValueCStr(rtype);
5460 len = RSTRING_LEN(rtype);
5461 break;
5462 }
5463 /* fall through */
5464
5465 case T_FIXNUM:
5466 case T_BIGNUM:
5467 return NUM2INT(rtype);
5468 }
5469
5470 r = rlimit_type_by_hname(name, len);
5471 if (r != -1)
5472 return r;
5473
5474 rb_raise(rb_eArgError, "invalid resource name: % "PRIsVALUE, rtype);
5475
5477}
5478
5479static rlim_t
5480rlimit_resource_value(VALUE rval)
5481{
5482 const char *name;
5483 VALUE v;
5484
5485 switch (TYPE(rval)) {
5486 case T_SYMBOL:
5487 v = rb_sym2str(rval);
5488 name = RSTRING_PTR(v);
5489 break;
5490
5491 default:
5492 v = rb_check_string_type(rval);
5493 if (!NIL_P(v)) {
5494 rval = v;
5495 case T_STRING:
5496 name = StringValueCStr(rval);
5497 break;
5498 }
5499 /* fall through */
5500
5501 case T_FIXNUM:
5502 case T_BIGNUM:
5503 return NUM2RLIM(rval);
5504 }
5505
5506#ifdef RLIM_INFINITY
5507 if (strcmp(name, "INFINITY") == 0) return RLIM_INFINITY;
5508#endif
5509#ifdef RLIM_SAVED_MAX
5510 if (strcmp(name, "SAVED_MAX") == 0) return RLIM_SAVED_MAX;
5511#endif
5512#ifdef RLIM_SAVED_CUR
5513 if (strcmp(name, "SAVED_CUR") == 0) return RLIM_SAVED_CUR;
5514#endif
5515 rb_raise(rb_eArgError, "invalid resource value: %"PRIsVALUE, rval);
5516
5517 UNREACHABLE_RETURN((rlim_t)-1);
5518}
5519#endif
5520
5521#if defined(HAVE_GETRLIMIT) && defined(RLIM2NUM)
5522/*
5523 * call-seq:
5524 * Process.getrlimit(resource) -> [cur_limit, max_limit]
5525 *
5526 * Returns a 2-element array of the current (soft) limit
5527 * and maximum (hard) limit for the given +resource+.
5528 *
5529 * Argument +resource+ specifies the resource whose limits are to be returned;
5530 * see Process.setrlimit.
5531 *
5532 * Each of the returned values +cur_limit+ and +max_limit+ is an integer;
5533 * see Process.setrlimit.
5534 *
5535 * Example:
5536 *
5537 * Process.getrlimit(:CORE) # => [0, 18446744073709551615]
5538 *
5539 * See Process.setrlimit.
5540 *
5541 * Not available on all platforms.
5542 */
5543
5544static VALUE
5545proc_getrlimit(VALUE obj, VALUE resource)
5546{
5547 struct rlimit rlim;
5548
5549 if (getrlimit(rlimit_resource_type(resource), &rlim) < 0) {
5550 rb_sys_fail("getrlimit");
5551 }
5552 return rb_assoc_new(RLIM2NUM(rlim.rlim_cur), RLIM2NUM(rlim.rlim_max));
5553}
5554#else
5555#define proc_getrlimit rb_f_notimplement
5556#endif
5557
5558#if defined(HAVE_SETRLIMIT) && defined(NUM2RLIM)
5559/*
5560 * call-seq:
5561 * Process.setrlimit(resource, cur_limit, max_limit = cur_limit) -> nil
5562 *
5563 * Sets limits for the current process for the given +resource+
5564 * to +cur_limit+ (soft limit) and +max_limit+ (hard limit);
5565 * returns +nil+.
5566 *
5567 * Argument +resource+ specifies the resource whose limits are to be set;
5568 * the argument may be given as a symbol, as a string, or as a constant
5569 * beginning with <tt>Process::RLIMIT_</tt>
5570 * (e.g., +:CORE+, <tt>'CORE'</tt>, or <tt>Process::RLIMIT_CORE</tt>.
5571 *
5572 * The resources available and supported are system-dependent,
5573 * and may include (here expressed as symbols):
5574 *
5575 * - +:AS+: Total available memory (bytes) (SUSv3, NetBSD, FreeBSD, OpenBSD except 4.4BSD-Lite).
5576 * - +:CORE+: Core size (bytes) (SUSv3).
5577 * - +:CPU+: CPU time (seconds) (SUSv3).
5578 * - +:DATA+: Data segment (bytes) (SUSv3).
5579 * - +:FSIZE+: File size (bytes) (SUSv3).
5580 * - +:MEMLOCK+: Total size for mlock(2) (bytes) (4.4BSD, GNU/Linux).
5581 * - +:MSGQUEUE+: Allocation for POSIX message queues (bytes) (GNU/Linux).
5582 * - +:NICE+: Ceiling on process's nice(2) value (number) (GNU/Linux).
5583 * - +:NOFILE+: File descriptors (number) (SUSv3).
5584 * - +:NPROC+: Number of processes for the user (number) (4.4BSD, GNU/Linux).
5585 * - +:NPTS+: Number of pseudo terminals (number) (FreeBSD).
5586 * - +:RSS+: Resident memory size (bytes) (4.2BSD, GNU/Linux).
5587 * - +:RTPRIO+: Ceiling on the process's real-time priority (number) (GNU/Linux).
5588 * - +:RTTIME+: CPU time for real-time process (us) (GNU/Linux).
5589 * - +:SBSIZE+: All socket buffers (bytes) (NetBSD, FreeBSD).
5590 * - +:SIGPENDING+: Number of queued signals allowed (signals) (GNU/Linux).
5591 * - +:STACK+: Stack size (bytes) (SUSv3).
5592 *
5593 * Arguments +cur_limit+ and +max_limit+ may be:
5594 *
5595 * - Integers (+max_limit+ should not be smaller than +cur_limit+).
5596 * - Symbol +:SAVED_MAX+, string <tt>'SAVED_MAX'</tt>,
5597 * or constant <tt>Process::RLIM_SAVED_MAX</tt>: saved maximum limit.
5598 * - Symbol +:SAVED_CUR+, string <tt>'SAVED_CUR'</tt>,
5599 * or constant <tt>Process::RLIM_SAVED_CUR</tt>: saved current limit.
5600 * - Symbol +:INFINITY+, string <tt>'INFINITY'</tt>,
5601 * or constant <tt>Process::RLIM_INFINITY</tt>: no limit on resource.
5602 *
5603 * This example raises the soft limit of core size to
5604 * the hard limit to try to make core dump possible:
5605 *
5606 * Process.setrlimit(:CORE, Process.getrlimit(:CORE)[1])
5607 *
5608 * Not available on all platforms.
5609 */
5610
5611static VALUE
5612proc_setrlimit(int argc, VALUE *argv, VALUE obj)
5613{
5614 VALUE resource, rlim_cur, rlim_max;
5615 struct rlimit rlim;
5616
5617 rb_check_arity(argc, 2, 3);
5618 resource = argv[0];
5619 rlim_cur = argv[1];
5620 if (argc < 3 || NIL_P(rlim_max = argv[2]))
5621 rlim_max = rlim_cur;
5622
5623 rlim.rlim_cur = rlimit_resource_value(rlim_cur);
5624 rlim.rlim_max = rlimit_resource_value(rlim_max);
5625
5626 if (setrlimit(rlimit_resource_type(resource), &rlim) < 0) {
5627 rb_sys_fail("setrlimit");
5628 }
5629 return Qnil;
5630}
5631#else
5632#define proc_setrlimit rb_f_notimplement
5633#endif
5634
5635static int under_uid_switch = 0;
5636static void
5637check_uid_switch(void)
5638{
5639 if (under_uid_switch) {
5640 rb_raise(rb_eRuntimeError, "can't handle UID while evaluating block given to Process::UID.switch method");
5641 }
5642}
5643
5644static int under_gid_switch = 0;
5645static void
5646check_gid_switch(void)
5647{
5648 if (under_gid_switch) {
5649 rb_raise(rb_eRuntimeError, "can't handle GID while evaluating block given to Process::UID.switch method");
5650 }
5651}
5652
5653
5654#if defined(HAVE_PWD_H)
5655static inline bool
5656login_not_found(int err)
5657{
5658 return (err == ENOTTY || err == ENXIO || err == ENOENT);
5659}
5660
5666VALUE
5667rb_getlogin(void)
5668{
5669# if !defined(USE_GETLOGIN_R) && !defined(USE_GETLOGIN)
5670 return Qnil;
5671# else
5672 char MAYBE_UNUSED(*login) = NULL;
5673
5674# ifdef USE_GETLOGIN_R
5675
5676# if defined(__FreeBSD__)
5677 typedef int getlogin_r_size_t;
5678# else
5679 typedef size_t getlogin_r_size_t;
5680# endif
5681
5682 long loginsize = GETLOGIN_R_SIZE_INIT; /* maybe -1 */
5683
5684 if (loginsize < 0)
5685 loginsize = GETLOGIN_R_SIZE_DEFAULT;
5686
5687 VALUE maybe_result = rb_str_buf_new(loginsize);
5688
5689 login = RSTRING_PTR(maybe_result);
5690 loginsize = rb_str_capacity(maybe_result);
5691 rb_str_set_len(maybe_result, loginsize);
5692
5693 int gle;
5694 while ((gle = getlogin_r(login, (getlogin_r_size_t)loginsize)) != 0) {
5695 if (login_not_found(gle)) {
5696 rb_str_resize(maybe_result, 0);
5697 return Qnil;
5698 }
5699
5700 if (gle != ERANGE || loginsize >= GETLOGIN_R_SIZE_LIMIT) {
5701 rb_str_resize(maybe_result, 0);
5702 rb_syserr_fail(gle, "getlogin_r");
5703 }
5704
5705 rb_str_modify_expand(maybe_result, loginsize);
5706 login = RSTRING_PTR(maybe_result);
5707 loginsize = rb_str_capacity(maybe_result);
5708 }
5709
5710 if (login == NULL) {
5711 rb_str_resize(maybe_result, 0);
5712 return Qnil;
5713 }
5714
5715 rb_str_set_len(maybe_result, strlen(login));
5716 return maybe_result;
5717
5718# elif defined(USE_GETLOGIN)
5719
5720 errno = 0;
5721 login = getlogin();
5722 int err = errno;
5723 if (err) {
5724 if (login_not_found(err)) {
5725 return Qnil;
5726 }
5727 rb_syserr_fail(err, "getlogin");
5728 }
5729
5730 return login ? rb_str_new_cstr(login) : Qnil;
5731# endif
5732
5733#endif
5734}
5735
5736/* avoid treating as errors errno values that indicate "not found" */
5737static inline bool
5738pwd_not_found(int err)
5739{
5740 switch (err) {
5741 case 0:
5742 case ENOENT:
5743 case ESRCH:
5744 case EBADF:
5745 case EPERM:
5746 return true;
5747 default:
5748 return false;
5749 }
5750}
5751
5752# if defined(USE_GETPWNAM_R)
5753struct getpwnam_r_args {
5754 const char *login;
5755 char *buf;
5756 size_t bufsize;
5757 struct passwd *result;
5758 struct passwd pwstore;
5759};
5760
5761# define GETPWNAM_R_ARGS(login_, buf_, bufsize_) (struct getpwnam_r_args) \
5762 {.login = login_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
5763
5764static void *
5765nogvl_getpwnam_r(void *args)
5766{
5767 struct getpwnam_r_args *arg = args;
5768 return (void *)(VALUE)getpwnam_r(arg->login, &arg->pwstore, arg->buf, arg->bufsize, &arg->result);
5769}
5770# endif
5771
5772VALUE
5773rb_getpwdirnam_for_login(VALUE login_name)
5774{
5775#if !defined(USE_GETPWNAM_R) && !defined(USE_GETPWNAM)
5776 return Qnil;
5777#else
5778
5779 if (NIL_P(login_name)) {
5780 /* nothing to do; no name with which to query the password database */
5781 return Qnil;
5782 }
5783
5784 const char *login = RSTRING_PTR(login_name);
5785
5786
5787# ifdef USE_GETPWNAM_R
5788
5789 char *bufnm;
5790 long bufsizenm = GETPW_R_SIZE_INIT; /* maybe -1 */
5791
5792 if (bufsizenm < 0)
5793 bufsizenm = GETPW_R_SIZE_DEFAULT;
5794
5795 VALUE getpwnm_tmp = rb_str_tmp_new(bufsizenm);
5796
5797 bufnm = RSTRING_PTR(getpwnm_tmp);
5798 bufsizenm = rb_str_capacity(getpwnm_tmp);
5799 rb_str_set_len(getpwnm_tmp, bufsizenm);
5800 struct getpwnam_r_args args = GETPWNAM_R_ARGS(login, bufnm, (size_t)bufsizenm);
5801
5802 int enm;
5803 while ((enm = IO_WITHOUT_GVL_INT(nogvl_getpwnam_r, &args)) != 0) {
5804 if (pwd_not_found(enm)) {
5805 rb_str_resize(getpwnm_tmp, 0);
5806 return Qnil;
5807 }
5808
5809 if (enm != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5810 rb_str_resize(getpwnm_tmp, 0);
5811 rb_syserr_fail(enm, "getpwnam_r");
5812 }
5813
5814 rb_str_modify_expand(getpwnm_tmp, (long)args.bufsize);
5815 args.buf = RSTRING_PTR(getpwnm_tmp);
5816 args.bufsize = (size_t)rb_str_capacity(getpwnm_tmp);
5817 }
5818
5819 if (args.result == NULL) {
5820 /* no record in the password database for the login name */
5821 rb_str_resize(getpwnm_tmp, 0);
5822 return Qnil;
5823 }
5824
5825 /* found it */
5826 VALUE result = rb_str_new_cstr(args.result->pw_dir);
5827 rb_str_resize(getpwnm_tmp, 0);
5828 return result;
5829
5830# elif defined(USE_GETPWNAM)
5831
5832 struct passwd *pwptr;
5833 errno = 0;
5834 if (!(pwptr = getpwnam(login))) {
5835 int err = errno;
5836
5837 if (pwd_not_found(err)) {
5838 return Qnil;
5839 }
5840
5841 rb_syserr_fail(err, "getpwnam");
5842 }
5843
5844 /* found it */
5845 return rb_str_new_cstr(pwptr->pw_dir);
5846# endif
5847
5848#endif
5849}
5850
5851# if defined(USE_GETPWUID_R)
5852struct getpwuid_r_args {
5853 uid_t uid;
5854 char *buf;
5855 size_t bufsize;
5856 struct passwd *result;
5857 struct passwd pwstore;
5858};
5859
5860# define GETPWUID_R_ARGS(uid_, buf_, bufsize_) (struct getpwuid_r_args) \
5861 {.uid = uid_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
5862
5863static void *
5864nogvl_getpwuid_r(void *args)
5865{
5866 struct getpwuid_r_args *arg = args;
5867 return (void *)(VALUE)getpwuid_r(arg->uid, &arg->pwstore, arg->buf, arg->bufsize, &arg->result);
5868}
5869# endif
5870
5874VALUE
5875rb_getpwdiruid(void)
5876{
5877# if !defined(USE_GETPWUID_R) && !defined(USE_GETPWUID)
5878 /* Should never happen... </famous-last-words> */
5879 return Qnil;
5880# else
5881 uid_t ruid = getuid();
5882
5883# ifdef USE_GETPWUID_R
5884
5885 char *bufid;
5886 long bufsizeid = GETPW_R_SIZE_INIT; /* maybe -1 */
5887
5888 if (bufsizeid < 0)
5889 bufsizeid = GETPW_R_SIZE_DEFAULT;
5890
5891 VALUE getpwid_tmp = rb_str_tmp_new(bufsizeid);
5892
5893 bufid = RSTRING_PTR(getpwid_tmp);
5894 bufsizeid = rb_str_capacity(getpwid_tmp);
5895 rb_str_set_len(getpwid_tmp, bufsizeid);
5896 struct getpwuid_r_args args = GETPWUID_R_ARGS(ruid, bufid, (size_t)bufsizeid);
5897
5898 int eid;
5899 while ((eid = IO_WITHOUT_GVL_INT(nogvl_getpwuid_r, &args)) != 0) {
5900 if (pwd_not_found(eid)) {
5901 rb_str_resize(getpwid_tmp, 0);
5902 return Qnil;
5903 }
5904
5905 if (eid != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5906 rb_str_resize(getpwid_tmp, 0);
5907 rb_syserr_fail(eid, "getpwuid_r");
5908 }
5909
5910 rb_str_modify_expand(getpwid_tmp, (long)args.bufsize);
5911 args.buf = RSTRING_PTR(getpwid_tmp);
5912 args.bufsize = (size_t)rb_str_capacity(getpwid_tmp);
5913 }
5914
5915 if (args.result == NULL) {
5916 /* no record in the password database for the uid */
5917 rb_str_resize(getpwid_tmp, 0);
5918 return Qnil;
5919 }
5920
5921 /* found it */
5922 VALUE result = rb_str_new_cstr(args.result->pw_dir);
5923 rb_str_resize(getpwid_tmp, 0);
5924 return result;
5925
5926# elif defined(USE_GETPWUID)
5927
5928 struct passwd *pwptr;
5929 errno = 0;
5930 if (!(pwptr = getpwuid(ruid))) {
5931 int err = errno;
5932
5933 if (pwd_not_found(err)) {
5934 return Qnil;
5935 }
5936
5937 rb_syserr_fail(err, "getpwuid");
5938 }
5939
5940 /* found it */
5941 return rb_str_new_cstr(pwptr->pw_dir);
5942# endif
5943
5944#endif /* !defined(USE_GETPWUID_R) && !defined(USE_GETPWUID) */
5945}
5946#endif /* HAVE_PWD_H */
5947
5948
5949/*********************************************************************
5950 * Document-class: Process::Sys
5951 *
5952 * The Process::Sys module contains UID and GID
5953 * functions which provide direct bindings to the system calls of the
5954 * same names instead of the more-portable versions of the same
5955 * functionality found in the +Process+,
5956 * Process::UID, and Process::GID modules.
5957 */
5958
5959#if defined(HAVE_PWD_H)
5960static rb_uid_t
5961obj2uid(VALUE id
5962# ifdef USE_GETPWNAM_R
5963 , VALUE *getpw_tmp
5964# endif
5965 )
5966{
5967 rb_uid_t uid;
5968 VALUE tmp;
5969
5970 if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) {
5971 uid = NUM2UIDT(id);
5972 }
5973 else {
5974 const char *usrname = StringValueCStr(id);
5975 struct passwd *pwptr;
5976#ifdef USE_GETPWNAM_R
5977 char *getpw_buf;
5978 long getpw_buf_len;
5979 int e;
5980 if (!*getpw_tmp) {
5981 getpw_buf_len = GETPW_R_SIZE_INIT;
5982 if (getpw_buf_len < 0) getpw_buf_len = GETPW_R_SIZE_DEFAULT;
5983 *getpw_tmp = rb_str_tmp_new(getpw_buf_len);
5984 }
5985 getpw_buf = RSTRING_PTR(*getpw_tmp);
5986 getpw_buf_len = rb_str_capacity(*getpw_tmp);
5987 rb_str_set_len(*getpw_tmp, getpw_buf_len);
5988 errno = 0;
5989 struct getpwnam_r_args args = GETPWNAM_R_ARGS((char *)usrname, getpw_buf, (size_t)getpw_buf_len);
5990
5991 while ((e = IO_WITHOUT_GVL_INT(nogvl_getpwnam_r, &args)) != 0) {
5992 if (e != ERANGE || args.bufsize >= GETPW_R_SIZE_LIMIT) {
5993 rb_str_resize(*getpw_tmp, 0);
5994 rb_syserr_fail(e, "getpwnam_r");
5995 }
5996 rb_str_modify_expand(*getpw_tmp, (long)args.bufsize);
5997 args.buf = RSTRING_PTR(*getpw_tmp);
5998 args.bufsize = (size_t)rb_str_capacity(*getpw_tmp);
5999 }
6000 pwptr = args.result;
6001#else
6002 pwptr = getpwnam(usrname);
6003#endif
6004 if (!pwptr) {
6005#ifndef USE_GETPWNAM_R
6006 endpwent();
6007#endif
6008 rb_raise(rb_eArgError, "can't find user for %"PRIsVALUE, id);
6009 }
6010 uid = pwptr->pw_uid;
6011#ifndef USE_GETPWNAM_R
6012 endpwent();
6013#endif
6014 }
6015 return uid;
6016}
6017
6018# ifdef p_uid_from_name
6019/*
6020 * call-seq:
6021 * Process::UID.from_name(name) -> uid
6022 *
6023 * Get the user ID by the _name_.
6024 * If the user is not found, +ArgumentError+ will be raised.
6025 *
6026 * Process::UID.from_name("root") #=> 0
6027 * Process::UID.from_name("nosuchuser") #=> can't find user for nosuchuser (ArgumentError)
6028 */
6029
6030static VALUE
6031p_uid_from_name(VALUE self, VALUE id)
6032{
6033 return UIDT2NUM(OBJ2UID(id));
6034}
6035# endif
6036#endif
6037
6038#if defined(HAVE_GRP_H)
6039# if defined(USE_GETGRNAM_R)
6040struct getgrnam_r_args {
6041 const char *name;
6042 char *buf;
6043 size_t bufsize;
6044 struct group *result;
6045 struct group grp;
6046};
6047
6048# define GETGRNAM_R_ARGS(name_, buf_, bufsize_) (struct getgrnam_r_args) \
6049 {.name = name_, .buf = buf_, .bufsize = bufsize_, .result = NULL}
6050
6051static void *
6052nogvl_getgrnam_r(void *args)
6053{
6054 struct getgrnam_r_args *arg = args;
6055 return (void *)(VALUE)getgrnam_r(arg->name, &arg->grp, arg->buf, arg->bufsize, &arg->result);
6056}
6057# endif
6058
6059static rb_gid_t
6060obj2gid(VALUE id
6061# ifdef USE_GETGRNAM_R
6062 , VALUE *getgr_tmp
6063# endif
6064 )
6065{
6066 rb_gid_t gid;
6067 VALUE tmp;
6068
6069 if (FIXNUM_P(id) || NIL_P(tmp = rb_check_string_type(id))) {
6070 gid = NUM2GIDT(id);
6071 }
6072 else {
6073 const char *grpname = StringValueCStr(id);
6074 struct group *grptr;
6075#ifdef USE_GETGRNAM_R
6076 char *getgr_buf;
6077 long getgr_buf_len;
6078 int e;
6079 if (!*getgr_tmp) {
6080 getgr_buf_len = GETGR_R_SIZE_INIT;
6081 if (getgr_buf_len < 0) getgr_buf_len = GETGR_R_SIZE_DEFAULT;
6082 *getgr_tmp = rb_str_tmp_new(getgr_buf_len);
6083 }
6084 getgr_buf = RSTRING_PTR(*getgr_tmp);
6085 getgr_buf_len = rb_str_capacity(*getgr_tmp);
6086 rb_str_set_len(*getgr_tmp, getgr_buf_len);
6087 errno = 0;
6088 struct getgrnam_r_args args = GETGRNAM_R_ARGS(grpname, getgr_buf, (size_t)getgr_buf_len);
6089
6090 while ((e = IO_WITHOUT_GVL_INT(nogvl_getgrnam_r, &args)) != 0) {
6091 if (e != ERANGE || args.bufsize >= GETGR_R_SIZE_LIMIT) {
6092 rb_str_resize(*getgr_tmp, 0);
6093 rb_syserr_fail(e, "getgrnam_r");
6094 }
6095 rb_str_modify_expand(*getgr_tmp, (long)args.bufsize);
6096 args.buf = RSTRING_PTR(*getgr_tmp);
6097 args.bufsize = (size_t)rb_str_capacity(*getgr_tmp);
6098 }
6099 grptr = args.result;
6100#elif defined(HAVE_GETGRNAM)
6101 grptr = getgrnam(grpname);
6102#else
6103 grptr = NULL;
6104#endif
6105 if (!grptr) {
6106#if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT)
6107 endgrent();
6108#endif
6109 rb_raise(rb_eArgError, "can't find group for %"PRIsVALUE, id);
6110 }
6111 gid = grptr->gr_gid;
6112#if !defined(USE_GETGRNAM_R) && defined(HAVE_ENDGRENT)
6113 endgrent();
6114#endif
6115 }
6116 return gid;
6117}
6118
6119# ifdef p_gid_from_name
6120/*
6121 * call-seq:
6122 * Process::GID.from_name(name) -> gid
6123 *
6124 * Get the group ID by the _name_.
6125 * If the group is not found, +ArgumentError+ will be raised.
6126 *
6127 * Process::GID.from_name("wheel") #=> 0
6128 * Process::GID.from_name("nosuchgroup") #=> can't find group for nosuchgroup (ArgumentError)
6129 */
6130
6131static VALUE
6132p_gid_from_name(VALUE self, VALUE id)
6133{
6134 return GIDT2NUM(OBJ2GID(id));
6135}
6136# endif
6137#endif
6138
6139#if defined HAVE_SETUID
6140/*
6141 * call-seq:
6142 * Process::Sys.setuid(user) -> nil
6143 *
6144 * Set the user ID of the current process to _user_. Not
6145 * available on all platforms.
6146 *
6147 */
6148
6149static VALUE
6150p_sys_setuid(VALUE obj, VALUE id)
6151{
6152 check_uid_switch();
6153 if (setuid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6154 return Qnil;
6155}
6156#else
6157#define p_sys_setuid rb_f_notimplement
6158#endif
6159
6160
6161#if defined HAVE_SETRUID
6162/*
6163 * call-seq:
6164 * Process::Sys.setruid(user) -> nil
6165 *
6166 * Set the real user ID of the calling process to _user_.
6167 * Not available on all platforms.
6168 *
6169 */
6170
6171static VALUE
6172p_sys_setruid(VALUE obj, VALUE id)
6173{
6174 check_uid_switch();
6175 if (setruid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6176 return Qnil;
6177}
6178#else
6179#define p_sys_setruid rb_f_notimplement
6180#endif
6181
6182
6183#if defined HAVE_SETEUID
6184/*
6185 * call-seq:
6186 * Process::Sys.seteuid(user) -> nil
6187 *
6188 * Set the effective user ID of the calling process to
6189 * _user_. Not available on all platforms.
6190 *
6191 */
6192
6193static VALUE
6194p_sys_seteuid(VALUE obj, VALUE id)
6195{
6196 check_uid_switch();
6197 if (seteuid(OBJ2UID(id)) != 0) rb_sys_fail(0);
6198 return Qnil;
6199}
6200#else
6201#define p_sys_seteuid rb_f_notimplement
6202#endif
6203
6204
6205#if defined HAVE_SETREUID
6206/*
6207 * call-seq:
6208 * Process::Sys.setreuid(rid, eid) -> nil
6209 *
6210 * Sets the (user) real and/or effective user IDs of the current
6211 * process to _rid_ and _eid_, respectively. A value of
6212 * <code>-1</code> for either means to leave that ID unchanged. Not
6213 * available on all platforms.
6214 *
6215 */
6216
6217static VALUE
6218p_sys_setreuid(VALUE obj, VALUE rid, VALUE eid)
6219{
6220 rb_uid_t ruid, euid;
6221 PREPARE_GETPWNAM;
6222 check_uid_switch();
6223 ruid = OBJ2UID1(rid);
6224 euid = OBJ2UID1(eid);
6225 FINISH_GETPWNAM;
6226 if (setreuid(ruid, euid) != 0) rb_sys_fail(0);
6227 return Qnil;
6228}
6229#else
6230#define p_sys_setreuid rb_f_notimplement
6231#endif
6232
6233
6234#if defined HAVE_SETRESUID
6235/*
6236 * call-seq:
6237 * Process::Sys.setresuid(rid, eid, sid) -> nil
6238 *
6239 * Sets the (user) real, effective, and saved user IDs of the
6240 * current process to _rid_, _eid_, and _sid_ respectively. A
6241 * value of <code>-1</code> for any value means to
6242 * leave that ID unchanged. Not available on all platforms.
6243 *
6244 */
6245
6246static VALUE
6247p_sys_setresuid(VALUE obj, VALUE rid, VALUE eid, VALUE sid)
6248{
6249 rb_uid_t ruid, euid, suid;
6250 PREPARE_GETPWNAM;
6251 check_uid_switch();
6252 ruid = OBJ2UID1(rid);
6253 euid = OBJ2UID1(eid);
6254 suid = OBJ2UID1(sid);
6255 FINISH_GETPWNAM;
6256 if (setresuid(ruid, euid, suid) != 0) rb_sys_fail(0);
6257 return Qnil;
6258}
6259#else
6260#define p_sys_setresuid rb_f_notimplement
6261#endif
6262
6263
6264/*
6265 * call-seq:
6266 * Process.uid -> integer
6267 * Process::UID.rid -> integer
6268 * Process::Sys.getuid -> integer
6269 *
6270 * Returns the (real) user ID of the current process.
6271 *
6272 * Process.uid # => 1000
6273 *
6274 */
6275
6276static VALUE
6277proc_getuid(VALUE obj)
6278{
6279 rb_uid_t uid = getuid();
6280 return UIDT2NUM(uid);
6281}
6282
6283
6284#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETRUID) || defined(HAVE_SETUID)
6285/*
6286 * call-seq:
6287 * Process.uid = new_uid -> new_uid
6288 *
6289 * Sets the (user) user ID for the current process to +new_uid+:
6290 *
6291 * Process.uid = 1000 # => 1000
6292 *
6293 * Not available on all platforms.
6294 */
6295
6296static VALUE
6297proc_setuid(VALUE obj, VALUE id)
6298{
6299 rb_uid_t uid;
6300
6301 check_uid_switch();
6302
6303 uid = OBJ2UID(id);
6304#if defined(HAVE_SETRESUID)
6305 if (setresuid(uid, -1, -1) < 0) rb_sys_fail(0);
6306#elif defined HAVE_SETREUID
6307 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6308#elif defined HAVE_SETRUID
6309 if (setruid(uid) < 0) rb_sys_fail(0);
6310#elif defined HAVE_SETUID
6311 {
6312 if (geteuid() == uid) {
6313 if (setuid(uid) < 0) rb_sys_fail(0);
6314 }
6315 else {
6317 }
6318 }
6319#endif
6320 return id;
6321}
6322#else
6323#define proc_setuid rb_f_notimplement
6324#endif
6325
6326
6327/********************************************************************
6328 *
6329 * Document-class: Process::UID
6330 *
6331 * The Process::UID module contains a collection of
6332 * module functions which can be used to portably get, set, and
6333 * switch the current process's real, effective, and saved user IDs.
6334 *
6335 */
6336
6337static rb_uid_t SAVED_USER_ID = -1;
6338
6339#ifdef BROKEN_SETREUID
6340int
6341setreuid(rb_uid_t ruid, rb_uid_t euid)
6342{
6343 if (ruid != (rb_uid_t)-1 && ruid != getuid()) {
6344 if (euid == (rb_uid_t)-1) euid = geteuid();
6345 if (setuid(ruid) < 0) return -1;
6346 }
6347 if (euid != (rb_uid_t)-1 && euid != geteuid()) {
6348 if (seteuid(euid) < 0) return -1;
6349 }
6350 return 0;
6351}
6352#endif
6353
6354/*
6355 * call-seq:
6356 * Process::UID.change_privilege(user) -> integer
6357 *
6358 * Change the current process's real and effective user ID to that
6359 * specified by _user_. Returns the new user ID. Not
6360 * available on all platforms.
6361 *
6362 * [Process.uid, Process.euid] #=> [0, 0]
6363 * Process::UID.change_privilege(31) #=> 31
6364 * [Process.uid, Process.euid] #=> [31, 31]
6365 */
6366
6367static VALUE
6368p_uid_change_privilege(VALUE obj, VALUE id)
6369{
6370 rb_uid_t uid;
6371
6372 check_uid_switch();
6373
6374 uid = OBJ2UID(id);
6375
6376 if (geteuid() == 0) { /* root-user */
6377#if defined(HAVE_SETRESUID)
6378 if (setresuid(uid, uid, uid) < 0) rb_sys_fail(0);
6379 SAVED_USER_ID = uid;
6380#elif defined(HAVE_SETUID)
6381 if (setuid(uid) < 0) rb_sys_fail(0);
6382 SAVED_USER_ID = uid;
6383#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
6384 if (getuid() == uid) {
6385 if (SAVED_USER_ID == uid) {
6386 if (setreuid(-1, uid) < 0) rb_sys_fail(0);
6387 }
6388 else {
6389 if (uid == 0) { /* (r,e,s) == (root, root, x) */
6390 if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
6391 if (setreuid(SAVED_USER_ID, 0) < 0) rb_sys_fail(0);
6392 SAVED_USER_ID = 0; /* (r,e,s) == (x, root, root) */
6393 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6394 SAVED_USER_ID = uid;
6395 }
6396 else {
6397 if (setreuid(0, -1) < 0) rb_sys_fail(0);
6398 SAVED_USER_ID = 0;
6399 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6400 SAVED_USER_ID = uid;
6401 }
6402 }
6403 }
6404 else {
6405 if (setreuid(uid, uid) < 0) rb_sys_fail(0);
6406 SAVED_USER_ID = uid;
6407 }
6408#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
6409 if (getuid() == uid) {
6410 if (SAVED_USER_ID == uid) {
6411 if (seteuid(uid) < 0) rb_sys_fail(0);
6412 }
6413 else {
6414 if (uid == 0) {
6415 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6416 SAVED_USER_ID = 0;
6417 if (setruid(0) < 0) rb_sys_fail(0);
6418 }
6419 else {
6420 if (setruid(0) < 0) rb_sys_fail(0);
6421 SAVED_USER_ID = 0;
6422 if (seteuid(uid) < 0) rb_sys_fail(0);
6423 if (setruid(uid) < 0) rb_sys_fail(0);
6424 SAVED_USER_ID = uid;
6425 }
6426 }
6427 }
6428 else {
6429 if (seteuid(uid) < 0) rb_sys_fail(0);
6430 if (setruid(uid) < 0) rb_sys_fail(0);
6431 SAVED_USER_ID = uid;
6432 }
6433#else
6434 (void)uid;
6436#endif
6437 }
6438 else { /* unprivileged user */
6439#if defined(HAVE_SETRESUID)
6440 if (setresuid((getuid() == uid)? (rb_uid_t)-1: uid,
6441 (geteuid() == uid)? (rb_uid_t)-1: uid,
6442 (SAVED_USER_ID == uid)? (rb_uid_t)-1: uid) < 0) rb_sys_fail(0);
6443 SAVED_USER_ID = uid;
6444#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
6445 if (SAVED_USER_ID == uid) {
6446 if (setreuid((getuid() == uid)? (rb_uid_t)-1: uid,
6447 (geteuid() == uid)? (rb_uid_t)-1: uid) < 0)
6448 rb_sys_fail(0);
6449 }
6450 else if (getuid() != uid) {
6451 if (setreuid(uid, (geteuid() == uid)? (rb_uid_t)-1: uid) < 0)
6452 rb_sys_fail(0);
6453 SAVED_USER_ID = uid;
6454 }
6455 else if (/* getuid() == uid && */ geteuid() != uid) {
6456 if (setreuid(geteuid(), uid) < 0) rb_sys_fail(0);
6457 SAVED_USER_ID = uid;
6458 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6459 }
6460 else { /* getuid() == uid && geteuid() == uid */
6461 if (setreuid(-1, SAVED_USER_ID) < 0) rb_sys_fail(0);
6462 if (setreuid(SAVED_USER_ID, uid) < 0) rb_sys_fail(0);
6463 SAVED_USER_ID = uid;
6464 if (setreuid(uid, -1) < 0) rb_sys_fail(0);
6465 }
6466#elif defined(HAVE_SETRUID) && defined(HAVE_SETEUID)
6467 if (SAVED_USER_ID == uid) {
6468 if (geteuid() != uid && seteuid(uid) < 0) rb_sys_fail(0);
6469 if (getuid() != uid && setruid(uid) < 0) rb_sys_fail(0);
6470 }
6471 else if (/* SAVED_USER_ID != uid && */ geteuid() == uid) {
6472 if (getuid() != uid) {
6473 if (setruid(uid) < 0) rb_sys_fail(0);
6474 SAVED_USER_ID = uid;
6475 }
6476 else {
6477 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6478 SAVED_USER_ID = uid;
6479 if (setruid(uid) < 0) rb_sys_fail(0);
6480 }
6481 }
6482 else if (/* geteuid() != uid && */ getuid() == uid) {
6483 if (seteuid(uid) < 0) rb_sys_fail(0);
6484 if (setruid(SAVED_USER_ID) < 0) rb_sys_fail(0);
6485 SAVED_USER_ID = uid;
6486 if (setruid(uid) < 0) rb_sys_fail(0);
6487 }
6488 else {
6489 rb_syserr_fail(EPERM, 0);
6490 }
6491#elif defined HAVE_44BSD_SETUID
6492 if (getuid() == uid) {
6493 /* (r,e,s)==(uid,?,?) ==> (uid,uid,uid) */
6494 if (setuid(uid) < 0) rb_sys_fail(0);
6495 SAVED_USER_ID = uid;
6496 }
6497 else {
6498 rb_syserr_fail(EPERM, 0);
6499 }
6500#elif defined HAVE_SETEUID
6501 if (getuid() == uid && SAVED_USER_ID == uid) {
6502 if (seteuid(uid) < 0) rb_sys_fail(0);
6503 }
6504 else {
6505 rb_syserr_fail(EPERM, 0);
6506 }
6507#elif defined HAVE_SETUID
6508 if (getuid() == uid && SAVED_USER_ID == uid) {
6509 if (setuid(uid) < 0) rb_sys_fail(0);
6510 }
6511 else {
6512 rb_syserr_fail(EPERM, 0);
6513 }
6514#else
6516#endif
6517 }
6518 return id;
6519}
6520
6521
6522
6523#if defined HAVE_SETGID
6524/*
6525 * call-seq:
6526 * Process::Sys.setgid(group) -> nil
6527 *
6528 * Set the group ID of the current process to _group_. Not
6529 * available on all platforms.
6530 *
6531 */
6532
6533static VALUE
6534p_sys_setgid(VALUE obj, VALUE id)
6535{
6536 check_gid_switch();
6537 if (setgid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6538 return Qnil;
6539}
6540#else
6541#define p_sys_setgid rb_f_notimplement
6542#endif
6543
6544
6545#if defined HAVE_SETRGID
6546/*
6547 * call-seq:
6548 * Process::Sys.setrgid(group) -> nil
6549 *
6550 * Set the real group ID of the calling process to _group_.
6551 * Not available on all platforms.
6552 *
6553 */
6554
6555static VALUE
6556p_sys_setrgid(VALUE obj, VALUE id)
6557{
6558 check_gid_switch();
6559 if (setrgid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6560 return Qnil;
6561}
6562#else
6563#define p_sys_setrgid rb_f_notimplement
6564#endif
6565
6566
6567#if defined HAVE_SETEGID
6568/*
6569 * call-seq:
6570 * Process::Sys.setegid(group) -> nil
6571 *
6572 * Set the effective group ID of the calling process to
6573 * _group_. Not available on all platforms.
6574 *
6575 */
6576
6577static VALUE
6578p_sys_setegid(VALUE obj, VALUE id)
6579{
6580 check_gid_switch();
6581 if (setegid(OBJ2GID(id)) != 0) rb_sys_fail(0);
6582 return Qnil;
6583}
6584#else
6585#define p_sys_setegid rb_f_notimplement
6586#endif
6587
6588
6589#if defined HAVE_SETREGID
6590/*
6591 * call-seq:
6592 * Process::Sys.setregid(rid, eid) -> nil
6593 *
6594 * Sets the (group) real and/or effective group IDs of the current
6595 * process to <em>rid</em> and <em>eid</em>, respectively. A value of
6596 * <code>-1</code> for either means to leave that ID unchanged. Not
6597 * available on all platforms.
6598 *
6599 */
6600
6601static VALUE
6602p_sys_setregid(VALUE obj, VALUE rid, VALUE eid)
6603{
6604 rb_gid_t rgid, egid;
6605 check_gid_switch();
6606 rgid = OBJ2GID(rid);
6607 egid = OBJ2GID(eid);
6608 if (setregid(rgid, egid) != 0) rb_sys_fail(0);
6609 return Qnil;
6610}
6611#else
6612#define p_sys_setregid rb_f_notimplement
6613#endif
6614
6615#if defined HAVE_SETRESGID
6616/*
6617 * call-seq:
6618 * Process::Sys.setresgid(rid, eid, sid) -> nil
6619 *
6620 * Sets the (group) real, effective, and saved user IDs of the
6621 * current process to <em>rid</em>, <em>eid</em>, and <em>sid</em>
6622 * respectively. A value of <code>-1</code> for any value means to
6623 * leave that ID unchanged. Not available on all platforms.
6624 *
6625 */
6626
6627static VALUE
6628p_sys_setresgid(VALUE obj, VALUE rid, VALUE eid, VALUE sid)
6629{
6630 rb_gid_t rgid, egid, sgid;
6631 check_gid_switch();
6632 rgid = OBJ2GID(rid);
6633 egid = OBJ2GID(eid);
6634 sgid = OBJ2GID(sid);
6635 if (setresgid(rgid, egid, sgid) != 0) rb_sys_fail(0);
6636 return Qnil;
6637}
6638#else
6639#define p_sys_setresgid rb_f_notimplement
6640#endif
6641
6642
6643#if defined HAVE_ISSETUGID
6644/*
6645 * call-seq:
6646 * Process::Sys.issetugid -> true or false
6647 *
6648 * Returns +true+ if the process was created as a result
6649 * of an execve(2) system call which had either of the setuid or
6650 * setgid bits set (and extra privileges were given as a result) or
6651 * if it has changed any of its real, effective or saved user or
6652 * group IDs since it began execution.
6653 *
6654 */
6655
6656static VALUE
6657p_sys_issetugid(VALUE obj)
6658{
6659 return RBOOL(issetugid());
6660}
6661#else
6662#define p_sys_issetugid rb_f_notimplement
6663#endif
6664
6665
6666/*
6667 * call-seq:
6668 * Process.gid -> integer
6669 * Process::GID.rid -> integer
6670 * Process::Sys.getgid -> integer
6671 *
6672 * Returns the (real) group ID for the current process:
6673 *
6674 * Process.gid # => 1000
6675 *
6676 */
6677
6678static VALUE
6679proc_getgid(VALUE obj)
6680{
6681 rb_gid_t gid = getgid();
6682 return GIDT2NUM(gid);
6683}
6684
6685
6686#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETRGID) || defined(HAVE_SETGID)
6687/*
6688 * call-seq:
6689 * Process.gid = new_gid -> new_gid
6690 *
6691 * Sets the group ID for the current process to +new_gid+:
6692 *
6693 * Process.gid = 1000 # => 1000
6694 *
6695 */
6696
6697static VALUE
6698proc_setgid(VALUE obj, VALUE id)
6699{
6700 rb_gid_t gid;
6701
6702 check_gid_switch();
6703
6704 gid = OBJ2GID(id);
6705#if defined(HAVE_SETRESGID)
6706 if (setresgid(gid, -1, -1) < 0) rb_sys_fail(0);
6707#elif defined HAVE_SETREGID
6708 if (setregid(gid, -1) < 0) rb_sys_fail(0);
6709#elif defined HAVE_SETRGID
6710 if (setrgid(gid) < 0) rb_sys_fail(0);
6711#elif defined HAVE_SETGID
6712 {
6713 if (getegid() == gid) {
6714 if (setgid(gid) < 0) rb_sys_fail(0);
6715 }
6716 else {
6718 }
6719 }
6720#endif
6721 return GIDT2NUM(gid);
6722}
6723#else
6724#define proc_setgid rb_f_notimplement
6725#endif
6726
6727
6728#if defined(_SC_NGROUPS_MAX) || defined(NGROUPS_MAX)
6729/*
6730 * Maximum supplementary groups are platform dependent.
6731 * FWIW, 65536 is enough big for our supported OSs.
6732 *
6733 * OS Name max groups
6734 * -----------------------------------------------
6735 * Linux Kernel >= 2.6.3 65536
6736 * Linux Kernel < 2.6.3 32
6737 * IBM AIX 5.2 64
6738 * IBM AIX 5.3 ... 6.1 128
6739 * IBM AIX 7.1 128 (can be configured to be up to 2048)
6740 * OpenBSD, NetBSD 16
6741 * FreeBSD < 8.0 16
6742 * FreeBSD >=8.0 1023
6743 * Darwin (Mac OS X) 16
6744 * Sun Solaris 7,8,9,10 16
6745 * Sun Solaris 11 / OpenSolaris 1024
6746 * Windows 1015
6747 */
6748static int _maxgroups = -1;
6749static int
6750get_sc_ngroups_max(void)
6751{
6752#ifdef _SC_NGROUPS_MAX
6753 return (int)sysconf(_SC_NGROUPS_MAX);
6754#elif defined(NGROUPS_MAX)
6755 return (int)NGROUPS_MAX;
6756#else
6757 return -1;
6758#endif
6759}
6760static int
6761maxgroups(void)
6762{
6763 if (_maxgroups < 0) {
6764 _maxgroups = get_sc_ngroups_max();
6765 if (_maxgroups < 0)
6766 _maxgroups = RB_MAX_GROUPS;
6767 }
6768
6769 return _maxgroups;
6770}
6771#endif
6772
6773
6774
6775#ifdef HAVE_GETGROUPS
6776/*
6777 * call-seq:
6778 * Process.groups -> array
6779 *
6780 * Returns an array of the group IDs
6781 * in the supplemental group access list for the current process:
6782 *
6783 * Process.groups # => [4, 24, 27, 30, 46, 122, 135, 136, 1000]
6784 *
6785 * These properties of the returned array are system-dependent:
6786 *
6787 * - Whether (and how) the array is sorted.
6788 * - Whether the array includes effective group IDs.
6789 * - Whether the array includes duplicate group IDs.
6790 * - Whether the array size exceeds the value of Process.maxgroups.
6791 *
6792 * Use this call to get a sorted and unique array:
6793 *
6794 * Process.groups.uniq.sort
6795 *
6796 */
6797
6798static VALUE
6799proc_getgroups(VALUE obj)
6800{
6801 VALUE ary, tmp;
6802 int i, ngroups;
6803 rb_gid_t *groups;
6804
6805 ngroups = getgroups(0, NULL);
6806 if (ngroups == -1)
6807 rb_sys_fail(0);
6808
6809 groups = ALLOCV_N(rb_gid_t, tmp, ngroups);
6810
6811 ngroups = getgroups(ngroups, groups);
6812 if (ngroups == -1)
6813 rb_sys_fail(0);
6814
6815 ary = rb_ary_new();
6816 for (i = 0; i < ngroups; i++)
6817 rb_ary_push(ary, GIDT2NUM(groups[i]));
6818
6819 ALLOCV_END(tmp);
6820
6821 return ary;
6822}
6823#else
6824#define proc_getgroups rb_f_notimplement
6825#endif
6826
6827
6828#ifdef HAVE_SETGROUPS
6829/*
6830 * call-seq:
6831 * Process.groups = new_groups -> new_groups
6832 *
6833 * Sets the supplemental group access list to the given
6834 * array of group IDs.
6835 *
6836 * Process.groups # => [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
6837 * Process.groups = [27, 6, 10, 11] # => [27, 6, 10, 11]
6838 * Process.groups # => [27, 6, 10, 11]
6839 *
6840 */
6841
6842static VALUE
6843proc_setgroups(VALUE obj, VALUE ary)
6844{
6845 int ngroups, i;
6846 rb_gid_t *groups;
6847 VALUE tmp;
6848 PREPARE_GETGRNAM;
6849
6850 Check_Type(ary, T_ARRAY);
6851
6852 ngroups = RARRAY_LENINT(ary);
6853 if (ngroups > maxgroups())
6854 rb_raise(rb_eArgError, "too many groups, %d max", maxgroups());
6855
6856 groups = ALLOCV_N(rb_gid_t, tmp, ngroups);
6857
6858 for (i = 0; i < ngroups; i++) {
6859 VALUE g = RARRAY_AREF(ary, i);
6860
6861 groups[i] = OBJ2GID1(g);
6862 }
6863 FINISH_GETGRNAM;
6864
6865 if (setgroups(ngroups, groups) == -1) /* ngroups <= maxgroups */
6866 rb_sys_fail(0);
6867
6868 ALLOCV_END(tmp);
6869
6870 return proc_getgroups(obj);
6871}
6872#else
6873#define proc_setgroups rb_f_notimplement
6874#endif
6875
6876
6877#ifdef HAVE_INITGROUPS
6878/*
6879 * call-seq:
6880 * Process.initgroups(username, gid) -> array
6881 *
6882 * Sets the supplemental group access list;
6883 * the new list includes:
6884 *
6885 * - The group IDs of those groups to which the user given by +username+ belongs.
6886 * - The group ID +gid+.
6887 *
6888 * Example:
6889 *
6890 * Process.groups # => [0, 1, 2, 3, 4, 6, 10, 11, 20, 26, 27]
6891 * Process.initgroups('me', 30) # => [30, 6, 10, 11]
6892 * Process.groups # => [30, 6, 10, 11]
6893 *
6894 * Not available on all platforms.
6895 */
6896
6897static VALUE
6898proc_initgroups(VALUE obj, VALUE uname, VALUE base_grp)
6899{
6900 if (initgroups(StringValueCStr(uname), OBJ2GID(base_grp)) != 0) {
6901 rb_sys_fail(0);
6902 }
6903 return proc_getgroups(obj);
6904}
6905#else
6906#define proc_initgroups rb_f_notimplement
6907#endif
6908
6909#if defined(_SC_NGROUPS_MAX) || defined(NGROUPS_MAX)
6910/*
6911 * call-seq:
6912 * Process.maxgroups -> integer
6913 *
6914 * Returns the maximum number of group IDs allowed
6915 * in the supplemental group access list:
6916 *
6917 * Process.maxgroups # => 32
6918 *
6919 */
6920
6921static VALUE
6922proc_getmaxgroups(VALUE obj)
6923{
6924 return INT2FIX(maxgroups());
6925}
6926#else
6927#define proc_getmaxgroups rb_f_notimplement
6928#endif
6929
6930#ifdef HAVE_SETGROUPS
6931/*
6932 * call-seq:
6933 * Process.maxgroups = new_max -> new_max
6934 *
6935 * Sets the maximum number of group IDs allowed
6936 * in the supplemental group access list.
6937 */
6938
6939static VALUE
6940proc_setmaxgroups(VALUE obj, VALUE val)
6941{
6942 int ngroups = FIX2INT(val);
6943 int ngroups_max = get_sc_ngroups_max();
6944
6945 if (ngroups <= 0)
6946 rb_raise(rb_eArgError, "maxgroups %d should be positive", ngroups);
6947
6948 if (ngroups > RB_MAX_GROUPS)
6949 ngroups = RB_MAX_GROUPS;
6950
6951 if (ngroups_max > 0 && ngroups > ngroups_max)
6952 ngroups = ngroups_max;
6953
6954 _maxgroups = ngroups;
6955
6956 return INT2FIX(_maxgroups);
6957}
6958#else
6959#define proc_setmaxgroups rb_f_notimplement
6960#endif
6961
6962#if defined(HAVE_DAEMON) || (defined(HAVE_WORKING_FORK) && defined(HAVE_SETSID))
6963static int rb_daemon(int nochdir, int noclose);
6964
6965/*
6966 * call-seq:
6967 * Process.daemon(nochdir = nil, noclose = nil) -> 0
6968 *
6969 * Detaches the current process from its controlling terminal
6970 * and runs it in the background as system daemon;
6971 * returns zero.
6972 *
6973 * By default:
6974 *
6975 * - Changes the current working directory to the root directory.
6976 * - Redirects $stdin, $stdout, and $stderr to the null device.
6977 *
6978 * If optional argument +nochdir+ is +true+,
6979 * does not change the current working directory.
6980 *
6981 * If optional argument +noclose+ is +true+,
6982 * does not redirect $stdin, $stdout, or $stderr.
6983 */
6984
6985static VALUE
6986proc_daemon(int argc, VALUE *argv, VALUE _)
6987{
6988 int n, nochdir = FALSE, noclose = FALSE;
6989
6990 switch (rb_check_arity(argc, 0, 2)) {
6991 case 2: noclose = TO_BOOL(argv[1], "noclose");
6992 case 1: nochdir = TO_BOOL(argv[0], "nochdir");
6993 }
6994
6995 prefork();
6996 n = rb_daemon(nochdir, noclose);
6997 if (n < 0) rb_sys_fail("daemon");
6998 return INT2FIX(n);
6999}
7000
7001extern const char ruby_null_device[];
7002
7003static int
7004rb_daemon(int nochdir, int noclose)
7005{
7006 int err = 0;
7007#ifdef HAVE_DAEMON
7008 rb_pid_t pid = getpid();
7009 before_fork_ruby();
7010 rb_thread_acquire_fork_lock();
7011 err = daemon(nochdir, noclose);
7012 /* daemon(3) can fail in the child as well, so compare pids */
7013 release_fork_lock_after_fork(getpid() == pid ? pid : 0);
7014 after_fork_ruby(0);
7015#else
7016 int n;
7017
7018 switch (rb_fork_ruby(NULL)) {
7019 case -1: return -1;
7020 case 0: break;
7021 default: _exit(EXIT_SUCCESS);
7022 }
7023
7024 /* ignore EPERM which means already being process-leader */
7025 if (setsid() < 0) (void)0;
7026
7027 if (!nochdir)
7028 err = chdir("/");
7029
7030 if (!noclose && (n = rb_cloexec_open(ruby_null_device, O_RDWR, 0)) != -1) {
7032 (void)dup2(n, 0);
7033 (void)dup2(n, 1);
7034 (void)dup2(n, 2);
7035 if (n > 2)
7036 (void)close (n);
7037 }
7038#endif
7039 return err;
7040}
7041#else
7042#define proc_daemon rb_f_notimplement
7043#endif
7044
7045/********************************************************************
7046 *
7047 * Document-class: Process::GID
7048 *
7049 * The Process::GID module contains a collection of
7050 * module functions which can be used to portably get, set, and
7051 * switch the current process's real, effective, and saved group IDs.
7052 *
7053 */
7054
7055static rb_gid_t SAVED_GROUP_ID = -1;
7056
7057#ifdef BROKEN_SETREGID
7058int
7059setregid(rb_gid_t rgid, rb_gid_t egid)
7060{
7061 if (rgid != (rb_gid_t)-1 && rgid != getgid()) {
7062 if (egid == (rb_gid_t)-1) egid = getegid();
7063 if (setgid(rgid) < 0) return -1;
7064 }
7065 if (egid != (rb_gid_t)-1 && egid != getegid()) {
7066 if (setegid(egid) < 0) return -1;
7067 }
7068 return 0;
7069}
7070#endif
7071
7072/*
7073 * call-seq:
7074 * Process::GID.change_privilege(group) -> integer
7075 *
7076 * Change the current process's real and effective group ID to that
7077 * specified by _group_. Returns the new group ID. Not
7078 * available on all platforms.
7079 *
7080 * [Process.gid, Process.egid] #=> [0, 0]
7081 * Process::GID.change_privilege(33) #=> 33
7082 * [Process.gid, Process.egid] #=> [33, 33]
7083 */
7084
7085static VALUE
7086p_gid_change_privilege(VALUE obj, VALUE id)
7087{
7088 rb_gid_t gid;
7089
7090 check_gid_switch();
7091
7092 gid = OBJ2GID(id);
7093
7094 if (geteuid() == 0) { /* root-user */
7095#if defined(HAVE_SETRESGID)
7096 if (setresgid(gid, gid, gid) < 0) rb_sys_fail(0);
7097 SAVED_GROUP_ID = gid;
7098#elif defined HAVE_SETGID
7099 if (setgid(gid) < 0) rb_sys_fail(0);
7100 SAVED_GROUP_ID = gid;
7101#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7102 if (getgid() == gid) {
7103 if (SAVED_GROUP_ID == gid) {
7104 if (setregid(-1, gid) < 0) rb_sys_fail(0);
7105 }
7106 else {
7107 if (gid == 0) { /* (r,e,s) == (root, y, x) */
7108 if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7109 if (setregid(SAVED_GROUP_ID, 0) < 0) rb_sys_fail(0);
7110 SAVED_GROUP_ID = 0; /* (r,e,s) == (x, root, root) */
7111 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7112 SAVED_GROUP_ID = gid;
7113 }
7114 else { /* (r,e,s) == (z, y, x) */
7115 if (setregid(0, 0) < 0) rb_sys_fail(0);
7116 SAVED_GROUP_ID = 0;
7117 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7118 SAVED_GROUP_ID = gid;
7119 }
7120 }
7121 }
7122 else {
7123 if (setregid(gid, gid) < 0) rb_sys_fail(0);
7124 SAVED_GROUP_ID = gid;
7125 }
7126#elif defined(HAVE_SETRGID) && defined (HAVE_SETEGID)
7127 if (getgid() == gid) {
7128 if (SAVED_GROUP_ID == gid) {
7129 if (setegid(gid) < 0) rb_sys_fail(0);
7130 }
7131 else {
7132 if (gid == 0) {
7133 if (setegid(gid) < 0) rb_sys_fail(0);
7134 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7135 SAVED_GROUP_ID = 0;
7136 if (setrgid(0) < 0) rb_sys_fail(0);
7137 }
7138 else {
7139 if (setrgid(0) < 0) rb_sys_fail(0);
7140 SAVED_GROUP_ID = 0;
7141 if (setegid(gid) < 0) rb_sys_fail(0);
7142 if (setrgid(gid) < 0) rb_sys_fail(0);
7143 SAVED_GROUP_ID = gid;
7144 }
7145 }
7146 }
7147 else {
7148 if (setegid(gid) < 0) rb_sys_fail(0);
7149 if (setrgid(gid) < 0) rb_sys_fail(0);
7150 SAVED_GROUP_ID = gid;
7151 }
7152#else
7154#endif
7155 }
7156 else { /* unprivileged user */
7157#if defined(HAVE_SETRESGID)
7158 if (setresgid((getgid() == gid)? (rb_gid_t)-1: gid,
7159 (getegid() == gid)? (rb_gid_t)-1: gid,
7160 (SAVED_GROUP_ID == gid)? (rb_gid_t)-1: gid) < 0) rb_sys_fail(0);
7161 SAVED_GROUP_ID = gid;
7162#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7163 if (SAVED_GROUP_ID == gid) {
7164 if (setregid((getgid() == gid)? (rb_uid_t)-1: gid,
7165 (getegid() == gid)? (rb_uid_t)-1: gid) < 0)
7166 rb_sys_fail(0);
7167 }
7168 else if (getgid() != gid) {
7169 if (setregid(gid, (getegid() == gid)? (rb_uid_t)-1: gid) < 0)
7170 rb_sys_fail(0);
7171 SAVED_GROUP_ID = gid;
7172 }
7173 else if (/* getgid() == gid && */ getegid() != gid) {
7174 if (setregid(getegid(), gid) < 0) rb_sys_fail(0);
7175 SAVED_GROUP_ID = gid;
7176 if (setregid(gid, -1) < 0) rb_sys_fail(0);
7177 }
7178 else { /* getgid() == gid && getegid() == gid */
7179 if (setregid(-1, SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7180 if (setregid(SAVED_GROUP_ID, gid) < 0) rb_sys_fail(0);
7181 SAVED_GROUP_ID = gid;
7182 if (setregid(gid, -1) < 0) rb_sys_fail(0);
7183 }
7184#elif defined(HAVE_SETRGID) && defined(HAVE_SETEGID)
7185 if (SAVED_GROUP_ID == gid) {
7186 if (getegid() != gid && setegid(gid) < 0) rb_sys_fail(0);
7187 if (getgid() != gid && setrgid(gid) < 0) rb_sys_fail(0);
7188 }
7189 else if (/* SAVED_GROUP_ID != gid && */ getegid() == gid) {
7190 if (getgid() != gid) {
7191 if (setrgid(gid) < 0) rb_sys_fail(0);
7192 SAVED_GROUP_ID = gid;
7193 }
7194 else {
7195 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7196 SAVED_GROUP_ID = gid;
7197 if (setrgid(gid) < 0) rb_sys_fail(0);
7198 }
7199 }
7200 else if (/* getegid() != gid && */ getgid() == gid) {
7201 if (setegid(gid) < 0) rb_sys_fail(0);
7202 if (setrgid(SAVED_GROUP_ID) < 0) rb_sys_fail(0);
7203 SAVED_GROUP_ID = gid;
7204 if (setrgid(gid) < 0) rb_sys_fail(0);
7205 }
7206 else {
7207 rb_syserr_fail(EPERM, 0);
7208 }
7209#elif defined HAVE_44BSD_SETGID
7210 if (getgid() == gid) {
7211 /* (r,e,s)==(gid,?,?) ==> (gid,gid,gid) */
7212 if (setgid(gid) < 0) rb_sys_fail(0);
7213 SAVED_GROUP_ID = gid;
7214 }
7215 else {
7216 rb_syserr_fail(EPERM, 0);
7217 }
7218#elif defined HAVE_SETEGID
7219 if (getgid() == gid && SAVED_GROUP_ID == gid) {
7220 if (setegid(gid) < 0) rb_sys_fail(0);
7221 }
7222 else {
7223 rb_syserr_fail(EPERM, 0);
7224 }
7225#elif defined HAVE_SETGID
7226 if (getgid() == gid && SAVED_GROUP_ID == gid) {
7227 if (setgid(gid) < 0) rb_sys_fail(0);
7228 }
7229 else {
7230 rb_syserr_fail(EPERM, 0);
7231 }
7232#else
7233 (void)gid;
7235#endif
7236 }
7237 return id;
7238}
7239
7240
7241/*
7242 * call-seq:
7243 * Process.euid -> integer
7244 * Process::UID.eid -> integer
7245 * Process::Sys.geteuid -> integer
7246 *
7247 * Returns the effective user ID for the current process.
7248 *
7249 * Process.euid # => 501
7250 *
7251 */
7252
7253static VALUE
7254proc_geteuid(VALUE obj)
7255{
7256 rb_uid_t euid = geteuid();
7257 return UIDT2NUM(euid);
7258}
7259
7260#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID) || defined(HAVE_SETUID) || defined(_POSIX_SAVED_IDS)
7261static void
7262proc_seteuid(rb_uid_t uid)
7263{
7264#if defined(HAVE_SETRESUID)
7265 if (setresuid(-1, uid, -1) < 0) rb_sys_fail(0);
7266#elif defined HAVE_SETREUID
7267 if (setreuid(-1, uid) < 0) rb_sys_fail(0);
7268#elif defined HAVE_SETEUID
7269 if (seteuid(uid) < 0) rb_sys_fail(0);
7270#elif defined HAVE_SETUID
7271 if (uid == getuid()) {
7272 if (setuid(uid) < 0) rb_sys_fail(0);
7273 }
7274 else {
7276 }
7277#else
7279#endif
7280}
7281#endif
7282
7283#if defined(HAVE_SETRESUID) || defined(HAVE_SETREUID) || defined(HAVE_SETEUID) || defined(HAVE_SETUID)
7284/*
7285 * call-seq:
7286 * Process.euid = new_euid -> new_euid
7287 *
7288 * Sets the effective user ID for the current process.
7289 *
7290 * Not available on all platforms.
7291 */
7292
7293static VALUE
7294proc_seteuid_m(VALUE mod, VALUE euid)
7295{
7296 check_uid_switch();
7297 proc_seteuid(OBJ2UID(euid));
7298 return euid;
7299}
7300#else
7301#define proc_seteuid_m rb_f_notimplement
7302#endif
7303
7304static rb_uid_t
7305rb_seteuid_core(rb_uid_t euid)
7306{
7307#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7308 rb_uid_t uid;
7309#endif
7310
7311 check_uid_switch();
7312
7313#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7314 uid = getuid();
7315#endif
7316
7317#if defined(HAVE_SETRESUID)
7318 if (uid != euid) {
7319 if (setresuid(-1,euid,euid) < 0) rb_sys_fail(0);
7320 SAVED_USER_ID = euid;
7321 }
7322 else {
7323 if (setresuid(-1,euid,-1) < 0) rb_sys_fail(0);
7324 }
7325#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7326 if (setreuid(-1, euid) < 0) rb_sys_fail(0);
7327 if (uid != euid) {
7328 if (setreuid(euid,uid) < 0) rb_sys_fail(0);
7329 if (setreuid(uid,euid) < 0) rb_sys_fail(0);
7330 SAVED_USER_ID = euid;
7331 }
7332#elif defined HAVE_SETEUID
7333 if (seteuid(euid) < 0) rb_sys_fail(0);
7334#elif defined HAVE_SETUID
7335 if (geteuid() == 0) rb_sys_fail(0);
7336 if (setuid(euid) < 0) rb_sys_fail(0);
7337#else
7339#endif
7340 return euid;
7341}
7342
7343
7344/*
7345 * call-seq:
7346 * Process::UID.grant_privilege(user) -> integer
7347 * Process::UID.eid= user -> integer
7348 *
7349 * Set the effective user ID, and if possible, the saved user ID of
7350 * the process to the given _user_. Returns the new
7351 * effective user ID. Not available on all platforms.
7352 *
7353 * [Process.uid, Process.euid] #=> [0, 0]
7354 * Process::UID.grant_privilege(31) #=> 31
7355 * [Process.uid, Process.euid] #=> [0, 31]
7356 */
7357
7358static VALUE
7359p_uid_grant_privilege(VALUE obj, VALUE id)
7360{
7361 rb_seteuid_core(OBJ2UID(id));
7362 return id;
7363}
7364
7365
7366/*
7367 * call-seq:
7368 * Process.egid -> integer
7369 * Process::GID.eid -> integer
7370 * Process::Sys.geteid -> integer
7371 *
7372 * Returns the effective group ID for the current process:
7373 *
7374 * Process.egid # => 500
7375 *
7376 * Not available on all platforms.
7377 */
7378
7379static VALUE
7380proc_getegid(VALUE obj)
7381{
7382 rb_gid_t egid = getegid();
7383
7384 return GIDT2NUM(egid);
7385}
7386
7387#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID) || defined(_POSIX_SAVED_IDS)
7388/*
7389 * call-seq:
7390 * Process.egid = new_egid -> new_egid
7391 *
7392 * Sets the effective group ID for the current process.
7393 *
7394 * Not available on all platforms.
7395 */
7396
7397static VALUE
7398proc_setegid(VALUE obj, VALUE egid)
7399{
7400#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7401 rb_gid_t gid;
7402#endif
7403
7404 check_gid_switch();
7405
7406#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7407 gid = OBJ2GID(egid);
7408#endif
7409
7410#if defined(HAVE_SETRESGID)
7411 if (setresgid(-1, gid, -1) < 0) rb_sys_fail(0);
7412#elif defined HAVE_SETREGID
7413 if (setregid(-1, gid) < 0) rb_sys_fail(0);
7414#elif defined HAVE_SETEGID
7415 if (setegid(gid) < 0) rb_sys_fail(0);
7416#elif defined HAVE_SETGID
7417 if (gid == getgid()) {
7418 if (setgid(gid) < 0) rb_sys_fail(0);
7419 }
7420 else {
7422 }
7423#else
7425#endif
7426 return egid;
7427}
7428#endif
7429
7430#if defined(HAVE_SETRESGID) || defined(HAVE_SETREGID) || defined(HAVE_SETEGID) || defined(HAVE_SETGID)
7431#define proc_setegid_m proc_setegid
7432#else
7433#define proc_setegid_m rb_f_notimplement
7434#endif
7435
7436static rb_gid_t
7437rb_setegid_core(rb_gid_t egid)
7438{
7439#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7440 rb_gid_t gid;
7441#endif
7442
7443 check_gid_switch();
7444
7445#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7446 gid = getgid();
7447#endif
7448
7449#if defined(HAVE_SETRESGID)
7450 if (gid != egid) {
7451 if (setresgid(-1,egid,egid) < 0) rb_sys_fail(0);
7452 SAVED_GROUP_ID = egid;
7453 }
7454 else {
7455 if (setresgid(-1,egid,-1) < 0) rb_sys_fail(0);
7456 }
7457#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7458 if (setregid(-1, egid) < 0) rb_sys_fail(0);
7459 if (gid != egid) {
7460 if (setregid(egid,gid) < 0) rb_sys_fail(0);
7461 if (setregid(gid,egid) < 0) rb_sys_fail(0);
7462 SAVED_GROUP_ID = egid;
7463 }
7464#elif defined HAVE_SETEGID
7465 if (setegid(egid) < 0) rb_sys_fail(0);
7466#elif defined HAVE_SETGID
7467 if (geteuid() == 0 /* root user */) rb_sys_fail(0);
7468 if (setgid(egid) < 0) rb_sys_fail(0);
7469#else
7471#endif
7472 return egid;
7473}
7474
7475
7476/*
7477 * call-seq:
7478 * Process::GID.grant_privilege(group) -> integer
7479 * Process::GID.eid = group -> integer
7480 *
7481 * Set the effective group ID, and if possible, the saved group ID of
7482 * the process to the given _group_. Returns the new
7483 * effective group ID. Not available on all platforms.
7484 *
7485 * [Process.gid, Process.egid] #=> [0, 0]
7486 * Process::GID.grant_privilege(31) #=> 33
7487 * [Process.gid, Process.egid] #=> [0, 33]
7488 */
7489
7490static VALUE
7491p_gid_grant_privilege(VALUE obj, VALUE id)
7492{
7493 rb_setegid_core(OBJ2GID(id));
7494 return id;
7495}
7496
7497
7498/*
7499 * call-seq:
7500 * Process::UID.re_exchangeable? -> true or false
7501 *
7502 * Returns +true+ if the real and effective user IDs of a
7503 * process may be exchanged on the current platform.
7504 *
7505 */
7506
7507static VALUE
7508p_uid_exchangeable(VALUE _)
7509{
7510#if defined(HAVE_SETRESUID)
7511 return Qtrue;
7512#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7513 return Qtrue;
7514#else
7515 return Qfalse;
7516#endif
7517}
7518
7519
7520/*
7521 * call-seq:
7522 * Process::UID.re_exchange -> integer
7523 *
7524 * Exchange real and effective user IDs and return the new effective
7525 * user ID. Not available on all platforms.
7526 *
7527 * [Process.uid, Process.euid] #=> [0, 31]
7528 * Process::UID.re_exchange #=> 0
7529 * [Process.uid, Process.euid] #=> [31, 0]
7530 */
7531
7532static VALUE
7533p_uid_exchange(VALUE obj)
7534{
7535 rb_uid_t uid;
7536#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7537 rb_uid_t euid;
7538#endif
7539
7540 check_uid_switch();
7541
7542 uid = getuid();
7543#if defined(HAVE_SETRESUID) || (defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID))
7544 euid = geteuid();
7545#endif
7546
7547#if defined(HAVE_SETRESUID)
7548 if (setresuid(euid, uid, uid) < 0) rb_sys_fail(0);
7549 SAVED_USER_ID = uid;
7550#elif defined(HAVE_SETREUID) && !defined(OBSOLETE_SETREUID)
7551 if (setreuid(euid,uid) < 0) rb_sys_fail(0);
7552 SAVED_USER_ID = uid;
7553#else
7555#endif
7556 return UIDT2NUM(uid);
7557}
7558
7559
7560/*
7561 * call-seq:
7562 * Process::GID.re_exchangeable? -> true or false
7563 *
7564 * Returns +true+ if the real and effective group IDs of a
7565 * process may be exchanged on the current platform.
7566 *
7567 */
7568
7569static VALUE
7570p_gid_exchangeable(VALUE _)
7571{
7572#if defined(HAVE_SETRESGID)
7573 return Qtrue;
7574#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7575 return Qtrue;
7576#else
7577 return Qfalse;
7578#endif
7579}
7580
7581
7582/*
7583 * call-seq:
7584 * Process::GID.re_exchange -> integer
7585 *
7586 * Exchange real and effective group IDs and return the new effective
7587 * group ID. Not available on all platforms.
7588 *
7589 * [Process.gid, Process.egid] #=> [0, 33]
7590 * Process::GID.re_exchange #=> 0
7591 * [Process.gid, Process.egid] #=> [33, 0]
7592 */
7593
7594static VALUE
7595p_gid_exchange(VALUE obj)
7596{
7597 rb_gid_t gid;
7598#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7599 rb_gid_t egid;
7600#endif
7601
7602 check_gid_switch();
7603
7604 gid = getgid();
7605#if defined(HAVE_SETRESGID) || (defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID))
7606 egid = getegid();
7607#endif
7608
7609#if defined(HAVE_SETRESGID)
7610 if (setresgid(egid, gid, gid) < 0) rb_sys_fail(0);
7611 SAVED_GROUP_ID = gid;
7612#elif defined(HAVE_SETREGID) && !defined(OBSOLETE_SETREGID)
7613 if (setregid(egid,gid) < 0) rb_sys_fail(0);
7614 SAVED_GROUP_ID = gid;
7615#else
7617#endif
7618 return GIDT2NUM(gid);
7619}
7620
7621/* [MG] :FIXME: Is this correct? I'm not sure how to phrase this. */
7622
7623/*
7624 * call-seq:
7625 * Process::UID.sid_available? -> true or false
7626 *
7627 * Returns +true+ if the current platform has saved user
7628 * ID functionality.
7629 *
7630 */
7631
7632static VALUE
7633p_uid_have_saved_id(VALUE _)
7634{
7635#if defined(HAVE_SETRESUID) || defined(HAVE_SETEUID) || defined(_POSIX_SAVED_IDS)
7636 return Qtrue;
7637#else
7638 return Qfalse;
7639#endif
7640}
7641
7642
7643#if defined(HAVE_SETRESUID) || defined(HAVE_SETEUID) || defined(_POSIX_SAVED_IDS)
7644static VALUE
7645p_uid_sw_ensure(VALUE i)
7646{
7647 rb_uid_t id = (rb_uid_t/* narrowing */)i;
7648 under_uid_switch = 0;
7649 id = rb_seteuid_core(id);
7650 return UIDT2NUM(id);
7651}
7652
7653
7654/*
7655 * call-seq:
7656 * Process::UID.switch -> integer
7657 * Process::UID.switch {|| block} -> object
7658 *
7659 * Switch the effective and real user IDs of the current process. If
7660 * a <em>block</em> is given, the user IDs will be switched back
7661 * after the block is executed. Returns the new effective user ID if
7662 * called without a block, and the return value of the block if one
7663 * is given.
7664 *
7665 */
7666
7667static VALUE
7668p_uid_switch(VALUE obj)
7669{
7670 rb_uid_t uid, euid;
7671
7672 check_uid_switch();
7673
7674 uid = getuid();
7675 euid = geteuid();
7676
7677 if (uid != euid) {
7678 proc_seteuid(uid);
7679 if (rb_block_given_p()) {
7680 under_uid_switch = 1;
7681 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, SAVED_USER_ID);
7682 }
7683 else {
7684 return UIDT2NUM(euid);
7685 }
7686 }
7687 else if (euid != SAVED_USER_ID) {
7688 proc_seteuid(SAVED_USER_ID);
7689 if (rb_block_given_p()) {
7690 under_uid_switch = 1;
7691 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, euid);
7692 }
7693 else {
7694 return UIDT2NUM(uid);
7695 }
7696 }
7697 else {
7698 rb_syserr_fail(EPERM, 0);
7699 }
7700
7702}
7703#else
7704static VALUE
7705p_uid_sw_ensure(VALUE obj)
7706{
7707 under_uid_switch = 0;
7708 return p_uid_exchange(obj);
7709}
7710
7711static VALUE
7712p_uid_switch(VALUE obj)
7713{
7714 rb_uid_t uid, euid;
7715
7716 check_uid_switch();
7717
7718 uid = getuid();
7719 euid = geteuid();
7720
7721 if (uid == euid) {
7722 rb_syserr_fail(EPERM, 0);
7723 }
7724 p_uid_exchange(obj);
7725 if (rb_block_given_p()) {
7726 under_uid_switch = 1;
7727 return rb_ensure(rb_yield, Qnil, p_uid_sw_ensure, obj);
7728 }
7729 else {
7730 return UIDT2NUM(euid);
7731 }
7732}
7733#endif
7734
7735
7736/* [MG] :FIXME: Is this correct? I'm not sure how to phrase this. */
7737
7738/*
7739 * call-seq:
7740 * Process::GID.sid_available? -> true or false
7741 *
7742 * Returns +true+ if the current platform has saved group
7743 * ID functionality.
7744 *
7745 */
7746
7747static VALUE
7748p_gid_have_saved_id(VALUE _)
7749{
7750#if defined(HAVE_SETRESGID) || defined(HAVE_SETEGID) || defined(_POSIX_SAVED_IDS)
7751 return Qtrue;
7752#else
7753 return Qfalse;
7754#endif
7755}
7756
7757#if defined(HAVE_SETRESGID) || defined(HAVE_SETEGID) || defined(_POSIX_SAVED_IDS)
7758static VALUE
7759p_gid_sw_ensure(VALUE i)
7760{
7761 rb_gid_t id = (rb_gid_t/* narrowing */)i;
7762 under_gid_switch = 0;
7763 id = rb_setegid_core(id);
7764 return GIDT2NUM(id);
7765}
7766
7767
7768/*
7769 * call-seq:
7770 * Process::GID.switch -> integer
7771 * Process::GID.switch {|| block} -> object
7772 *
7773 * Switch the effective and real group IDs of the current process. If
7774 * a <em>block</em> is given, the group IDs will be switched back
7775 * after the block is executed. Returns the new effective group ID if
7776 * called without a block, and the return value of the block if one
7777 * is given.
7778 *
7779 */
7780
7781static VALUE
7782p_gid_switch(VALUE obj)
7783{
7784 rb_gid_t gid, egid;
7785
7786 check_gid_switch();
7787
7788 gid = getgid();
7789 egid = getegid();
7790
7791 if (gid != egid) {
7792 proc_setegid(obj, GIDT2NUM(gid));
7793 if (rb_block_given_p()) {
7794 under_gid_switch = 1;
7795 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, SAVED_GROUP_ID);
7796 }
7797 else {
7798 return GIDT2NUM(egid);
7799 }
7800 }
7801 else if (egid != SAVED_GROUP_ID) {
7802 proc_setegid(obj, GIDT2NUM(SAVED_GROUP_ID));
7803 if (rb_block_given_p()) {
7804 under_gid_switch = 1;
7805 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, egid);
7806 }
7807 else {
7808 return GIDT2NUM(gid);
7809 }
7810 }
7811 else {
7812 rb_syserr_fail(EPERM, 0);
7813 }
7814
7816}
7817#else
7818static VALUE
7819p_gid_sw_ensure(VALUE obj)
7820{
7821 under_gid_switch = 0;
7822 return p_gid_exchange(obj);
7823}
7824
7825static VALUE
7826p_gid_switch(VALUE obj)
7827{
7828 rb_gid_t gid, egid;
7829
7830 check_gid_switch();
7831
7832 gid = getgid();
7833 egid = getegid();
7834
7835 if (gid == egid) {
7836 rb_syserr_fail(EPERM, 0);
7837 }
7838 p_gid_exchange(obj);
7839 if (rb_block_given_p()) {
7840 under_gid_switch = 1;
7841 return rb_ensure(rb_yield, Qnil, p_gid_sw_ensure, obj);
7842 }
7843 else {
7844 return GIDT2NUM(egid);
7845 }
7846}
7847#endif
7848
7849
7850#if defined(HAVE_TIMES)
7851static long
7852get_clk_tck(void)
7853{
7854#ifdef HAVE__SC_CLK_TCK
7855 return sysconf(_SC_CLK_TCK);
7856#elif defined CLK_TCK
7857 return CLK_TCK;
7858#elif defined HZ
7859 return HZ;
7860#else
7861 return 60;
7862#endif
7863}
7864
7865/*
7866 * call-seq:
7867 * Process.times -> process_tms
7868 *
7869 * Returns a Process::Tms structure that contains user and system CPU times
7870 * for the current process, and for its children processes:
7871 *
7872 * Process.times
7873 * # => #<struct Process::Tms utime=55.122118, stime=35.533068, cutime=0.0, cstime=0.002846>
7874 *
7875 * The precision is platform-defined.
7876 */
7877
7878VALUE
7879rb_proc_times(VALUE obj)
7880{
7881 VALUE utime, stime, cutime, cstime, ret;
7882#if defined(RUSAGE_SELF) && defined(RUSAGE_CHILDREN)
7883 struct rusage usage_s, usage_c;
7884
7885 if (getrusage(RUSAGE_SELF, &usage_s) != 0 || getrusage(RUSAGE_CHILDREN, &usage_c) != 0)
7886 rb_sys_fail("getrusage");
7887 utime = DBL2NUM((double)usage_s.ru_utime.tv_sec + (double)usage_s.ru_utime.tv_usec/1e6);
7888 stime = DBL2NUM((double)usage_s.ru_stime.tv_sec + (double)usage_s.ru_stime.tv_usec/1e6);
7889 cutime = DBL2NUM((double)usage_c.ru_utime.tv_sec + (double)usage_c.ru_utime.tv_usec/1e6);
7890 cstime = DBL2NUM((double)usage_c.ru_stime.tv_sec + (double)usage_c.ru_stime.tv_usec/1e6);
7891#else
7892 const double hertz = (double)get_clk_tck();
7893 struct tms buf;
7894
7895 times(&buf);
7896 utime = DBL2NUM(buf.tms_utime / hertz);
7897 stime = DBL2NUM(buf.tms_stime / hertz);
7898 cutime = DBL2NUM(buf.tms_cutime / hertz);
7899 cstime = DBL2NUM(buf.tms_cstime / hertz);
7900#endif
7901 ret = rb_struct_new(rb_cProcessTms, utime, stime, cutime, cstime);
7902 RB_GC_GUARD(utime);
7903 RB_GC_GUARD(stime);
7904 RB_GC_GUARD(cutime);
7905 RB_GC_GUARD(cstime);
7906 return ret;
7907}
7908#else
7909#define rb_proc_times rb_f_notimplement
7910#endif
7911
7912#ifdef HAVE_LONG_LONG
7913typedef LONG_LONG timetick_int_t;
7914#define TIMETICK_INT_MIN LLONG_MIN
7915#define TIMETICK_INT_MAX LLONG_MAX
7916#define TIMETICK_INT2NUM(v) LL2NUM(v)
7917#define MUL_OVERFLOW_TIMETICK_P(a, b) MUL_OVERFLOW_LONG_LONG_P(a, b)
7918#else
7919typedef long timetick_int_t;
7920#define TIMETICK_INT_MIN LONG_MIN
7921#define TIMETICK_INT_MAX LONG_MAX
7922#define TIMETICK_INT2NUM(v) LONG2NUM(v)
7923#define MUL_OVERFLOW_TIMETICK_P(a, b) MUL_OVERFLOW_LONG_P(a, b)
7924#endif
7925
7926CONSTFUNC(static timetick_int_t gcd_timetick_int(timetick_int_t, timetick_int_t));
7927static timetick_int_t
7928gcd_timetick_int(timetick_int_t a, timetick_int_t b)
7929{
7930 timetick_int_t t;
7931
7932 if (a < b) {
7933 t = a;
7934 a = b;
7935 b = t;
7936 }
7937
7938 while (1) {
7939 t = a % b;
7940 if (t == 0)
7941 return b;
7942 a = b;
7943 b = t;
7944 }
7945}
7946
7947static void
7948reduce_fraction(timetick_int_t *np, timetick_int_t *dp)
7949{
7950 timetick_int_t gcd = gcd_timetick_int(*np, *dp);
7951 if (gcd != 1) {
7952 *np /= gcd;
7953 *dp /= gcd;
7954 }
7955}
7956
7957static void
7958reduce_factors(timetick_int_t *numerators, int num_numerators,
7959 timetick_int_t *denominators, int num_denominators)
7960{
7961 int i, j;
7962 for (i = 0; i < num_numerators; i++) {
7963 if (numerators[i] == 1)
7964 continue;
7965 for (j = 0; j < num_denominators; j++) {
7966 if (denominators[j] == 1)
7967 continue;
7968 reduce_fraction(&numerators[i], &denominators[j]);
7969 }
7970 }
7971}
7972
7973struct timetick {
7974 timetick_int_t giga_count;
7975 int32_t count; /* 0 .. 999999999 */
7976};
7977
7978static VALUE
7979timetick2dblnum(struct timetick *ttp,
7980 timetick_int_t *numerators, int num_numerators,
7981 timetick_int_t *denominators, int num_denominators)
7982{
7983 double d;
7984 int i;
7985
7986 reduce_factors(numerators, num_numerators,
7987 denominators, num_denominators);
7988
7989 d = ttp->giga_count * 1e9 + ttp->count;
7990
7991 for (i = 0; i < num_numerators; i++)
7992 d *= numerators[i];
7993 for (i = 0; i < num_denominators; i++)
7994 d /= denominators[i];
7995
7996 return DBL2NUM(d);
7997}
7998
7999static VALUE
8000timetick2dblnum_reciprocal(struct timetick *ttp,
8001 timetick_int_t *numerators, int num_numerators,
8002 timetick_int_t *denominators, int num_denominators)
8003{
8004 double d;
8005 int i;
8006
8007 reduce_factors(numerators, num_numerators,
8008 denominators, num_denominators);
8009
8010 d = 1.0;
8011 for (i = 0; i < num_denominators; i++)
8012 d *= denominators[i];
8013 for (i = 0; i < num_numerators; i++)
8014 d /= numerators[i];
8015 d /= ttp->giga_count * 1e9 + ttp->count;
8016
8017 return DBL2NUM(d);
8018}
8019
8020#define NDIV(x,y) (-(-((x)+1)/(y))-1)
8021#define DIV(n,d) ((n)<0 ? NDIV((n),(d)) : (n)/(d))
8022
8023static VALUE
8024timetick2integer(struct timetick *ttp,
8025 timetick_int_t *numerators, int num_numerators,
8026 timetick_int_t *denominators, int num_denominators)
8027{
8028 VALUE v;
8029 int i;
8030
8031 reduce_factors(numerators, num_numerators,
8032 denominators, num_denominators);
8033
8034 if (!MUL_OVERFLOW_SIGNED_INTEGER_P(1000000000, ttp->giga_count,
8035 TIMETICK_INT_MIN, TIMETICK_INT_MAX-ttp->count)) {
8036 timetick_int_t t = ttp->giga_count * 1000000000 + ttp->count;
8037 for (i = 0; i < num_numerators; i++) {
8038 timetick_int_t factor = numerators[i];
8039 if (MUL_OVERFLOW_TIMETICK_P(factor, t))
8040 goto generic;
8041 t *= factor;
8042 }
8043 for (i = 0; i < num_denominators; i++) {
8044 t = DIV(t, denominators[i]);
8045 }
8046 return TIMETICK_INT2NUM(t);
8047 }
8048
8049 generic:
8050 v = TIMETICK_INT2NUM(ttp->giga_count);
8051 v = rb_funcall(v, '*', 1, LONG2FIX(1000000000));
8052 v = rb_funcall(v, '+', 1, LONG2FIX(ttp->count));
8053 for (i = 0; i < num_numerators; i++) {
8054 timetick_int_t factor = numerators[i];
8055 if (factor == 1)
8056 continue;
8057 v = rb_funcall(v, '*', 1, TIMETICK_INT2NUM(factor));
8058 }
8059 for (i = 0; i < num_denominators; i++) {
8060 v = rb_funcall(v, '/', 1, TIMETICK_INT2NUM(denominators[i])); /* Ruby's '/' is div. */
8061 }
8062 return v;
8063}
8064
8065static VALUE
8066make_clock_result(struct timetick *ttp,
8067 timetick_int_t *numerators, int num_numerators,
8068 timetick_int_t *denominators, int num_denominators,
8069 VALUE unit)
8070{
8071 if (unit == ID2SYM(id_nanosecond)) {
8072 numerators[num_numerators++] = 1000000000;
8073 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
8074 }
8075 else if (unit == ID2SYM(id_microsecond)) {
8076 numerators[num_numerators++] = 1000000;
8077 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
8078 }
8079 else if (unit == ID2SYM(id_millisecond)) {
8080 numerators[num_numerators++] = 1000;
8081 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
8082 }
8083 else if (unit == ID2SYM(id_second)) {
8084 return timetick2integer(ttp, numerators, num_numerators, denominators, num_denominators);
8085 }
8086 else if (unit == ID2SYM(id_float_microsecond)) {
8087 numerators[num_numerators++] = 1000000;
8088 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
8089 }
8090 else if (unit == ID2SYM(id_float_millisecond)) {
8091 numerators[num_numerators++] = 1000;
8092 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
8093 }
8094 else if (NIL_P(unit) || unit == ID2SYM(id_float_second)) {
8095 return timetick2dblnum(ttp, numerators, num_numerators, denominators, num_denominators);
8096 }
8097 else
8098 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
8099}
8100
8101#ifdef __APPLE__
8102static const mach_timebase_info_data_t *
8103get_mach_timebase_info(void)
8104{
8105 static mach_timebase_info_data_t sTimebaseInfo;
8106
8107 if ( sTimebaseInfo.denom == 0 ) {
8108 (void) mach_timebase_info(&sTimebaseInfo);
8109 }
8110
8111 return &sTimebaseInfo;
8112}
8113
8114double
8115ruby_real_ms_time(void)
8116{
8117 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8118 uint64_t t = mach_absolute_time();
8119 return (double)t * info->numer / info->denom / 1e6;
8120}
8121#endif
8122
8123#if defined(NUM2CLOCKID)
8124# define NUMERIC_CLOCKID 1
8125#else
8126# define NUMERIC_CLOCKID 0
8127# define NUM2CLOCKID(x) 0
8128#endif
8129
8130#define clock_failed(name, err, arg) do { \
8131 int clock_error = (err); \
8132 rb_syserr_fail_str(clock_error, rb_sprintf("clock_" name "(%+"PRIsVALUE")", (arg))); \
8133 } while (0)
8134
8135/*
8136 * call-seq:
8137 * Process.clock_gettime(clock_id, unit = :float_second) -> number
8138 *
8139 * Returns a clock time as determined by POSIX function
8140 * {clock_gettime()}[https://man7.org/linux/man-pages/man3/clock_gettime.3.html]:
8141 *
8142 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID) # => 198.650379677
8143 *
8144 * Argument +clock_id+ should be a symbol or a constant that specifies
8145 * the clock whose time is to be returned;
8146 * see below.
8147 *
8148 * Optional argument +unit+ should be a symbol that specifies
8149 * the unit to be used in the returned clock time;
8150 * see below.
8151 *
8152 * <b>Argument +clock_id+</b>
8153 *
8154 * Argument +clock_id+ specifies the clock whose time is to be returned;
8155 * it may be a constant such as <tt>Process::CLOCK_REALTIME</tt>,
8156 * or a symbol shorthand such as +:CLOCK_REALTIME+.
8157 *
8158 * The supported clocks depend on the underlying operating system;
8159 * this method supports the following clocks on the indicated platforms
8160 * (raises Errno::EINVAL if called with an unsupported clock):
8161 *
8162 * - +:CLOCK_BOOTTIME+: Linux 2.6.39.
8163 * - +:CLOCK_BOOTTIME_ALARM+: Linux 3.0.
8164 * - +:CLOCK_MONOTONIC+: SUSv3 to 4, Linux 2.5.63, FreeBSD 3.0, NetBSD 2.0, OpenBSD 3.4, macOS 10.12, Windows-2000.
8165 * - +:CLOCK_MONOTONIC_COARSE+: Linux 2.6.32.
8166 * - +:CLOCK_MONOTONIC_FAST+: FreeBSD 8.1.
8167 * - +:CLOCK_MONOTONIC_PRECISE+: FreeBSD 8.1.
8168 * - +:CLOCK_MONOTONIC_RAW+: Linux 2.6.28, macOS 10.12.
8169 * - +:CLOCK_MONOTONIC_RAW_APPROX+: macOS 10.12.
8170 * - +:CLOCK_PROCESS_CPUTIME_ID+: SUSv3 to 4, Linux 2.5.63, FreeBSD 9.3, OpenBSD 5.4, macOS 10.12.
8171 * - +:CLOCK_PROF+: FreeBSD 3.0, OpenBSD 2.1.
8172 * - +:CLOCK_REALTIME+: SUSv2 to 4, Linux 2.5.63, FreeBSD 3.0, NetBSD 2.0, OpenBSD 2.1, macOS 10.12, Windows-8/Server-2012.
8173 * Time.now is recommended over +:CLOCK_REALTIME:.
8174 * - +:CLOCK_REALTIME_ALARM+: Linux 3.0.
8175 * - +:CLOCK_REALTIME_COARSE+: Linux 2.6.32.
8176 * - +:CLOCK_REALTIME_FAST+: FreeBSD 8.1.
8177 * - +:CLOCK_REALTIME_PRECISE+: FreeBSD 8.1.
8178 * - +:CLOCK_SECOND+: FreeBSD 8.1.
8179 * - +:CLOCK_TAI+: Linux 3.10.
8180 * - +:CLOCK_THREAD_CPUTIME_ID+: SUSv3 to 4, Linux 2.5.63, FreeBSD 7.1, OpenBSD 5.4, macOS 10.12.
8181 * - +:CLOCK_UPTIME+: FreeBSD 7.0, OpenBSD 5.5.
8182 * - +:CLOCK_UPTIME_FAST+: FreeBSD 8.1.
8183 * - +:CLOCK_UPTIME_PRECISE+: FreeBSD 8.1.
8184 * - +:CLOCK_UPTIME_RAW+: macOS 10.12.
8185 * - +:CLOCK_UPTIME_RAW_APPROX+: macOS 10.12.
8186 * - +:CLOCK_VIRTUAL+: FreeBSD 3.0, OpenBSD 2.1.
8187 *
8188 * Note that SUS stands for Single Unix Specification.
8189 * SUS contains POSIX and clock_gettime is defined in the POSIX part.
8190 * SUS defines +:CLOCK_REALTIME+ as mandatory but
8191 * +:CLOCK_MONOTONIC+, +:CLOCK_PROCESS_CPUTIME_ID+,
8192 * and +:CLOCK_THREAD_CPUTIME_ID+ are optional.
8193 *
8194 * Certain emulations are used when the given +clock_id+
8195 * is not supported directly:
8196 *
8197 * - Emulations for +:CLOCK_REALTIME+:
8198 *
8199 * - +:GETTIMEOFDAY_BASED_CLOCK_REALTIME+:
8200 * Use gettimeofday() defined by SUS (deprecated in SUSv4).
8201 * The resolution is 1 microsecond.
8202 * - +:TIME_BASED_CLOCK_REALTIME+:
8203 * Use time() defined by ISO C.
8204 * The resolution is 1 second.
8205 *
8206 * - Emulations for +:CLOCK_MONOTONIC+:
8207 *
8208 * - +:MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC+:
8209 * Use mach_absolute_time(), available on Darwin.
8210 * The resolution is CPU dependent.
8211 * - +:TIMES_BASED_CLOCK_MONOTONIC+:
8212 * Use the result value of times() defined by POSIX, thus:
8213 * >>>
8214 * Upon successful completion, times() shall return the elapsed real time,
8215 * in clock ticks, since an arbitrary point in the past
8216 * (for example, system start-up time).
8217 *
8218 * For example, GNU/Linux returns a value based on jiffies and it is monotonic.
8219 * However, 4.4BSD uses gettimeofday() and it is not monotonic.
8220 * (FreeBSD uses +:CLOCK_MONOTONIC+ instead, though.)
8221 *
8222 * The resolution is the clock tick.
8223 * "getconf CLK_TCK" command shows the clock ticks per second.
8224 * (The clock ticks-per-second is defined by HZ macro in older systems.)
8225 * If it is 100 and clock_t is 32 bits integer type,
8226 * the resolution is 10 millisecond and cannot represent over 497 days.
8227 *
8228 * - Emulations for +:CLOCK_PROCESS_CPUTIME_ID+:
8229 *
8230 * - +:GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8231 * Use getrusage() defined by SUS.
8232 * getrusage() is used with RUSAGE_SELF to obtain the time only for
8233 * the calling process (excluding the time for child processes).
8234 * The result is addition of user time (ru_utime) and system time (ru_stime).
8235 * The resolution is 1 microsecond.
8236 * - +:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8237 * Use times() defined by POSIX.
8238 * The result is addition of user time (tms_utime) and system time (tms_stime).
8239 * tms_cutime and tms_cstime are ignored to exclude the time for child processes.
8240 * The resolution is the clock tick.
8241 * "getconf CLK_TCK" command shows the clock ticks per second.
8242 * (The clock ticks per second is defined by HZ macro in older systems.)
8243 * If it is 100, the resolution is 10 millisecond.
8244 * - +:CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID+:
8245 * Use clock() defined by ISO C.
8246 * The resolution is <tt>1/CLOCKS_PER_SEC</tt>.
8247 * +CLOCKS_PER_SEC+ is the C-level macro defined by time.h.
8248 * SUS defines +CLOCKS_PER_SEC+ as 1000000;
8249 * other systems may define it differently.
8250 * If +CLOCKS_PER_SEC+ is 1000000 (as in SUS),
8251 * the resolution is 1 microsecond.
8252 * If +CLOCKS_PER_SEC+ is 1000000 and clock_t is a 32-bit integer type,
8253 * it cannot represent over 72 minutes.
8254 *
8255 * <b>Argument +unit+</b>
8256 *
8257 * Optional argument +unit+ (default +:float_second+)
8258 * specifies the unit for the returned value.
8259 *
8260 * - +:float_microsecond+: Number of microseconds as a float.
8261 * - +:float_millisecond+: Number of milliseconds as a float.
8262 * - +:float_second+: Number of seconds as a float.
8263 * - +:microsecond+: Number of microseconds as an integer.
8264 * - +:millisecond+: Number of milliseconds as an integer.
8265 * - +:nanosecond+: Number of nanoseconds as an integer.
8266 * - +:second+: Number of seconds as an integer.
8267 *
8268 * Examples:
8269 *
8270 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_microsecond)
8271 * # => 203605054.825
8272 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_millisecond)
8273 * # => 203643.696848
8274 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :float_second)
8275 * # => 203.762181929
8276 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :microsecond)
8277 * # => 204123212
8278 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :millisecond)
8279 * # => 204298
8280 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :nanosecond)
8281 * # => 204602286036
8282 * Process.clock_gettime(:CLOCK_PROCESS_CPUTIME_ID, :second)
8283 * # => 204
8284 *
8285 * The underlying function, clock_gettime(), returns a number of nanoseconds.
8286 * Float object (IEEE 754 double) is not enough to represent
8287 * the return value for +:CLOCK_REALTIME+.
8288 * If the exact nanoseconds value is required, use +:nanosecond+ as the +unit+.
8289 *
8290 * The origin (time zero) of the returned value is system-dependent,
8291 * and may be, for example, system start up time,
8292 * process start up time, the Epoch, etc.
8293 *
8294 * The origin in +:CLOCK_REALTIME+ is defined as the Epoch:
8295 * <tt>1970-01-01 00:00:00 UTC</tt>;
8296 * some systems count leap seconds and others don't,
8297 * so the result may vary across systems.
8298 */
8299static VALUE
8300rb_clock_gettime(int argc, VALUE *argv, VALUE _)
8301{
8302 int ret;
8303
8304 struct timetick tt;
8305 timetick_int_t numerators[2];
8306 timetick_int_t denominators[2];
8307 int num_numerators = 0;
8308 int num_denominators = 0;
8309
8310 VALUE unit = (rb_check_arity(argc, 1, 2) == 2) ? argv[1] : Qnil;
8311 VALUE clk_id = argv[0];
8312#ifdef HAVE_CLOCK_GETTIME
8313 clockid_t c;
8314#endif
8315
8316 if (SYMBOL_P(clk_id)) {
8317#ifdef CLOCK_REALTIME
8318 if (clk_id == RUBY_CLOCK_REALTIME) {
8319 c = CLOCK_REALTIME;
8320 goto gettime;
8321 }
8322#endif
8323
8324#ifdef CLOCK_MONOTONIC
8325 if (clk_id == RUBY_CLOCK_MONOTONIC) {
8326 c = CLOCK_MONOTONIC;
8327 goto gettime;
8328 }
8329#endif
8330
8331#ifdef CLOCK_PROCESS_CPUTIME_ID
8332 if (clk_id == RUBY_CLOCK_PROCESS_CPUTIME_ID) {
8333 c = CLOCK_PROCESS_CPUTIME_ID;
8334 goto gettime;
8335 }
8336#endif
8337
8338#ifdef CLOCK_THREAD_CPUTIME_ID
8339 if (clk_id == RUBY_CLOCK_THREAD_CPUTIME_ID) {
8340 c = CLOCK_THREAD_CPUTIME_ID;
8341 goto gettime;
8342 }
8343#endif
8344
8345 /*
8346 * Non-clock_gettime clocks are provided by symbol clk_id.
8347 */
8348#ifdef HAVE_GETTIMEOFDAY
8349 /*
8350 * GETTIMEOFDAY_BASED_CLOCK_REALTIME is used for
8351 * CLOCK_REALTIME if clock_gettime is not available.
8352 */
8353#define RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME ID2SYM(id_GETTIMEOFDAY_BASED_CLOCK_REALTIME)
8354 if (clk_id == RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME) {
8355 struct timeval tv;
8356 ret = gettimeofday(&tv, 0);
8357 if (ret != 0)
8358 rb_sys_fail("gettimeofday");
8359 tt.giga_count = tv.tv_sec;
8360 tt.count = (int32_t)tv.tv_usec * 1000;
8361 denominators[num_denominators++] = 1000000000;
8362 goto success;
8363 }
8364#endif
8365
8366#define RUBY_TIME_BASED_CLOCK_REALTIME ID2SYM(id_TIME_BASED_CLOCK_REALTIME)
8367 if (clk_id == RUBY_TIME_BASED_CLOCK_REALTIME) {
8368 time_t t;
8369 t = time(NULL);
8370 if (t == (time_t)-1)
8371 rb_sys_fail("time");
8372 tt.giga_count = t;
8373 tt.count = 0;
8374 denominators[num_denominators++] = 1000000000;
8375 goto success;
8376 }
8377
8378#ifdef HAVE_TIMES
8379#define RUBY_TIMES_BASED_CLOCK_MONOTONIC \
8380 ID2SYM(id_TIMES_BASED_CLOCK_MONOTONIC)
8381 if (clk_id == RUBY_TIMES_BASED_CLOCK_MONOTONIC) {
8382 struct tms buf;
8383 clock_t c;
8384 unsigned_clock_t uc;
8385 c = times(&buf);
8386 if (c == (clock_t)-1)
8387 rb_sys_fail("times");
8388 uc = (unsigned_clock_t)c;
8389 tt.count = (int32_t)(uc % 1000000000);
8390 tt.giga_count = (uc / 1000000000);
8391 denominators[num_denominators++] = get_clk_tck();
8392 goto success;
8393 }
8394#endif
8395
8396#ifdef RUSAGE_SELF
8397#define RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID \
8398 ID2SYM(id_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID)
8399 if (clk_id == RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8400 struct rusage usage;
8401 int32_t usec;
8402 ret = getrusage(RUSAGE_SELF, &usage);
8403 if (ret != 0)
8404 rb_sys_fail("getrusage");
8405 tt.giga_count = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
8406 usec = (int32_t)(usage.ru_utime.tv_usec + usage.ru_stime.tv_usec);
8407 if (1000000 <= usec) {
8408 tt.giga_count++;
8409 usec -= 1000000;
8410 }
8411 tt.count = usec * 1000;
8412 denominators[num_denominators++] = 1000000000;
8413 goto success;
8414 }
8415#endif
8416
8417#ifdef HAVE_TIMES
8418#define RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID \
8419 ID2SYM(id_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID)
8420 if (clk_id == RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8421 struct tms buf;
8422 unsigned_clock_t utime, stime;
8423 if (times(&buf) == (clock_t)-1)
8424 rb_sys_fail("times");
8425 utime = (unsigned_clock_t)buf.tms_utime;
8426 stime = (unsigned_clock_t)buf.tms_stime;
8427 tt.count = (int32_t)((utime % 1000000000) + (stime % 1000000000));
8428 tt.giga_count = (utime / 1000000000) + (stime / 1000000000);
8429 if (1000000000 <= tt.count) {
8430 tt.count -= 1000000000;
8431 tt.giga_count++;
8432 }
8433 denominators[num_denominators++] = get_clk_tck();
8434 goto success;
8435 }
8436#endif
8437
8438#define RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID \
8439 ID2SYM(id_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID)
8440 if (clk_id == RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8441 clock_t c;
8442 unsigned_clock_t uc;
8443 errno = 0;
8444 c = clock();
8445 if (c == (clock_t)-1)
8446 rb_sys_fail("clock");
8447 uc = (unsigned_clock_t)c;
8448 tt.count = (int32_t)(uc % 1000000000);
8449 tt.giga_count = uc / 1000000000;
8450 denominators[num_denominators++] = CLOCKS_PER_SEC;
8451 goto success;
8452 }
8453
8454#ifdef __APPLE__
8455 if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) {
8456 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8457 uint64_t t = mach_absolute_time();
8458 tt.count = (int32_t)(t % 1000000000);
8459 tt.giga_count = t / 1000000000;
8460 numerators[num_numerators++] = info->numer;
8461 denominators[num_denominators++] = info->denom;
8462 denominators[num_denominators++] = 1000000000;
8463 goto success;
8464 }
8465#endif
8466 }
8467 else if (NUMERIC_CLOCKID) {
8468#if defined(HAVE_CLOCK_GETTIME)
8469 struct timespec ts;
8470 c = NUM2CLOCKID(clk_id);
8471 gettime:
8472 ret = clock_gettime(c, &ts);
8473 if (ret == -1)
8474 clock_failed("gettime", errno, clk_id);
8475 tt.count = (int32_t)ts.tv_nsec;
8476 tt.giga_count = ts.tv_sec;
8477 denominators[num_denominators++] = 1000000000;
8478 goto success;
8479#endif
8480 }
8481 else {
8483 }
8484 clock_failed("gettime", EINVAL, clk_id);
8485
8486 success:
8487 return make_clock_result(&tt, numerators, num_numerators, denominators, num_denominators, unit);
8488}
8489
8490/*
8491 * call-seq:
8492 * Process.clock_getres(clock_id, unit = :float_second) -> number
8493 *
8494 * Returns a clock resolution as determined by POSIX function
8495 * {clock_getres()}[https://man7.org/linux/man-pages/man3/clock_getres.3.html]:
8496 *
8497 * Process.clock_getres(:CLOCK_REALTIME) # => 1.0e-09
8498 *
8499 * See Process.clock_gettime for the values of +clock_id+ and +unit+.
8500 *
8501 * Examples:
8502 *
8503 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_microsecond) # => 0.001
8504 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_millisecond) # => 1.0e-06
8505 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :float_second) # => 1.0e-09
8506 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :microsecond) # => 0
8507 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :millisecond) # => 0
8508 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :nanosecond) # => 1
8509 * Process.clock_getres(:CLOCK_PROCESS_CPUTIME_ID, :second) # => 0
8510 *
8511 * In addition to the values for +unit+ supported in Process.clock_gettime,
8512 * this method supports +:hertz+, the integer number of clock ticks per second
8513 * (which is the reciprocal of +:float_second+):
8514 *
8515 * Process.clock_getres(:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, :hertz) # => 100.0
8516 * Process.clock_getres(:TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID, :float_second) # => 0.01
8517 *
8518 * <b>Accuracy</b>:
8519 * Note that the returned resolution may be inaccurate on some platforms
8520 * due to underlying bugs.
8521 * Inaccurate resolutions have been reported for various clocks including
8522 * +:CLOCK_MONOTONIC+ and +:CLOCK_MONOTONIC_RAW+
8523 * on Linux, macOS, BSD or AIX platforms, when using ARM processors,
8524 * or when using virtualization.
8525 */
8526static VALUE
8527rb_clock_getres(int argc, VALUE *argv, VALUE _)
8528{
8529 int ret;
8530
8531 struct timetick tt;
8532 timetick_int_t numerators[2];
8533 timetick_int_t denominators[2];
8534 int num_numerators = 0;
8535 int num_denominators = 0;
8536#ifdef HAVE_CLOCK_GETRES
8537 clockid_t c;
8538#endif
8539
8540 VALUE unit = (rb_check_arity(argc, 1, 2) == 2) ? argv[1] : Qnil;
8541 VALUE clk_id = argv[0];
8542
8543 if (SYMBOL_P(clk_id)) {
8544#ifdef CLOCK_REALTIME
8545 if (clk_id == RUBY_CLOCK_REALTIME) {
8546 c = CLOCK_REALTIME;
8547 goto getres;
8548 }
8549#endif
8550
8551#ifdef CLOCK_MONOTONIC
8552 if (clk_id == RUBY_CLOCK_MONOTONIC) {
8553 c = CLOCK_MONOTONIC;
8554 goto getres;
8555 }
8556#endif
8557
8558#ifdef CLOCK_PROCESS_CPUTIME_ID
8559 if (clk_id == RUBY_CLOCK_PROCESS_CPUTIME_ID) {
8560 c = CLOCK_PROCESS_CPUTIME_ID;
8561 goto getres;
8562 }
8563#endif
8564
8565#ifdef CLOCK_THREAD_CPUTIME_ID
8566 if (clk_id == RUBY_CLOCK_THREAD_CPUTIME_ID) {
8567 c = CLOCK_THREAD_CPUTIME_ID;
8568 goto getres;
8569 }
8570#endif
8571
8572#ifdef RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME
8573 if (clk_id == RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME) {
8574 tt.giga_count = 0;
8575 tt.count = 1000;
8576 denominators[num_denominators++] = 1000000000;
8577 goto success;
8578 }
8579#endif
8580
8581#ifdef RUBY_TIME_BASED_CLOCK_REALTIME
8582 if (clk_id == RUBY_TIME_BASED_CLOCK_REALTIME) {
8583 tt.giga_count = 1;
8584 tt.count = 0;
8585 denominators[num_denominators++] = 1000000000;
8586 goto success;
8587 }
8588#endif
8589
8590#ifdef RUBY_TIMES_BASED_CLOCK_MONOTONIC
8591 if (clk_id == RUBY_TIMES_BASED_CLOCK_MONOTONIC) {
8592 tt.count = 1;
8593 tt.giga_count = 0;
8594 denominators[num_denominators++] = get_clk_tck();
8595 goto success;
8596 }
8597#endif
8598
8599#ifdef RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
8600 if (clk_id == RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8601 tt.giga_count = 0;
8602 tt.count = 1000;
8603 denominators[num_denominators++] = 1000000000;
8604 goto success;
8605 }
8606#endif
8607
8608#ifdef RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID
8609 if (clk_id == RUBY_TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8610 tt.count = 1;
8611 tt.giga_count = 0;
8612 denominators[num_denominators++] = get_clk_tck();
8613 goto success;
8614 }
8615#endif
8616
8617#ifdef RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID
8618 if (clk_id == RUBY_CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID) {
8619 tt.count = 1;
8620 tt.giga_count = 0;
8621 denominators[num_denominators++] = CLOCKS_PER_SEC;
8622 goto success;
8623 }
8624#endif
8625
8626#ifdef RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
8627 if (clk_id == RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC) {
8628 const mach_timebase_info_data_t *info = get_mach_timebase_info();
8629 tt.count = 1;
8630 tt.giga_count = 0;
8631 numerators[num_numerators++] = info->numer;
8632 denominators[num_denominators++] = info->denom;
8633 denominators[num_denominators++] = 1000000000;
8634 goto success;
8635 }
8636#endif
8637 }
8638 else if (NUMERIC_CLOCKID) {
8639#if defined(HAVE_CLOCK_GETRES)
8640 struct timespec ts;
8641 c = NUM2CLOCKID(clk_id);
8642 getres:
8643 ret = clock_getres(c, &ts);
8644 if (ret == -1)
8645 clock_failed("getres", errno, clk_id);
8646 tt.count = (int32_t)ts.tv_nsec;
8647 tt.giga_count = ts.tv_sec;
8648 denominators[num_denominators++] = 1000000000;
8649 goto success;
8650#endif
8651 }
8652 else {
8654 }
8655 clock_failed("getres", EINVAL, clk_id);
8656
8657 success:
8658 if (unit == ID2SYM(id_hertz)) {
8659 return timetick2dblnum_reciprocal(&tt, numerators, num_numerators, denominators, num_denominators);
8660 }
8661 else {
8662 return make_clock_result(&tt, numerators, num_numerators, denominators, num_denominators, unit);
8663 }
8664}
8665
8666static VALUE
8667get_CHILD_STATUS(ID _x, VALUE *_y)
8668{
8669 return rb_last_status_get();
8670}
8671
8672static VALUE
8673get_PROCESS_ID(ID _x, VALUE *_y)
8674{
8675 return get_pid();
8676}
8677
8678/*
8679 * call-seq:
8680 * Process.kill(signal, *ids) -> count
8681 *
8682 * Sends a signal to each process specified by +ids+
8683 * (which must specify at least one ID);
8684 * returns the count of signals sent.
8685 *
8686 * For each given +id+, if +id+ is:
8687 *
8688 * - Positive, sends the signal to the process whose process ID is +id+.
8689 * - Zero, send the signal to all processes in the current process group.
8690 * - Negative, sends the signal to a system-dependent collection of processes.
8691 *
8692 * Argument +signal+ specifies the signal to be sent;
8693 * the argument may be:
8694 *
8695 * - An integer signal number: e.g., +-29+, +0+, +29+.
8696 * - A signal name (string), with or without leading <tt>'SIG'</tt>,
8697 * and with or without a further prefixed minus sign (<tt>'-'</tt>):
8698 * e.g.:
8699 *
8700 * - <tt>'SIGPOLL'</tt>.
8701 * - <tt>'POLL'</tt>,
8702 * - <tt>'-SIGPOLL'</tt>.
8703 * - <tt>'-POLL'</tt>.
8704 *
8705 * - A signal symbol, with or without leading <tt>'SIG'</tt>,
8706 * and with or without a further prefixed minus sign (<tt>'-'</tt>):
8707 * e.g.:
8708 *
8709 * - +:SIGPOLL+.
8710 * - +:POLL+.
8711 * - <tt>:'-SIGPOLL'</tt>.
8712 * - <tt>:'-POLL'</tt>.
8713 *
8714 * If +signal+ is:
8715 *
8716 * - A non-negative integer, or a signal name or symbol
8717 * without prefixed <tt>'-'</tt>,
8718 * each process with process ID +id+ is signalled.
8719 * - A negative integer, or a signal name or symbol
8720 * with prefixed <tt>'-'</tt>,
8721 * each process group with group ID +id+ is signalled.
8722 *
8723 * Use method Signal.list to see which signals are supported
8724 * by Ruby on the underlying platform;
8725 * the method returns a hash of the string names
8726 * and non-negative integer values of the supported signals.
8727 * The size and content of the returned hash varies widely
8728 * among platforms.
8729 *
8730 * Additionally, signal +0+ is useful to determine if the process exists.
8731 *
8732 * Example:
8733 *
8734 * pid = fork do
8735 * Signal.trap('HUP') { puts 'Ouch!'; exit }
8736 * # ... do some work ...
8737 * end
8738 * # ...
8739 * Process.kill('HUP', pid)
8740 * Process.wait
8741 *
8742 * Output:
8743 *
8744 * Ouch!
8745 *
8746 * Exceptions:
8747 *
8748 * - Raises Errno::EINVAL or RangeError if +signal+ is an integer
8749 * but invalid.
8750 * - Raises ArgumentError if +signal+ is a string or symbol
8751 * but invalid.
8752 * - Raises Errno::ESRCH or RangeError if one of +ids+ is invalid.
8753 * - Raises Errno::EPERM if needed permissions are not in force.
8754 *
8755 * In the last two cases, signals may have been sent to some processes.
8756 */
8757
8758static VALUE
8759proc_rb_f_kill(int c, const VALUE *v, VALUE _)
8760{
8761 return rb_f_kill(c, v);
8762}
8763
8765static VALUE rb_mProcUID;
8766static VALUE rb_mProcGID;
8767static VALUE rb_mProcID_Syscall;
8768
8769/*
8770 * call-seq:
8771 * Process.warmup -> true
8772 *
8773 * Notify the Ruby virtual machine that the boot sequence is finished,
8774 * and that now is a good time to optimize the application. This is useful
8775 * for long running applications.
8776 *
8777 * This method is expected to be called at the end of the application boot.
8778 * If the application is deployed using a pre-forking model, +Process.warmup+
8779 * should be called in the original process before the first fork.
8780 *
8781 * The actual optimizations performed are entirely implementation specific
8782 * and may change in the future without notice.
8783 *
8784 * On CRuby, +Process.warmup+:
8785 *
8786 * * Performs a major GC.
8787 * * Compacts the heap.
8788 * * Promotes all surviving objects to the old generation.
8789 * * Precomputes the coderange of all strings.
8790 * * Frees all empty heap pages and increments the allocatable pages counter
8791 * by the number of pages freed.
8792 * * Invoke +malloc_trim+ if available to free empty malloc pages.
8793 */
8794
8795static VALUE
8796proc_warmup(VALUE _)
8797{
8798 RB_VM_LOCKING() {
8799 rb_gc_prepare_heap();
8800 }
8801 return Qtrue;
8802}
8803
8804/*
8805 * Document-module: Process
8806 *
8807 * Module +Process+ represents a process in the underlying operating system.
8808 * Its methods support management of the current process and its child processes.
8809 *
8810 * == Process Creation
8811 *
8812 * Each of the following methods executes a given command in a new process or subshell,
8813 * or multiple commands in new processes and/or subshells.
8814 * The choice of process or subshell depends on the form of the command;
8815 * see {Argument command_line or exe_path}[rdoc-ref:Process@Argument+command_line+or+exe_path].
8816 *
8817 * - Process.spawn, Kernel#spawn: Executes the command;
8818 * returns the new pid without waiting for completion.
8819 * - Process.exec: Replaces the current process by executing the command.
8820 *
8821 * In addition:
8822 *
8823 * - Method Kernel#system executes a given command-line (string) in a subshell;
8824 * returns +true+, +false+, or +nil+.
8825 * - Method Kernel#` executes a given command-line (string) in a subshell;
8826 * returns its $stdout string.
8827 * - Module Open3 supports creating child processes
8828 * with access to their $stdin, $stdout, and $stderr streams.
8829 *
8830 * === Execution Environment
8831 *
8832 * Optional leading argument +env+ is a hash of name/value pairs,
8833 * where each name is a string and each value is a string or +nil+;
8834 * each name/value pair is added to ENV in the new process.
8835 *
8836 * Process.spawn( 'ruby -e "p ENV[\"Foo\"]"')
8837 * Process.spawn({'Foo' => '0'}, 'ruby -e "p ENV[\"Foo\"]"')
8838 *
8839 * Output:
8840 *
8841 * "0"
8842 *
8843 * The effect is usually similar to that of calling ENV#update with argument +env+,
8844 * where each named environment variable is created or updated
8845 * (if the value is non-+nil+),
8846 * or deleted (if the value is +nil+).
8847 *
8848 * However, some modifications to the calling process may remain
8849 * if the new process fails.
8850 * For example, hard resource limits are not restored.
8851 *
8852 * === Argument +command_line+ or +exe_path+
8853 *
8854 * The required string argument is one of the following:
8855 *
8856 * - +command_line+ if it begins with a shell reserved word or special built-in,
8857 * or if it contains one or more meta characters.
8858 * - +exe_path+ otherwise.
8859 *
8860 * ==== Argument +command_line+
8861 *
8862 * \String argument +command_line+ is a command line to be passed to a shell;
8863 * it must begin with a shell reserved word, begin with a special built-in,
8864 * or contain meta characters:
8865 *
8866 * system('if true; then echo "Foo"; fi') # => true # Shell reserved word.
8867 * system('exit') # => true # Built-in.
8868 * system('date > /tmp/date.tmp') # => true # Contains meta character.
8869 * system('date > /nop/date.tmp') # => false
8870 * system('date > /nop/date.tmp', exception: true) # Raises RuntimeError.
8871 *
8872 * The command line may also contain arguments and options for the command:
8873 *
8874 * system('echo "Foo"') # => true
8875 *
8876 * Output:
8877 *
8878 * Foo
8879 *
8880 * See {Execution Shell}[rdoc-ref:Process@Execution+Shell] for details about the shell.
8881 *
8882 * ==== Argument +exe_path+
8883 *
8884 * Argument +exe_path+ is one of the following:
8885 *
8886 * - The string path to an executable file to be called:
8887 *
8888 * Example:
8889 *
8890 * system('/usr/bin/date') # => true # Path to date on Unix-style system.
8891 * system('foo') # => nil # Command execlution failed.
8892 *
8893 * Output:
8894 *
8895 * Thu Aug 31 10:06:48 AM CDT 2023
8896 *
8897 * A path or command name containing spaces without arguments cannot
8898 * be distinguished from +command_line+ above, so you must quote or
8899 * escape the entire command name using a shell in platform
8900 * dependent manner, or use the array form below.
8901 *
8902 * If +exe_path+ does not contain any path separator, an executable
8903 * file is searched from directories specified with the +PATH+
8904 * environment variable. What the word "executable" means here is
8905 * depending on platforms.
8906 *
8907 * Even if the file considered "executable", its content may not be
8908 * in proper executable format. In that case, Ruby tries to run it
8909 * by using <tt>/bin/sh</tt> on a Unix-like system, like system(3)
8910 * does.
8911 *
8912 * File.write('shell_command', 'echo $SHELL', perm: 0o755)
8913 * system('./shell_command') # prints "/bin/sh" or something.
8914 *
8915 * - A 2-element array containing the path to an executable
8916 * and the string to be used as the name of the executing process:
8917 *
8918 * Example:
8919 *
8920 * pid = spawn(['sleep', 'Hello!'], '1') # 2-element array.
8921 * p `ps -p #{pid} -o command=`
8922 *
8923 * Output:
8924 *
8925 * "Hello! 1\n"
8926 *
8927 * === Arguments +args+
8928 *
8929 * If +command_line+ does not contain shell meta characters except for
8930 * spaces and tabs, or +exe_path+ is given, Ruby invokes the
8931 * executable directly. This form does not use the shell:
8932 *
8933 * spawn("doesnt_exist") # Raises Errno::ENOENT
8934 * spawn("doesnt_exist", "\n") # Raises Errno::ENOENT
8935 *
8936 * spawn("doesnt_exist\n") # => false
8937 * # sh: 1: doesnot_exist: not found
8938 *
8939 * The error message is from a shell and would vary depending on your
8940 * system.
8941 *
8942 * If one or more +args+ is given after +exe_path+, each is an
8943 * argument or option to be passed to the executable:
8944 *
8945 * Example:
8946 *
8947 * system('echo', '<', 'C*', '|', '$SHELL', '>') # => true
8948 *
8949 * Output:
8950 *
8951 * < C* | $SHELL >
8952 *
8953 * However, there are exceptions on Windows. See {Execution Shell on
8954 * Windows}[rdoc-ref:Process@Execution+Shell+on+Windows].
8955 *
8956 * If you want to invoke a path containing spaces with no arguments
8957 * without shell, you will need to use a 2-element array +exe_path+.
8958 *
8959 * Example:
8960 *
8961 * path = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
8962 * spawn(path) # Raises Errno::ENOENT; No such file or directory - /Applications/Google
8963 * spawn([path] * 2)
8964 *
8965 * === Execution Options
8966 *
8967 * Optional trailing argument +options+ is a hash of execution options.
8968 *
8969 * ==== Working Directory (+:chdir+)
8970 *
8971 * By default, the working directory for the new process is the same as
8972 * that of the current process:
8973 *
8974 * Dir.chdir('/var')
8975 * Process.spawn('ruby -e "puts Dir.pwd"')
8976 *
8977 * Output:
8978 *
8979 * /var
8980 *
8981 * Use option +:chdir+ to set the working directory for the new process:
8982 *
8983 * Process.spawn('ruby -e "puts Dir.pwd"', {chdir: '/tmp'})
8984 *
8985 * Output:
8986 *
8987 * /tmp
8988 *
8989 * The working directory of the current process is not changed:
8990 *
8991 * Dir.pwd # => "/var"
8992 *
8993 * ==== \File Redirection (\File Descriptor)
8994 *
8995 * Use execution options for file redirection in the new process.
8996 *
8997 * The key for such an option may be an integer file descriptor (fd),
8998 * specifying a source,
8999 * or an array of fds, specifying multiple sources.
9000 *
9001 * An integer source fd may be specified as:
9002 *
9003 * - _n_: Specifies file descriptor _n_.
9004 *
9005 * There are these shorthand symbols for fds:
9006 *
9007 * - +:in+: Specifies file descriptor 0 (STDIN).
9008 * - +:out+: Specifies file descriptor 1 (STDOUT).
9009 * - +:err+: Specifies file descriptor 2 (STDERR).
9010 *
9011 * The value given with a source is one of:
9012 *
9013 * - _n_:
9014 * Redirects to fd _n_ in the parent process.
9015 * - +filepath+:
9016 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, 0644)</tt>,
9017 * where +mode+ is <tt>'r'</tt> for source +:in+,
9018 * or <tt>'w'</tt> for source +:out+ or +:err+.
9019 * - <tt>[filepath]</tt>:
9020 * Redirects from the file at +filepath+ via <tt>open(filepath, 'r', 0644)</tt>.
9021 * - <tt>[filepath, mode]</tt>:
9022 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, 0644)</tt>.
9023 * - <tt>[filepath, mode, perm]</tt>:
9024 * Redirects from or to the file at +filepath+ via <tt>open(filepath, mode, perm)</tt>.
9025 * - <tt>[:child, fd]</tt>:
9026 * Redirects to the redirected +fd+.
9027 * - +:close+: Closes the file descriptor in child process.
9028 *
9029 * See {Access Modes}[rdoc-ref:File@Access+Modes]
9030 * and {File Permissions}[rdoc-ref:File@File+Permissions].
9031 *
9032 * ==== Environment Variables (+:unsetenv_others+)
9033 *
9034 * By default, the new process inherits environment variables
9035 * from the parent process;
9036 * use execution option key +:unsetenv_others+ with value +true+
9037 * to clear environment variables in the new process.
9038 *
9039 * Any changes specified by execution option +env+ are made after the new process
9040 * inherits or clears its environment variables;
9041 * see {Execution Environment}[rdoc-ref:Process@Execution+Environment].
9042 *
9043 * ==== \File-Creation Access (+:umask+)
9044 *
9045 * Use execution option +:umask+ to set the file-creation access
9046 * for the new process;
9047 * see {Access Modes}[rdoc-ref:File@Access+Modes]:
9048 *
9049 * command = 'ruby -e "puts sprintf(\"0%o\", File.umask)"'
9050 * options = {:umask => 0644}
9051 * Process.spawn(command, options)
9052 *
9053 * Output:
9054 *
9055 * 0644
9056 *
9057 * ==== Process Groups (+:pgroup+ and +:new_pgroup+)
9058 *
9059 * By default, the new process belongs to the same
9060 * {process group}[https://en.wikipedia.org/wiki/Process_group]
9061 * as the parent process.
9062 *
9063 * To specify a different process group.
9064 * use execution option +:pgroup+ with one of the following values:
9065 *
9066 * - +true+: Create a new process group for the new process.
9067 * - _pgid_: Create the new process in the process group
9068 * whose id is _pgid_.
9069 *
9070 * On Windows only, use execution option +:new_pgroup+ with value +true+
9071 * to create a new process group for the new process.
9072 *
9073 * ==== Resource Limits
9074 *
9075 * Use execution options to set resource limits.
9076 *
9077 * The keys for these options are symbols of the form
9078 * <tt>:rlimit_<i>resource_name</i></tt>,
9079 * where _resource_name_ is the downcased form of one of the string
9080 * resource names described at method Process.setrlimit.
9081 * For example, key +:rlimit_cpu+ corresponds to resource limit <tt>'CPU'</tt>.
9082 *
9083 * The value for such as key is one of:
9084 *
9085 * - An integer, specifying both the current and maximum limits.
9086 * - A 2-element array of integers, specifying the current and maximum limits.
9087 *
9088 * ==== \File Descriptor Inheritance
9089 *
9090 * By default, the new process inherits file descriptors from the parent process.
9091 *
9092 * Use execution option <tt>:close_others => true</tt> to modify that inheritance
9093 * by closing non-standard fds (3 and greater) that are not otherwise redirected.
9094 *
9095 * === Execution Shell
9096 *
9097 * On a Unix-like system, the shell invoked is <tt>/bin/sh</tt>;
9098 * the entire string +command_line+ is passed as an argument
9099 * to {shell option -c}[https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/sh.html].
9100 *
9101 * The shell performs normal shell expansion on the command line:
9102 *
9103 * Example:
9104 *
9105 * system('echo $SHELL: C*') # => true
9106 *
9107 * Output:
9108 *
9109 * /bin/bash: CONTRIBUTING.md COPYING COPYING.ja
9110 *
9111 * ==== Execution Shell on Windows
9112 *
9113 * On Windows, the shell invoked is determined by environment variable
9114 * +RUBYSHELL+, if defined, or +COMSPEC+ otherwise; the entire string
9115 * +command_line+ is passed as an argument to <tt>-c</tt> option for
9116 * +RUBYSHELL+, as well as <tt>/bin/sh</tt>, and {/c
9117 * option}[https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd]
9118 * for +COMSPEC+. The shell is invoked automatically in the following
9119 * cases:
9120 *
9121 * - The command is a built-in of +cmd.exe+, such as +echo+.
9122 * - The executable file is a batch file; its name ends with +.bat+ or
9123 * +.cmd+.
9124 *
9125 * Note that the command will still be invoked as +command_line+ form
9126 * even when called in +exe_path+ form, because +cmd.exe+ does not
9127 * accept a script name like <tt>/bin/sh</tt> does but only works with
9128 * <tt>/c</tt> option.
9129 *
9130 * The standard shell +cmd.exe+ performs environment variable
9131 * expansion but does not have globbing functionality:
9132 *
9133 * Example:
9134 *
9135 * system("echo %COMSPEC%: C*")' # => true
9136 *
9137 * Output:
9138 *
9139 * C:\WINDOWS\system32\cmd.exe: C*
9140 *
9141 * == What's Here
9142 *
9143 * === Current-Process Getters
9144 *
9145 * - ::argv0: Returns the process name as a frozen string.
9146 * - ::egid: Returns the effective group ID.
9147 * - ::euid: Returns the effective user ID.
9148 * - ::getpgrp: Return the process group ID.
9149 * - ::getrlimit: Returns the resource limit.
9150 * - ::gid: Returns the (real) group ID.
9151 * - ::pid: Returns the process ID.
9152 * - ::ppid: Returns the process ID of the parent process.
9153 * - ::uid: Returns the (real) user ID.
9154 *
9155 * === Current-Process Setters
9156 *
9157 * - ::egid=: Sets the effective group ID.
9158 * - ::euid=: Sets the effective user ID.
9159 * - ::gid=: Sets the (real) group ID.
9160 * - ::setproctitle: Sets the process title.
9161 * - ::setpgrp: Sets the process group ID of the process to zero.
9162 * - ::setrlimit: Sets a resource limit.
9163 * - ::setsid: Establishes the process as a new session and process group leader,
9164 * with no controlling tty.
9165 * - ::uid=: Sets the user ID.
9166 *
9167 * === Current-Process Execution
9168 *
9169 * - ::abort: Immediately terminates the process.
9170 * - ::daemon: Detaches the process from its controlling terminal
9171 * and continues running it in the background as system daemon.
9172 * - ::exec: Replaces the process by running a given external command.
9173 * - ::exit: Initiates process termination by raising exception SystemExit
9174 * (which may be caught).
9175 * - ::exit!: Immediately exits the process.
9176 * - ::warmup: Notifies the Ruby virtual machine that the boot sequence
9177 * for the application is completed,
9178 * and that the VM may begin optimizing the application.
9179 *
9180 * === Child Processes
9181 *
9182 * - ::detach: Guards against a child process becoming a zombie.
9183 * - ::fork: Creates a child process.
9184 * - ::kill: Sends a given signal to processes.
9185 * - ::spawn: Creates a child process.
9186 * - ::wait, ::waitpid: Waits for a child process to exit; returns its process ID.
9187 * - ::wait2, ::waitpid2: Waits for a child process to exit; returns its process ID and status.
9188 * - ::waitall: Waits for all child processes to exit;
9189 * returns their process IDs and statuses.
9190 *
9191 * === Process Groups
9192 *
9193 * - ::getpgid: Returns the process group ID for a process.
9194 * - ::getpriority: Returns the scheduling priority
9195 * for a process, process group, or user.
9196 * - ::getsid: Returns the session ID for a process.
9197 * - ::groups: Returns an array of the group IDs
9198 * in the supplemental group access list for this process.
9199 * - ::groups=: Sets the supplemental group access list
9200 * to the given array of group IDs.
9201 * - ::initgroups: Initializes the supplemental group access list.
9202 * - ::last_status: Returns the status of the last executed child process
9203 * in the current thread.
9204 * - ::maxgroups: Returns the maximum number of group IDs allowed
9205 * in the supplemental group access list.
9206 * - ::maxgroups=: Sets the maximum number of group IDs allowed
9207 * in the supplemental group access list.
9208 * - ::setpgid: Sets the process group ID of a process.
9209 * - ::setpriority: Sets the scheduling priority
9210 * for a process, process group, or user.
9211 *
9212 * === Timing
9213 *
9214 * - ::clock_getres: Returns the resolution of a system clock.
9215 * - ::clock_gettime: Returns the time from a system clock.
9216 * - ::times: Returns a Process::Tms object containing times
9217 * for the current process and its child processes.
9218 *
9219 */
9220
9221void
9222InitVM_process(void)
9223{
9224 rb_define_virtual_variable("$?", get_CHILD_STATUS, 0);
9225 rb_define_virtual_variable("$$", get_PROCESS_ID, 0);
9226
9227 rb_gvar_ractor_local("$$");
9228 rb_gvar_ractor_local("$?");
9229
9230 rb_define_global_function("exec", f_exec, -1);
9231 rb_define_global_function("fork", rb_f_fork, 0);
9232 rb_define_global_function("exit!", rb_f_exit_bang, -1);
9233 rb_define_global_function("system", rb_f_system, -1);
9234 rb_define_global_function("spawn", rb_f_spawn, -1);
9235 rb_define_global_function("sleep", rb_f_sleep, -1);
9236 rb_define_global_function("exit", f_exit, -1);
9237 rb_define_global_function("abort", f_abort, -1);
9238
9239 rb_mProcess = rb_define_module("Process");
9240
9241#ifdef WNOHANG
9242 /* see Process.wait */
9243 rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(WNOHANG));
9244#else
9245 /* see Process.wait */
9246 rb_define_const(rb_mProcess, "WNOHANG", INT2FIX(0));
9247#endif
9248#ifdef WUNTRACED
9249 /* see Process.wait */
9250 rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(WUNTRACED));
9251#else
9252 /* see Process.wait */
9253 rb_define_const(rb_mProcess, "WUNTRACED", INT2FIX(0));
9254#endif
9255
9256 rb_define_singleton_method(rb_mProcess, "exec", f_exec, -1);
9257 rb_define_singleton_method(rb_mProcess, "fork", rb_f_fork, 0);
9258 rb_define_singleton_method(rb_mProcess, "spawn", rb_f_spawn, -1);
9259 rb_define_singleton_method(rb_mProcess, "exit!", rb_f_exit_bang, -1);
9260 rb_define_singleton_method(rb_mProcess, "exit", f_exit, -1);
9261 rb_define_singleton_method(rb_mProcess, "abort", f_abort, -1);
9262 rb_define_singleton_method(rb_mProcess, "last_status", proc_s_last_status, 0);
9263 rb_define_singleton_method(rb_mProcess, "_fork", rb_proc__fork, 0);
9264
9265 rb_define_module_function(rb_mProcess, "kill", proc_rb_f_kill, -1);
9266 rb_define_module_function(rb_mProcess, "wait", proc_m_wait, -1);
9267 rb_define_module_function(rb_mProcess, "wait2", proc_wait2, -1);
9268 rb_define_module_function(rb_mProcess, "waitpid", proc_m_wait, -1);
9269 rb_define_module_function(rb_mProcess, "waitpid2", proc_wait2, -1);
9270 rb_define_module_function(rb_mProcess, "waitall", proc_waitall, 0);
9271 rb_define_module_function(rb_mProcess, "detach", proc_detach, 1);
9272
9273 /* :nodoc: */
9274 rb_cWaiter = rb_define_class_under(rb_mProcess, "Waiter", rb_cThread);
9275 rb_undef_alloc_func(rb_cWaiter);
9276 rb_undef_method(CLASS_OF(rb_cWaiter), "new");
9277 rb_define_method(rb_cWaiter, "pid", detach_process_pid, 0);
9278
9279 rb_cProcessStatus = rb_define_class_under(rb_mProcess, "Status", rb_cObject);
9280 rb_define_alloc_func(rb_cProcessStatus, rb_process_status_allocate);
9281 rb_undef_method(CLASS_OF(rb_cProcessStatus), "new");
9282 rb_marshal_define_compat(rb_cProcessStatus, rb_cObject,
9283 process_status_dump, process_status_load);
9284
9285 rb_define_singleton_method(rb_cProcessStatus, "wait", rb_process_status_waitv, -1);
9286
9287 rb_define_method(rb_cProcessStatus, "==", pst_equal, 1);
9288 rb_define_method(rb_cProcessStatus, "to_i", pst_to_i, 0);
9289 rb_define_method(rb_cProcessStatus, "to_s", pst_to_s, 0);
9290 rb_define_method(rb_cProcessStatus, "inspect", pst_inspect, 0);
9291
9292 rb_define_method(rb_cProcessStatus, "pid", pst_pid_m, 0);
9293
9294 rb_define_method(rb_cProcessStatus, "stopped?", pst_wifstopped, 0);
9295 rb_define_method(rb_cProcessStatus, "stopsig", pst_wstopsig, 0);
9296 rb_define_method(rb_cProcessStatus, "signaled?", pst_wifsignaled, 0);
9297 rb_define_method(rb_cProcessStatus, "termsig", pst_wtermsig, 0);
9298 rb_define_method(rb_cProcessStatus, "exited?", pst_wifexited, 0);
9299 rb_define_method(rb_cProcessStatus, "exitstatus", pst_wexitstatus, 0);
9300 rb_define_method(rb_cProcessStatus, "success?", pst_success_p, 0);
9301 rb_define_method(rb_cProcessStatus, "coredump?", pst_wcoredump, 0);
9302
9303 rb_define_module_function(rb_mProcess, "pid", proc_get_pid, 0);
9304 rb_define_module_function(rb_mProcess, "ppid", proc_get_ppid, 0);
9305
9306 rb_define_module_function(rb_mProcess, "getpgrp", proc_getpgrp, 0);
9307 rb_define_module_function(rb_mProcess, "setpgrp", proc_setpgrp, 0);
9308 rb_define_module_function(rb_mProcess, "getpgid", proc_getpgid, 1);
9309 rb_define_module_function(rb_mProcess, "setpgid", proc_setpgid, 2);
9310
9311 rb_define_module_function(rb_mProcess, "getsid", proc_getsid, -1);
9312 rb_define_module_function(rb_mProcess, "setsid", proc_setsid, 0);
9313
9314 rb_define_module_function(rb_mProcess, "getpriority", proc_getpriority, 2);
9315 rb_define_module_function(rb_mProcess, "setpriority", proc_setpriority, 3);
9316
9317 rb_define_module_function(rb_mProcess, "warmup", proc_warmup, 0);
9318
9319#ifdef HAVE_GETPRIORITY
9320 /* see Process.setpriority */
9321 rb_define_const(rb_mProcess, "PRIO_PROCESS", INT2FIX(PRIO_PROCESS));
9322 /* see Process.setpriority */
9323 rb_define_const(rb_mProcess, "PRIO_PGRP", INT2FIX(PRIO_PGRP));
9324 /* see Process.setpriority */
9325 rb_define_const(rb_mProcess, "PRIO_USER", INT2FIX(PRIO_USER));
9326#endif
9327
9328 rb_define_module_function(rb_mProcess, "getrlimit", proc_getrlimit, 1);
9329 rb_define_module_function(rb_mProcess, "setrlimit", proc_setrlimit, -1);
9330#if defined(RLIM2NUM) && defined(RLIM_INFINITY)
9331 {
9332 VALUE inf = RLIM2NUM(RLIM_INFINITY);
9333#ifdef RLIM_SAVED_MAX
9334 {
9335 VALUE v = RLIM_INFINITY == RLIM_SAVED_MAX ? inf : RLIM2NUM(RLIM_SAVED_MAX);
9336 /* see Process.setrlimit */
9337 rb_define_const(rb_mProcess, "RLIM_SAVED_MAX", v);
9338 }
9339#endif
9340 /* see Process.setrlimit */
9341 rb_define_const(rb_mProcess, "RLIM_INFINITY", inf);
9342#ifdef RLIM_SAVED_CUR
9343 {
9344 VALUE v = RLIM_INFINITY == RLIM_SAVED_CUR ? inf : RLIM2NUM(RLIM_SAVED_CUR);
9345 /* see Process.setrlimit */
9346 rb_define_const(rb_mProcess, "RLIM_SAVED_CUR", v);
9347 }
9348#endif
9349 }
9350#ifdef RLIMIT_AS
9351 /* Maximum size of the process's virtual memory (address space) in bytes.
9352 *
9353 * see the system getrlimit(2) manual for details.
9354 */
9355 rb_define_const(rb_mProcess, "RLIMIT_AS", INT2FIX(RLIMIT_AS));
9356#endif
9357#ifdef RLIMIT_CORE
9358 /* Maximum size of the core file.
9359 *
9360 * see the system getrlimit(2) manual for details.
9361 */
9362 rb_define_const(rb_mProcess, "RLIMIT_CORE", INT2FIX(RLIMIT_CORE));
9363#endif
9364#ifdef RLIMIT_CPU
9365 /* CPU time limit in seconds.
9366 *
9367 * see the system getrlimit(2) manual for details.
9368 */
9369 rb_define_const(rb_mProcess, "RLIMIT_CPU", INT2FIX(RLIMIT_CPU));
9370#endif
9371#ifdef RLIMIT_DATA
9372 /* Maximum size of the process's data segment.
9373 *
9374 * see the system getrlimit(2) manual for details.
9375 */
9376 rb_define_const(rb_mProcess, "RLIMIT_DATA", INT2FIX(RLIMIT_DATA));
9377#endif
9378#ifdef RLIMIT_FSIZE
9379 /* Maximum size of files that the process may create.
9380 *
9381 * see the system getrlimit(2) manual for details.
9382 */
9383 rb_define_const(rb_mProcess, "RLIMIT_FSIZE", INT2FIX(RLIMIT_FSIZE));
9384#endif
9385#ifdef RLIMIT_MEMLOCK
9386 /* Maximum number of bytes of memory that may be locked into RAM.
9387 *
9388 * see the system getrlimit(2) manual for details.
9389 */
9390 rb_define_const(rb_mProcess, "RLIMIT_MEMLOCK", INT2FIX(RLIMIT_MEMLOCK));
9391#endif
9392#ifdef RLIMIT_MSGQUEUE
9393 /* Specifies the limit on the number of bytes that can be allocated
9394 * for POSIX message queues for the real user ID of the calling process.
9395 *
9396 * see the system getrlimit(2) manual for details.
9397 */
9398 rb_define_const(rb_mProcess, "RLIMIT_MSGQUEUE", INT2FIX(RLIMIT_MSGQUEUE));
9399#endif
9400#ifdef RLIMIT_NICE
9401 /* Specifies a ceiling to which the process's nice value can be raised.
9402 *
9403 * see the system getrlimit(2) manual for details.
9404 */
9405 rb_define_const(rb_mProcess, "RLIMIT_NICE", INT2FIX(RLIMIT_NICE));
9406#endif
9407#ifdef RLIMIT_NOFILE
9408 /* Specifies a value one greater than the maximum file descriptor
9409 * number that can be opened by this process.
9410 *
9411 * see the system getrlimit(2) manual for details.
9412 */
9413 rb_define_const(rb_mProcess, "RLIMIT_NOFILE", INT2FIX(RLIMIT_NOFILE));
9414#endif
9415#ifdef RLIMIT_NPROC
9416 /* The maximum number of processes that can be created for the
9417 * real user ID of the calling process.
9418 *
9419 * see the system getrlimit(2) manual for details.
9420 */
9421 rb_define_const(rb_mProcess, "RLIMIT_NPROC", INT2FIX(RLIMIT_NPROC));
9422#endif
9423#ifdef RLIMIT_NPTS
9424 /* The maximum number of pseudo-terminals that can be created for the
9425 * real user ID of the calling process.
9426 *
9427 * see the system getrlimit(2) manual for details.
9428 */
9429 rb_define_const(rb_mProcess, "RLIMIT_NPTS", INT2FIX(RLIMIT_NPTS));
9430#endif
9431#ifdef RLIMIT_RSS
9432 /* Specifies the limit (in pages) of the process's resident set.
9433 *
9434 * see the system getrlimit(2) manual for details.
9435 */
9436 rb_define_const(rb_mProcess, "RLIMIT_RSS", INT2FIX(RLIMIT_RSS));
9437#endif
9438#ifdef RLIMIT_RTPRIO
9439 /* Specifies a ceiling on the real-time priority that may be set for this process.
9440 *
9441 * see the system getrlimit(2) manual for details.
9442 */
9443 rb_define_const(rb_mProcess, "RLIMIT_RTPRIO", INT2FIX(RLIMIT_RTPRIO));
9444#endif
9445#ifdef RLIMIT_RTTIME
9446 /* Specifies limit on CPU time this process scheduled under a real-time
9447 * scheduling policy can consume.
9448 *
9449 * see the system getrlimit(2) manual for details.
9450 */
9451 rb_define_const(rb_mProcess, "RLIMIT_RTTIME", INT2FIX(RLIMIT_RTTIME));
9452#endif
9453#ifdef RLIMIT_SBSIZE
9454 /* Maximum size of the socket buffer.
9455 */
9456 rb_define_const(rb_mProcess, "RLIMIT_SBSIZE", INT2FIX(RLIMIT_SBSIZE));
9457#endif
9458#ifdef RLIMIT_SIGPENDING
9459 /* Specifies a limit on the number of signals that may be queued for
9460 * the real user ID of the calling process.
9461 *
9462 * see the system getrlimit(2) manual for details.
9463 */
9464 rb_define_const(rb_mProcess, "RLIMIT_SIGPENDING", INT2FIX(RLIMIT_SIGPENDING));
9465#endif
9466#ifdef RLIMIT_STACK
9467 /* Maximum size of the stack, in bytes.
9468 *
9469 * see the system getrlimit(2) manual for details.
9470 */
9471 rb_define_const(rb_mProcess, "RLIMIT_STACK", INT2FIX(RLIMIT_STACK));
9472#endif
9473#endif
9474
9475 rb_define_module_function(rb_mProcess, "uid", proc_getuid, 0);
9476 rb_define_module_function(rb_mProcess, "uid=", proc_setuid, 1);
9477 rb_define_module_function(rb_mProcess, "gid", proc_getgid, 0);
9478 rb_define_module_function(rb_mProcess, "gid=", proc_setgid, 1);
9479 rb_define_module_function(rb_mProcess, "euid", proc_geteuid, 0);
9480 rb_define_module_function(rb_mProcess, "euid=", proc_seteuid_m, 1);
9481 rb_define_module_function(rb_mProcess, "egid", proc_getegid, 0);
9482 rb_define_module_function(rb_mProcess, "egid=", proc_setegid_m, 1);
9483 rb_define_module_function(rb_mProcess, "initgroups", proc_initgroups, 2);
9484 rb_define_module_function(rb_mProcess, "groups", proc_getgroups, 0);
9485 rb_define_module_function(rb_mProcess, "groups=", proc_setgroups, 1);
9486 rb_define_module_function(rb_mProcess, "maxgroups", proc_getmaxgroups, 0);
9487 rb_define_module_function(rb_mProcess, "maxgroups=", proc_setmaxgroups, 1);
9488
9489 rb_define_module_function(rb_mProcess, "daemon", proc_daemon, -1);
9490
9491 rb_define_module_function(rb_mProcess, "times", rb_proc_times, 0);
9492
9493#if defined(RUBY_CLOCK_REALTIME)
9494#elif defined(RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME)
9495# define RUBY_CLOCK_REALTIME RUBY_GETTIMEOFDAY_BASED_CLOCK_REALTIME
9496#elif defined(RUBY_TIME_BASED_CLOCK_REALTIME)
9497# define RUBY_CLOCK_REALTIME RUBY_TIME_BASED_CLOCK_REALTIME
9498#endif
9499#if defined(CLOCK_REALTIME) && defined(CLOCKID2NUM)
9500 /* see Process.clock_gettime */
9501 rb_define_const(rb_mProcess, "CLOCK_REALTIME", CLOCKID2NUM(CLOCK_REALTIME));
9502#elif defined(RUBY_CLOCK_REALTIME)
9503 rb_define_const(rb_mProcess, "CLOCK_REALTIME", RUBY_CLOCK_REALTIME);
9504#endif
9505
9506#if defined(RUBY_CLOCK_MONOTONIC)
9507#elif defined(RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC)
9508# define RUBY_CLOCK_MONOTONIC RUBY_MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC
9509#endif
9510#if defined(CLOCK_MONOTONIC) && defined(CLOCKID2NUM)
9511 /* see Process.clock_gettime */
9512 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC", CLOCKID2NUM(CLOCK_MONOTONIC));
9513#elif defined(RUBY_CLOCK_MONOTONIC)
9514 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC", RUBY_CLOCK_MONOTONIC);
9515#endif
9516
9517#if defined(RUBY_CLOCK_PROCESS_CPUTIME_ID)
9518#elif defined(RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID)
9519# define RUBY_CLOCK_PROCESS_CPUTIME_ID RUBY_GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID
9520#endif
9521#if defined(CLOCK_PROCESS_CPUTIME_ID) && defined(CLOCKID2NUM)
9522 /* see Process.clock_gettime */
9523 rb_define_const(rb_mProcess, "CLOCK_PROCESS_CPUTIME_ID", CLOCKID2NUM(CLOCK_PROCESS_CPUTIME_ID));
9524#elif defined(RUBY_CLOCK_PROCESS_CPUTIME_ID)
9525 rb_define_const(rb_mProcess, "CLOCK_PROCESS_CPUTIME_ID", RUBY_CLOCK_PROCESS_CPUTIME_ID);
9526#endif
9527
9528#if defined(CLOCK_THREAD_CPUTIME_ID) && defined(CLOCKID2NUM)
9529 /* see Process.clock_gettime */
9530 rb_define_const(rb_mProcess, "CLOCK_THREAD_CPUTIME_ID", CLOCKID2NUM(CLOCK_THREAD_CPUTIME_ID));
9531#elif defined(RUBY_CLOCK_THREAD_CPUTIME_ID)
9532 rb_define_const(rb_mProcess, "CLOCK_THREAD_CPUTIME_ID", RUBY_CLOCK_THREAD_CPUTIME_ID);
9533#endif
9534
9535#ifdef CLOCKID2NUM
9536#ifdef CLOCK_VIRTUAL
9537 /* see Process.clock_gettime */
9538 rb_define_const(rb_mProcess, "CLOCK_VIRTUAL", CLOCKID2NUM(CLOCK_VIRTUAL));
9539#endif
9540#ifdef CLOCK_PROF
9541 /* see Process.clock_gettime */
9542 rb_define_const(rb_mProcess, "CLOCK_PROF", CLOCKID2NUM(CLOCK_PROF));
9543#endif
9544#ifdef CLOCK_REALTIME_FAST
9545 /* see Process.clock_gettime */
9546 rb_define_const(rb_mProcess, "CLOCK_REALTIME_FAST", CLOCKID2NUM(CLOCK_REALTIME_FAST));
9547#endif
9548#ifdef CLOCK_REALTIME_PRECISE
9549 /* see Process.clock_gettime */
9550 rb_define_const(rb_mProcess, "CLOCK_REALTIME_PRECISE", CLOCKID2NUM(CLOCK_REALTIME_PRECISE));
9551#endif
9552#ifdef CLOCK_REALTIME_COARSE
9553 /* see Process.clock_gettime */
9554 rb_define_const(rb_mProcess, "CLOCK_REALTIME_COARSE", CLOCKID2NUM(CLOCK_REALTIME_COARSE));
9555#endif
9556#ifdef CLOCK_REALTIME_ALARM
9557 /* see Process.clock_gettime */
9558 rb_define_const(rb_mProcess, "CLOCK_REALTIME_ALARM", CLOCKID2NUM(CLOCK_REALTIME_ALARM));
9559#endif
9560#ifdef CLOCK_MONOTONIC_FAST
9561 /* see Process.clock_gettime */
9562 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_FAST", CLOCKID2NUM(CLOCK_MONOTONIC_FAST));
9563#endif
9564#ifdef CLOCK_MONOTONIC_PRECISE
9565 /* see Process.clock_gettime */
9566 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_PRECISE", CLOCKID2NUM(CLOCK_MONOTONIC_PRECISE));
9567#endif
9568#ifdef CLOCK_MONOTONIC_RAW
9569 /* see Process.clock_gettime */
9570 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_RAW", CLOCKID2NUM(CLOCK_MONOTONIC_RAW));
9571#endif
9572#ifdef CLOCK_MONOTONIC_RAW_APPROX
9573 /* see Process.clock_gettime */
9574 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_RAW_APPROX", CLOCKID2NUM(CLOCK_MONOTONIC_RAW_APPROX));
9575#endif
9576#ifdef CLOCK_MONOTONIC_COARSE
9577 /* see Process.clock_gettime */
9578 rb_define_const(rb_mProcess, "CLOCK_MONOTONIC_COARSE", CLOCKID2NUM(CLOCK_MONOTONIC_COARSE));
9579#endif
9580#ifdef CLOCK_BOOTTIME
9581 /* see Process.clock_gettime */
9582 rb_define_const(rb_mProcess, "CLOCK_BOOTTIME", CLOCKID2NUM(CLOCK_BOOTTIME));
9583#endif
9584#ifdef CLOCK_BOOTTIME_ALARM
9585 /* see Process.clock_gettime */
9586 rb_define_const(rb_mProcess, "CLOCK_BOOTTIME_ALARM", CLOCKID2NUM(CLOCK_BOOTTIME_ALARM));
9587#endif
9588#ifdef CLOCK_UPTIME
9589 /* see Process.clock_gettime */
9590 rb_define_const(rb_mProcess, "CLOCK_UPTIME", CLOCKID2NUM(CLOCK_UPTIME));
9591#endif
9592#ifdef CLOCK_UPTIME_FAST
9593 /* see Process.clock_gettime */
9594 rb_define_const(rb_mProcess, "CLOCK_UPTIME_FAST", CLOCKID2NUM(CLOCK_UPTIME_FAST));
9595#endif
9596#ifdef CLOCK_UPTIME_PRECISE
9597 /* see Process.clock_gettime */
9598 rb_define_const(rb_mProcess, "CLOCK_UPTIME_PRECISE", CLOCKID2NUM(CLOCK_UPTIME_PRECISE));
9599#endif
9600#ifdef CLOCK_UPTIME_RAW
9601 /* see Process.clock_gettime */
9602 rb_define_const(rb_mProcess, "CLOCK_UPTIME_RAW", CLOCKID2NUM(CLOCK_UPTIME_RAW));
9603#endif
9604#ifdef CLOCK_UPTIME_RAW_APPROX
9605 /* see Process.clock_gettime */
9606 rb_define_const(rb_mProcess, "CLOCK_UPTIME_RAW_APPROX", CLOCKID2NUM(CLOCK_UPTIME_RAW_APPROX));
9607#endif
9608#ifdef CLOCK_SECOND
9609 /* see Process.clock_gettime */
9610 rb_define_const(rb_mProcess, "CLOCK_SECOND", CLOCKID2NUM(CLOCK_SECOND));
9611#endif
9612#ifdef CLOCK_TAI
9613 /* see Process.clock_gettime */
9614 rb_define_const(rb_mProcess, "CLOCK_TAI", CLOCKID2NUM(CLOCK_TAI));
9615#endif
9616#endif
9617 rb_define_module_function(rb_mProcess, "clock_gettime", rb_clock_gettime, -1);
9618 rb_define_module_function(rb_mProcess, "clock_getres", rb_clock_getres, -1);
9619
9620#if defined(HAVE_TIMES) || defined(_WIN32)
9621 rb_cProcessTms = rb_struct_define_under(rb_mProcess, "Tms", "utime", "stime", "cutime", "cstime", NULL);
9622#if 0 /* for RDoc */
9623 /* user time used in this process */
9624 rb_define_attr(rb_cProcessTms, "utime", TRUE, TRUE);
9625 /* system time used in this process */
9626 rb_define_attr(rb_cProcessTms, "stime", TRUE, TRUE);
9627 /* user time used in the child processes */
9628 rb_define_attr(rb_cProcessTms, "cutime", TRUE, TRUE);
9629 /* system time used in the child processes */
9630 rb_define_attr(rb_cProcessTms, "cstime", TRUE, TRUE);
9631#endif
9632#endif
9633
9634 SAVED_USER_ID = geteuid();
9635 SAVED_GROUP_ID = getegid();
9636
9637 rb_mProcUID = rb_define_module_under(rb_mProcess, "UID");
9638 rb_mProcGID = rb_define_module_under(rb_mProcess, "GID");
9639
9640 rb_define_module_function(rb_mProcUID, "rid", proc_getuid, 0);
9641 rb_define_module_function(rb_mProcGID, "rid", proc_getgid, 0);
9642 rb_define_module_function(rb_mProcUID, "eid", proc_geteuid, 0);
9643 rb_define_module_function(rb_mProcGID, "eid", proc_getegid, 0);
9644 rb_define_module_function(rb_mProcUID, "change_privilege", p_uid_change_privilege, 1);
9645 rb_define_module_function(rb_mProcGID, "change_privilege", p_gid_change_privilege, 1);
9646 rb_define_module_function(rb_mProcUID, "grant_privilege", p_uid_grant_privilege, 1);
9647 rb_define_module_function(rb_mProcGID, "grant_privilege", p_gid_grant_privilege, 1);
9648 rb_define_alias(rb_singleton_class(rb_mProcUID), "eid=", "grant_privilege");
9649 rb_define_alias(rb_singleton_class(rb_mProcGID), "eid=", "grant_privilege");
9650 rb_define_module_function(rb_mProcUID, "re_exchange", p_uid_exchange, 0);
9651 rb_define_module_function(rb_mProcGID, "re_exchange", p_gid_exchange, 0);
9652 rb_define_module_function(rb_mProcUID, "re_exchangeable?", p_uid_exchangeable, 0);
9653 rb_define_module_function(rb_mProcGID, "re_exchangeable?", p_gid_exchangeable, 0);
9654 rb_define_module_function(rb_mProcUID, "sid_available?", p_uid_have_saved_id, 0);
9655 rb_define_module_function(rb_mProcGID, "sid_available?", p_gid_have_saved_id, 0);
9656 rb_define_module_function(rb_mProcUID, "switch", p_uid_switch, 0);
9657 rb_define_module_function(rb_mProcGID, "switch", p_gid_switch, 0);
9658#ifdef p_uid_from_name
9659 rb_define_module_function(rb_mProcUID, "from_name", p_uid_from_name, 1);
9660#endif
9661#ifdef p_gid_from_name
9662 rb_define_module_function(rb_mProcGID, "from_name", p_gid_from_name, 1);
9663#endif
9664
9665 rb_mProcID_Syscall = rb_define_module_under(rb_mProcess, "Sys");
9666
9667 rb_define_module_function(rb_mProcID_Syscall, "getuid", proc_getuid, 0);
9668 rb_define_module_function(rb_mProcID_Syscall, "geteuid", proc_geteuid, 0);
9669 rb_define_module_function(rb_mProcID_Syscall, "getgid", proc_getgid, 0);
9670 rb_define_module_function(rb_mProcID_Syscall, "getegid", proc_getegid, 0);
9671
9672 rb_define_module_function(rb_mProcID_Syscall, "setuid", p_sys_setuid, 1);
9673 rb_define_module_function(rb_mProcID_Syscall, "setgid", p_sys_setgid, 1);
9674
9675 rb_define_module_function(rb_mProcID_Syscall, "setruid", p_sys_setruid, 1);
9676 rb_define_module_function(rb_mProcID_Syscall, "setrgid", p_sys_setrgid, 1);
9677
9678 rb_define_module_function(rb_mProcID_Syscall, "seteuid", p_sys_seteuid, 1);
9679 rb_define_module_function(rb_mProcID_Syscall, "setegid", p_sys_setegid, 1);
9680
9681 rb_define_module_function(rb_mProcID_Syscall, "setreuid", p_sys_setreuid, 2);
9682 rb_define_module_function(rb_mProcID_Syscall, "setregid", p_sys_setregid, 2);
9683
9684 rb_define_module_function(rb_mProcID_Syscall, "setresuid", p_sys_setresuid, 3);
9685 rb_define_module_function(rb_mProcID_Syscall, "setresgid", p_sys_setresgid, 3);
9686 rb_define_module_function(rb_mProcID_Syscall, "issetugid", p_sys_issetugid, 0);
9687}
9688
9689void
9690Init_process(void)
9691{
9692#define define_id(name) id_##name = rb_intern_const(#name)
9693 define_id(in);
9694 define_id(out);
9695 define_id(err);
9696 define_id(pid);
9697 define_id(uid);
9698 define_id(gid);
9699 define_id(close);
9700 define_id(child);
9701#ifdef HAVE_SETPGID
9702 define_id(pgroup);
9703#endif
9704#ifdef _WIN32
9705 define_id(new_pgroup);
9706#endif
9707 define_id(unsetenv_others);
9708 define_id(chdir);
9709 define_id(umask);
9710 define_id(close_others);
9711 define_id(nanosecond);
9712 define_id(microsecond);
9713 define_id(millisecond);
9714 define_id(second);
9715 define_id(float_microsecond);
9716 define_id(float_millisecond);
9717 define_id(float_second);
9718 define_id(GETTIMEOFDAY_BASED_CLOCK_REALTIME);
9719 define_id(TIME_BASED_CLOCK_REALTIME);
9720#ifdef CLOCK_REALTIME
9721 define_id(CLOCK_REALTIME);
9722#endif
9723#ifdef CLOCK_MONOTONIC
9724 define_id(CLOCK_MONOTONIC);
9725#endif
9726#ifdef CLOCK_PROCESS_CPUTIME_ID
9727 define_id(CLOCK_PROCESS_CPUTIME_ID);
9728#endif
9729#ifdef CLOCK_THREAD_CPUTIME_ID
9730 define_id(CLOCK_THREAD_CPUTIME_ID);
9731#endif
9732#ifdef HAVE_TIMES
9733 define_id(TIMES_BASED_CLOCK_MONOTONIC);
9734 define_id(TIMES_BASED_CLOCK_PROCESS_CPUTIME_ID);
9735#endif
9736#ifdef RUSAGE_SELF
9737 define_id(GETRUSAGE_BASED_CLOCK_PROCESS_CPUTIME_ID);
9738#endif
9739 define_id(CLOCK_BASED_CLOCK_PROCESS_CPUTIME_ID);
9740#ifdef __APPLE__
9741 define_id(MACH_ABSOLUTE_TIME_BASED_CLOCK_MONOTONIC);
9742#endif
9743 define_id(hertz);
9744#ifdef HAVE_WORKING_FORK
9745 define_id(_fork);
9746#endif
9747
9748 InitVM(process);
9749}
#define LONG_LONG
Definition long_long.h:38
#define ISUPPER
@old{rb_isupper}
Definition ctype.h:89
#define TOUPPER
@old{rb_toupper}
Definition ctype.h:100
#define ISLOWER
@old{rb_islower}
Definition ctype.h:90
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_module_function(klass, mid, func, arity)
Defines klass#mid and makes it a module function.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define PATH_ENV
Definition dosish.h:63
#define GIDT2NUM
Converts a C's gid_t into an instance of rb_cInteger.
Definition gid_t.h:28
#define NUM2GIDT
Converts an instance of rb_cNumeric into C's gid_t.
Definition gid_t.h:33
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2825
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1601
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1624
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2868
void rb_define_attr(VALUE klass, const char *name, int read, int write)
Defines public accessor method(s) for an attribute.
Definition class.c:2874
void rb_undef_method(VALUE klass, const char *name)
Defines an undef of a method.
Definition class.c:2680
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1027
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define NUM2UINT
Old name of RB_NUM2UINT.
Definition int.h:45
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define T_SYMBOL
Old name of RUBY_T_SYMBOL.
Definition value_type.h:80
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
#define SYMBOL_P
Old name of RB_SYMBOL_P.
Definition value_type.h:88
void ruby_stop(int ex)
Calls ruby_cleanup() and exits the process.
Definition eval.c:301
void rb_notimplement(void)
Definition error.c:3842
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:3911
VALUE rb_eSystemExit
SystemExit exception.
Definition error.c:1424
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:3917
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1429
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1398
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition error.c:1482
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
Definition eval.c:1178
void rb_unexpected_type(VALUE x, int t)
Fails with the given object's type incompatibility to the type.
Definition error.c:1361
void rb_exit(int status)
Terminates the current execution context.
Definition process.c:4391
VALUE rb_mProcess
Process module.
Definition process.c:8764
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2249
VALUE rb_cThread
Thread class.
Definition vm.c:671
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3306
#define RB_OBJ_WRITTEN(old, oldv, young)
Identical to RB_OBJ_WRITE(), except it doesn't write any values, but only a WB declaration.
Definition gc.h:615
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
VALUE rb_ary_dup(VALUE ary)
Duplicates an array.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
void rb_ary_store(VALUE ary, long key, VALUE val)
Destructively stores the passed value to the passed array's passed index.
#define UNLIMITED_ARGUMENTS
This macro is used in conjunction with rb_check_arity().
Definition error.h:35
VALUE rb_f_abort(int argc, const VALUE *argv)
This is similar to rb_f_exit().
Definition process.c:4473
VALUE rb_f_exit(int argc, const VALUE *argv)
Identical to rb_exit(), except how arguments are passed.
Definition process.c:4404
int rb_cloexec_dup2(int oldfd, int newfd)
Identical to rb_cloexec_dup(), except you can specify the destination file descriptor.
Definition io.c:412
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:286
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:366
void rb_close_before_exec(int lowfd, int maxhint, VALUE noclose_fds)
Closes everything.
int rb_reserved_fd_p(int fd)
Queries if the given FD is reserved or not.
int rb_pipe(int *pipes)
This is an rb_cloexec_pipe() + rb_update_max_fd() combo.
Definition io.c:7491
int rb_cloexec_fcntl_dupfd(int fd, int minfd)
Duplicates a file descriptor with closing on exec.
Definition io.c:520
int rb_cloexec_dup(int oldfd)
Identical to rb_cloexec_fcntl_dupfd(), except it implies minfd is 3.
Definition io.c:405
int rb_proc_exec(const char *cmd)
Executes a shell command.
Definition process.c:1712
VALUE rb_last_status_get(void)
Queries the "last status", or the $?.
Definition process.c:614
rb_pid_t rb_waitpid(rb_pid_t pid, int *status, int flags)
Waits for a process, with releasing GVL.
Definition process.c:1171
rb_pid_t rb_spawn_err(int argc, const VALUE *argv, char *errbuf, size_t buflen)
Identical to rb_spawn(), except you can additionally know the detailed situation in case of abnormal ...
Definition process.c:4651
void rb_syswait(rb_pid_t pid)
This is a shorthand of rb_waitpid without status and flags.
Definition process.c:4521
VALUE rb_f_exec(int argc, const VALUE *argv)
Replaces the current process by running the given external command.
Definition process.c:2931
rb_pid_t rb_spawn(int argc, const VALUE *argv)
Identical to rb_f_exec(), except it spawns a child process instead of replacing the current one.
Definition process.c:4657
VALUE rb_process_status_wait(rb_pid_t pid, int flags)
Wait for the specified process to terminate, reap it, and return its status.
Definition process.c:1098
void rb_last_status_set(int status, rb_pid_t pid)
Sets the "last status", or the $?.
Definition process.c:685
VALUE rb_detach_process(rb_pid_t pid)
"Detaches" a subprocess.
Definition process.c:1455
const char * ruby_signal_name(int signo)
Queries the name of the signal.
Definition signal.c:318
VALUE rb_f_kill(int argc, const VALUE *argv)
Sends a signal ("kills") to processes.
Definition signal.c:429
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3833
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition string.c:1763
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3184
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1682
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1018
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1535
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2014
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3418
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:2981
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1657
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2775
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1735
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition struct.c:506
VALUE rb_struct_new(VALUE klass,...)
Creates an instance of the given struct.
Definition struct.c:872
VALUE rb_thread_local_aref(VALUE thread, ID key)
This badly named function reads from a Fiber local storage.
Definition thread.c:3815
#define RUBY_UBF_IO
A special UBF for blocking IO operations.
Definition thread.h:382
void rb_thread_sleep_forever(void)
Blocks indefinitely.
Definition thread.c:1412
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
Definition thread.c:1445
void rb_thread_check_ints(void)
Checks for interrupts.
Definition thread.c:1466
void rb_thread_atfork(void)
A pthread_atfork(3posix)-like API.
Definition thread.c:5086
VALUE rb_thread_local_aset(VALUE thread, ID key, VALUE val)
This badly named function writes to a Fiber local storage.
Definition thread.c:3963
#define RUBY_UBF_PROCESS
A special UBF for blocking process operations.
Definition thread.h:389
void rb_thread_sleep(int sec)
Blocks for the given period of time.
Definition thread.c:1489
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2950
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition variable.c:2030
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1719
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
ID rb_check_id(volatile VALUE *namep)
Detects if the given name is already interned or not.
Definition symbol.c:1134
VALUE rb_sym2str(VALUE symbol)
Obtain a frozen string representation of a symbol (not including the leading colon).
Definition symbol.c:994
int rb_io_modestr_oflags(const char *modestr)
Identical to rb_io_modestr_fmode(), except it returns a mixture of O_ flags.
Definition io.c:6708
#define GetOpenFile
This is an old name of RB_IO_POINTER.
Definition io.h:442
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
VALUE rb_io_check_io(VALUE io)
Try converting an object to its IO representation using its to_io method, if any.
Definition io.c:876
int len
Length of the buffer.
Definition io.h:8
void * rb_thread_call_without_gvl2(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Identical to rb_thread_call_without_gvl(), except it does not interface with signals etc.
Definition thread.c:1731
void * rb_thread_call_without_gvl(void *(*func)(void *), void *data1, rb_unblock_function_t *ubf, void *data2)
Allows the passed function to run in parallel with other Ruby threads.
Definition thread.c:1738
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
#define RB_INT2NUM
Just another name of rb_int2num_inline.
Definition int.h:37
#define RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, callback_arg)
Shim for block function parameters.
Definition iterator.h:58
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1374
void rb_marshal_define_compat(VALUE newclass, VALUE oldclass, VALUE(*dumper)(VALUE), VALUE(*loader)(VALUE, VALUE))
Marshal format compatibility layer.
Definition marshal.c:137
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
VALUE rb_thread_create(type *q, void *w)
Creates a rb_cThread instance.
VALUE rb_block_call(VALUE q, ID w, int e, const VALUE *r, type *t, VALUE y)
Call a method with a block.
void rb_define_virtual_variable(const char *q, type *w, void_type *e)
Define a function-backended global variable.
#define PIDT2NUM
Converts a C's pid_t into an instance of rb_cInteger.
Definition pid_t.h:28
#define NUM2PIDT
Converts an instance of rb_cNumeric into C's pid_t.
Definition pid_t.h:33
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define RUBY_DEFAULT_FREE
This is a value you can set to RData::dfree.
Definition rdata.h:78
#define RHASH_SIZE(h)
Queries the size of the hash.
Definition rhash.h:69
#define RHASH_EMPTY_P(h)
Checks if the hash is empty.
Definition rhash.h:79
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
const char * rb_class2name(VALUE klass)
Queries the name of the passed class.
Definition variable.c:506
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
Scheduler APIs.
VALUE rb_fiber_scheduler_current(void)
Identical to rb_fiber_scheduler_get(), except it also returns RUBY_Qnil in case of a blocking fiber.
Definition scheduler.c:471
VALUE rb_fiber_scheduler_kernel_sleepv(VALUE scheduler, int argc, VALUE *argv)
Identical to rb_fiber_scheduler_kernel_sleep(), except it can pass multiple arguments.
Definition scheduler.c:549
VALUE rb_fiber_scheduler_process_wait(VALUE scheduler, rb_pid_t pid, int flags)
Non-blocking waitpid.
Definition scheduler.c:636
#define RTEST
This is an old name of RB_TEST.
Defines old _.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
VALUE tied_io_for_writing
Duplex IO object, if set.
Definition io.h:345
int fd
file descriptor.
Definition io.h:306
Definition win32.h:710
#define UIDT2NUM
Converts a C's uid_t into an instance of rb_cInteger.
Definition uid_t.h:28
#define NUM2UIDT
Converts an instance of rb_cNumeric into C's uid_t.
Definition uid_t.h:33
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40