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