Ruby 4.1.0dev (2026-09-27 revision f6ff9e7d02e46360f8930b280a3dd921cccbda29)
file.c (f6ff9e7d02e46360f8930b280a3dd921cccbda29)
1/**********************************************************************
2
3 file.c -
4
5 $Author$
6 created at: Mon Nov 15 12:24:34 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"
16
17#ifdef _WIN32
18# include "missing/file.h"
19# include "ruby.h"
20#endif
21
22#include <ctype.h>
23#include <time.h>
24
25#ifdef __CYGWIN__
26# include <windows.h>
27#endif
28
29#ifdef __APPLE__
30# if !(defined(__has_feature) && defined(__has_attribute))
31/* Maybe a bug in SDK of Xcode 10.2.1 */
32/* In this condition, <os/availability.h> does not define
33 * API_AVAILABLE and similar, but __API_AVAILABLE and similar which
34 * are defined in <Availability.h> */
35# define API_AVAILABLE(...)
36# define API_DEPRECATED(...)
37# endif
38# include <CoreFoundation/CFString.h>
39#endif
40
41#ifdef HAVE_UNISTD_H
42# include <unistd.h>
43#endif
44
45#ifdef HAVE_SYS_TIME_H
46# include <sys/time.h>
47#endif
48
49#ifdef HAVE_SYS_FILE_H
50# include <sys/file.h>
51#else
52int flock(int, int);
53#endif
54
55#ifdef HAVE_SYS_PARAM_H
56# include <sys/param.h>
57#endif
58#ifndef MAXPATHLEN
59# define MAXPATHLEN 1024
60#endif
61
62#ifdef HAVE_UTIME_H
63# include <utime.h>
64#elif defined HAVE_SYS_UTIME_H
65# include <sys/utime.h>
66#endif
67
68#ifdef HAVE_PWD_H
69# include <pwd.h>
70#endif
71
72#ifdef HAVE_SYS_SYSMACROS_H
73# include <sys/sysmacros.h>
74#endif
75
76#include <sys/types.h>
77#include <sys/stat.h>
78
79#ifdef HAVE_SYS_MKDEV_H
80# include <sys/mkdev.h>
81#endif
82
83#if defined(HAVE_FCNTL_H)
84# include <fcntl.h>
85#endif
86
87#if defined(HAVE_SYS_TIME_H)
88# include <sys/time.h>
89#endif
90
91#if !defined HAVE_LSTAT && !defined lstat
92# define lstat stat
93#endif
94
95/* define system APIs */
96#ifdef _WIN32
97# include "win32/file.h"
98# undef chmod
99# define chmod(p, m) rb_w32_uchmod((p), (m))
100# undef chown
101# define chown(p, o, g) rb_w32_uchown((p), (o), (g))
102# undef lchown
103# define lchown(p, o, g) rb_w32_ulchown((p), (o), (g))
104# undef link
105# define link(f, t) rb_w32_ulink((f), (t))
106# undef readlink
107# define readlink(f, t, l) rb_w32_ureadlink((f), (t), (l))
108# undef symlink
109# define symlink(s, l) rb_w32_usymlink((s), (l))
110
111# ifdef HAVE_REALPATH
112/* Don't use native realpath(3) on Windows, as the check for
113 absolute paths does not work for drive letters. */
114# undef HAVE_REALPATH
115# endif
116#endif /* _WIN32 */
117#define STAT(p, s) stat((p), (s))
118
119#ifdef HAVE_STRUCT_STATX_STX_BTIME
120# define ST_(name) stx_ ## name
121typedef struct statx_timestamp stat_timestamp;
122#else
123# define ST_(name) st_ ## name
124typedef struct timespec stat_timestamp;
125#endif
126
127#if defined _WIN32 || defined __APPLE__
128# define USE_OSPATH 1
129# define TO_OSPATH(str) rb_str_encode_ospath(str)
130#else
131# define USE_OSPATH 0
132# define TO_OSPATH(str) (str)
133#endif
134
135/* utime may fail if time is out-of-range for the FS [ruby-dev:38277] */
136#if defined DOSISH || defined __CYGWIN__
137# define UTIME_EINVAL
138#endif
139
140/* Solaris 10 realpath(3) doesn't support File.realpath */
141#if defined HAVE_REALPATH && defined __sun && defined __SVR4
142#undef HAVE_REALPATH
143#endif
144
145#ifdef HAVE_REALPATH
146# include <limits.h>
147# include <stdlib.h>
148#endif
149
150#include "dln.h"
151#include "encindex.h"
152#include "id.h"
153#include "internal.h"
154#include "internal/compilers.h"
155#include "internal/dir.h"
156#include "internal/encoding.h"
157#include "internal/error.h"
158#include "internal/file.h"
159#include "internal/io.h"
160#include "internal/load.h"
161#include "internal/object.h"
162#include "internal/process.h"
163#include "internal/thread.h"
164#include "internal/vm.h"
165#include "ruby/encoding.h"
166#include "ruby/thread.h"
167#include "ruby/util.h"
168
169#define UIANY2NUM(x) \
170 ((sizeof(x) <= sizeof(unsigned int)) ? \
171 UINT2NUM((unsigned)(x)) : \
172 (sizeof(x) <= sizeof(unsigned long)) ? \
173 ULONG2NUM((unsigned long)(x)) : \
174 ULL2NUM((unsigned LONG_LONG)(x)))
175
179
180static VALUE
181file_path_convert(VALUE name)
182{
183#ifndef _WIN32 /* non Windows == Unix */
184 int fname_encidx = ENCODING_GET(name);
185 int fs_encidx;
186 if (ENCINDEX_US_ASCII != fname_encidx &&
187 ENCINDEX_ASCII_8BIT != fname_encidx &&
188 (fs_encidx = rb_filesystem_encindex()) != fname_encidx &&
189 rb_default_internal_encoding() &&
190 !rb_enc_str_asciionly_p(name)) {
191 /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */
192 /* fs_encoding should be ascii compatible */
193 rb_encoding *fname_encoding = rb_enc_from_index(fname_encidx);
194 rb_encoding *fs_encoding = rb_enc_from_index(fs_encidx);
195 name = rb_str_conv_enc(name, fname_encoding, fs_encoding);
196 }
197#endif
198 return name;
199}
200
201static void
202check_path_encoding(VALUE str)
203{
204 if (RB_UNLIKELY(!rb_str_enc_fastpath(str))) {
205 rb_encoding *enc = rb_str_enc_get(str);
206 if (!rb_enc_asciicompat(enc)) {
207 rb_raise(rb_eEncCompatError, "path name must be ASCII-compatible (%s): %"PRIsVALUE,
208 rb_enc_name(enc), rb_str_inspect(str));
209 }
210 }
211}
212
213VALUE
214rb_get_path_check_to_string(VALUE obj)
215{
216 VALUE tmp;
217 ID to_path;
218
219 if (RB_TYPE_P(obj, T_STRING)) {
220 return obj;
221 }
222 CONST_ID(to_path, "to_path");
223 tmp = rb_check_funcall_default(obj, to_path, 0, 0, obj);
224 StringValue(tmp);
225 return tmp;
226}
227
228VALUE
229rb_get_path_check_convert(VALUE obj)
230{
231 obj = file_path_convert(obj);
232 rb_get_path_check_no_convert(obj);
233 return rb_str_new_frozen(obj);
234}
235
236/* TODO: name */
237VALUE
238rb_get_path_check_no_convert(VALUE obj)
239{
240 check_path_encoding(obj);
241 if (!rb_str_to_cstr(obj)) {
242 rb_raise(rb_eArgError, "path name contains null byte");
243 }
244
245 return obj;
246}
247
248VALUE
249rb_get_path_no_checksafe(VALUE obj)
250{
251 return rb_get_path(obj);
252}
253
254VALUE
255rb_get_path(VALUE obj)
256{
257 return rb_get_path_check_convert(rb_get_path_check_to_string(obj));
258}
259
260static inline VALUE
261check_path(VALUE obj, const char **cstr)
262{
263 VALUE str = rb_get_path_check_convert(rb_get_path_check_to_string(obj));
264#if RUBY_DEBUG
265 str = rb_str_new_frozen(str);
266#endif
267 *cstr = RSTRING_PTR(str);
268 return str;
269}
270
271#define CheckPath(str, cstr) RB_GC_GUARD(str) = check_path(str, &cstr);
272
273VALUE
274rb_str_encode_ospath(VALUE path)
275{
276#if USE_OSPATH
277 int encidx = ENCODING_GET(path);
278 if (encidx != ENCINDEX_ASCII_8BIT && encidx != ENCINDEX_UTF_8) {
279 rb_encoding *enc = rb_enc_from_index(encidx);
280 rb_encoding *utf8 = rb_utf8_encoding();
281 path = rb_str_conv_enc(path, enc, utf8);
282 }
283#endif /* USE_OSPATH */
284 return path;
285}
286
287#ifdef __APPLE__
288# define NORMALIZE_UTF8PATH 1
289
290# ifdef HAVE_WORKING_FORK
291static CFMutableStringRef
292mutable_CFString_new(CFStringRef *s, const char *ptr, long len)
293{
294 const CFAllocatorRef alloc = kCFAllocatorDefault;
295 *s = CFStringCreateWithBytesNoCopy(alloc, (const UInt8 *)ptr, len,
296 kCFStringEncodingUTF8, FALSE,
297 kCFAllocatorNull);
298 return CFStringCreateMutableCopy(alloc, len, *s);
299}
300
301# define mutable_CFString_release(m, s) (CFRelease(m), CFRelease(s))
302
303static void
304rb_CFString_class_initialize_before_fork(void)
305{
306 /*
307 * Since macOS 13, CFString family API used in
308 * rb_str_append_normalized_ospath may internally use Objective-C classes
309 * (NSTaggedPointerString and NSPlaceholderMutableString) for small strings.
310 *
311 * On the other hand, Objective-C classes should not be used for the first
312 * time in a fork()'ed but not exec()'ed process. Violations for this rule
313 * can result deadlock during class initialization, so Objective-C runtime
314 * conservatively crashes on such cases by default.
315 *
316 * Therefore, we need to use CFString API to initialize Objective-C classes
317 * used internally *before* fork().
318 *
319 * For future changes, please note that this initialization process cannot
320 * be done in ctor because NSTaggedPointerString in CoreFoundation is enabled
321 * after CFStringInitializeTaggedStrings(), which is called during loading
322 * Objective-C runtime after ctor.
323 * For more details, see https://bugs.ruby-lang.org/issues/18912
324 */
325
326 /* Enough small but non-empty ASCII string to fit in NSTaggedPointerString. */
327 const char small_str[] = "/";
328 long len = sizeof(small_str) - 1;
329 CFStringRef s;
330 /*
331 * Touch `CFStringCreateWithBytesNoCopy` *twice* because the implementation
332 * shipped with macOS 15.0 24A5331b does not return `NSTaggedPointerString`
333 * instance for the first call (totally not sure why). CoreFoundation
334 * shipped with macOS 15.1 does not have this issue.
335 */
336 for (int i = 0; i < 2; i++) {
337 CFMutableStringRef m = mutable_CFString_new(&s, small_str, len);
338 mutable_CFString_release(m, s);
339 }
340}
341# endif /* HAVE_WORKING_FORK */
342
343static VALUE
344rb_str_append_normalized_ospath(VALUE str, const char *ptr, long len)
345{
346 CFIndex buflen = 0;
347 CFRange all;
348 CFStringRef s;
349 CFMutableStringRef m = mutable_CFString_new(&s, ptr, len);
350 long oldlen = RSTRING_LEN(str);
351
352 CFStringNormalize(m, kCFStringNormalizationFormC);
353 all = CFRangeMake(0, CFStringGetLength(m));
354 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE, NULL, 0, &buflen);
355 rb_str_modify_expand(str, buflen);
356 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE,
357 (UInt8 *)(RSTRING_PTR(str) + oldlen), buflen, &buflen);
358 rb_str_set_len(str, oldlen + buflen);
359 mutable_CFString_release(m, s);
360 return str;
361}
362
363VALUE
364rb_str_normalize_ospath(const char *ptr, long len)
365{
366 const char *p = ptr;
367 const char *e = ptr + len;
368 const char *p1 = p;
369 rb_encoding *enc = rb_utf8_encoding();
370 VALUE str = rb_utf8_str_new(ptr, len);
371 if (RB_LIKELY(rb_enc_str_coderange(str) == ENC_CODERANGE_7BIT)) {
372 return str;
373 }
374 else {
375 str = rb_str_buf_new(len);
376 rb_enc_associate(str, enc);
377 }
378
379 while (p < e) {
380 int l, c;
381 int r = rb_enc_precise_mbclen(p, e, enc);
382 if (!MBCLEN_CHARFOUND_P(r)) {
383 /* invalid byte shall not happen but */
384 RBIMPL_ATTR_NONSTRING() static const char invalid[3] = "\xEF\xBF\xBD";
385 rb_str_append_normalized_ospath(str, p1, p-p1);
386 rb_str_cat(str, invalid, sizeof(invalid));
387 p += 1;
388 p1 = p;
389 continue;
390 }
392 c = rb_enc_mbc_to_codepoint(p, e, enc);
393 if ((0x2000 <= c && c <= 0x2FFF) || (0xF900 <= c && c <= 0xFAFF) ||
394 (0x2F800 <= c && c <= 0x2FAFF)) {
395 if (p - p1 > 0) {
396 rb_str_append_normalized_ospath(str, p1, p-p1);
397 }
398 rb_str_cat(str, p, l);
399 p += l;
400 p1 = p;
401 }
402 else {
403 p += l;
404 }
405 }
406 if (p - p1 > 0) {
407 rb_str_append_normalized_ospath(str, p1, p-p1);
408 }
409
410 return str;
411}
412
413static int
414ignored_char_p(const char *p, const char *e, rb_encoding *enc)
415{
416 unsigned char c;
417 if (p+3 > e) return 0;
418 switch ((unsigned char)*p) {
419 case 0xe2:
420 switch ((unsigned char)p[1]) {
421 case 0x80:
422 c = (unsigned char)p[2];
423 /* c >= 0x200c && c <= 0x200f */
424 if (c >= 0x8c && c <= 0x8f) return 3;
425 /* c >= 0x202a && c <= 0x202e */
426 if (c >= 0xaa && c <= 0xae) return 3;
427 return 0;
428 case 0x81:
429 c = (unsigned char)p[2];
430 /* c >= 0x206a && c <= 0x206f */
431 if (c >= 0xaa && c <= 0xaf) return 3;
432 return 0;
433 }
434 break;
435 case 0xef:
436 /* c == 0xfeff */
437 if ((unsigned char)p[1] == 0xbb &&
438 (unsigned char)p[2] == 0xbf)
439 return 3;
440 break;
441 }
442 return 0;
443}
444#else /* !__APPLE__ */
445# define NORMALIZE_UTF8PATH 0
446#endif /* __APPLE__ */
447
448#define apply2args(n) (rb_check_arity(argc, n, UNLIMITED_ARGUMENTS), argc-=n)
449
451 const char *ptr;
452 VALUE path;
453};
454
455struct apply_arg {
456 int i;
457 int argc;
458 int errnum;
459 int (*func)(const char *, void *);
460 void *arg;
461 struct apply_filename fn[FLEX_ARY_LEN];
462};
463
464static void *
465no_gvl_apply2files(void *ptr)
466{
467 struct apply_arg *aa = ptr;
468
469 for (aa->i = 0; aa->i < aa->argc; aa->i++) {
470 if (aa->func(aa->fn[aa->i].ptr, aa->arg) < 0) {
471 aa->errnum = errno;
472 break;
473 }
474 }
475 return 0;
476}
477
478#ifdef UTIME_EINVAL
479NORETURN(static void utime_failed(struct apply_arg *));
480static int utime_internal(const char *, void *);
481#endif
482
483static VALUE
484apply2files(int (*func)(const char *, void *), int argc, VALUE *argv, void *arg)
485{
486 VALUE v;
487 const size_t size = sizeof(struct apply_filename);
488 const long len = (long)(offsetof(struct apply_arg, fn) + (size * argc));
489 struct apply_arg *aa = ALLOCV(v, len);
490
491 aa->errnum = 0;
492 aa->argc = argc;
493 aa->arg = arg;
494 aa->func = func;
495
496 for (aa->i = 0; aa->i < argc; aa->i++) {
497 VALUE path = rb_get_path(argv[aa->i]);
498
499 path = rb_str_encode_ospath(path);
500 aa->fn[aa->i].ptr = RSTRING_PTR(path);
501 aa->fn[aa->i].path = path;
502 }
503
504 IO_WITHOUT_GVL(no_gvl_apply2files, aa);
505 if (aa->errnum) {
506#ifdef UTIME_EINVAL
507 if (func == utime_internal) {
508 utime_failed(aa);
509 }
510#endif
511 rb_syserr_fail_path(aa->errnum, aa->fn[aa->i].path);
512 }
513 if (v) {
514 ALLOCV_END(v);
515 }
516 return LONG2FIX(argc);
517}
518
519static stat_timestamp stat_atimespec(const struct stat *st);
520static stat_timestamp stat_mtimespec(const struct stat *st);
521static stat_timestamp stat_ctimespec(const struct stat *st);
522
523static const rb_data_type_t stat_data_type = {
524 "stat",
525 {
526 NULL,
528 NULL, // No external memory to report
529 },
530 0, 0, RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
531};
532
533struct rb_stat {
534 rb_io_stat_data stat;
535 bool initialized;
536};
537
538static struct rb_stat *
539stat_alloc(VALUE klass, VALUE *obj)
540{
541 struct rb_stat *rb_st;
542 *obj = TypedData_Make_Struct(klass, struct rb_stat, &stat_data_type, rb_st);
543 return rb_st;
544}
545
546VALUE
547rb_stat_new(const struct stat *st)
548{
549 VALUE obj;
550 struct rb_stat *rb_st = stat_alloc(rb_cStat, &obj);
551 if (st) {
552#if RUBY_USE_STATX
553# define CP(m) .stx_ ## m = st->st_ ## m
554# define CP_32(m) .stx_ ## m = (uint32_t)st->st_ ## m
555# define CP_TS(m) .stx_ ## m = stat_ ## m ## spec(st)
556 rb_st->stat = (struct statx){
557 .stx_mask = STATX_BASIC_STATS,
558 CP(mode),
559 CP_32(nlink),
560 CP(uid),
561 CP(gid),
562 CP_TS(atime),
563 CP_TS(mtime),
564 CP_TS(ctime),
565 CP(ino),
566 CP(size),
567 CP(blocks),
568 };
569# undef CP
570# undef CP_TS
571#else
572 rb_st->stat = *st;
573#endif
574 rb_st->initialized = true;
575 }
576
577 return obj;
578}
579
580#ifndef rb_statx_new
581VALUE
582rb_statx_new(const rb_io_stat_data *st)
583{
584 VALUE obj;
585 struct rb_stat *rb_st = stat_alloc(rb_cStat, &obj);
586 if (st) {
587 rb_st->stat = *st;
588 rb_st->initialized = true;
589 }
590 return obj;
591}
592#endif
593
594static rb_io_stat_data*
595get_stat(VALUE self)
596{
597 struct rb_stat* rb_st;
598 TypedData_Get_Struct(self, struct rb_stat, &stat_data_type, rb_st);
599 if (!rb_st->initialized) rb_raise(rb_eTypeError, "uninitialized File::Stat");
600 return &rb_st->stat;
601}
602
603#if RUBY_USE_STATX
604static stat_timestamp
605statx_mtimespec(const rb_io_stat_data *st)
606{
607 return st->stx_mtime;
608}
609#else
610# define statx_mtimespec stat_mtimespec
611#endif
612
613/*
614 * call-seq:
615 * self <=> other -> -1, 0, 1, or nil
616 *
617 * Compares +self+ and +other+, by comparing their modification times;
618 * that is, by comparing <tt>self.mtime</tt> and <tt>other.mtime</tt>.
619 *
620 * Returns:
621 *
622 * - +-1+, if <tt>self.mtime</tt> is earlier.
623 * - +0+, if the two values are equal.
624 * - +1+, if <tt>self.mtime</tt> is later.
625 * - +nil+, if +other+ is not a File::Stat object.
626 *
627 * Examples:
628 *
629 * stat0 = File.stat('README.md')
630 * stat1 = File.stat('NEWS.md')
631 * stat0.mtime # => 2025-12-20 15:33:05.6972341 -0600
632 * stat1.mtime # => 2025-12-20 16:02:08.2672945 -0600
633 * stat0 <=> stat1 # => -1
634 * stat0 <=> stat0.dup # => 0
635 * stat1 <=> stat0 # => 1
636 * stat0 <=> :foo # => nil
637 *
638 * \Class \File::Stat includes module Comparable,
639 * each of whose methods uses File::Stat#<=> for comparison.
640 */
641
642static VALUE
643rb_stat_cmp(VALUE self, VALUE other)
644{
645 if (rb_obj_is_kind_of(other, rb_obj_class(self))) {
646 stat_timestamp ts1 = statx_mtimespec(get_stat(self));
647 stat_timestamp ts2 = statx_mtimespec(get_stat(other));
648 if (ts1.tv_sec == ts2.tv_sec) {
649 if (ts1.tv_nsec == ts2.tv_nsec) return INT2FIX(0);
650 if (ts1.tv_nsec < ts2.tv_nsec) return INT2FIX(-1);
651 return INT2FIX(1);
652 }
653 if (ts1.tv_sec < ts2.tv_sec) return INT2FIX(-1);
654 return INT2FIX(1);
655 }
656 return Qnil;
657}
658
659#define ST2UINT(val) ((val) & ~(~1UL << (sizeof(val) * CHAR_BIT - 1)))
660
661#ifndef NUM2DEVT
662# define NUM2DEVT(v) NUM2UINT(v)
663#endif
664#ifndef DEVT2NUM
665# define DEVT2NUM(v) UINT2NUM(v)
666#endif
667#ifndef PRI_DEVT_PREFIX
668# define PRI_DEVT_PREFIX ""
669#endif
670
671/*
672 * call-seq:
673 * stat.dev -> integer
674 *
675 * Returns an integer representing the device on which <i>stat</i>
676 * resides.
677 *
678 * File.stat("testfile").dev #=> 774
679 */
680
681static VALUE
682rb_stat_dev(VALUE self)
683{
684#if RUBY_USE_STATX
685 unsigned int m = get_stat(self)->stx_dev_major;
686 unsigned int n = get_stat(self)->stx_dev_minor;
687 return ULL2NUM(makedev(m, n));
688#elif SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_DEV_T
689 return DEVT2NUM(get_stat(self)->st_dev);
690#elif SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_LONG
691 return ULONG2NUM(get_stat(self)->st_dev);
692#else
693 return ULL2NUM(get_stat(self)->st_dev);
694#endif
695}
696
697/*
698 * call-seq:
699 * stat.dev_major -> integer
700 *
701 * Returns the major part of File::Stat#dev or +nil+.
702 *
703 * File.stat("/dev/fd1").dev_major #=> 2
704 * File.stat("/dev/tty").dev_major #=> 5
705 */
706
707static VALUE
708rb_stat_dev_major(VALUE self)
709{
710#if RUBY_USE_STATX
711 return UINT2NUM(get_stat(self)->stx_dev_major);
712#elif defined(major)
713 return UINT2NUM(major(get_stat(self)->st_dev));
714#else
715 return Qnil;
716#endif
717}
718
719/*
720 * call-seq:
721 * stat.dev_minor -> integer
722 *
723 * Returns the minor part of File::Stat#dev or +nil+.
724 *
725 * File.stat("/dev/fd1").dev_minor #=> 1
726 * File.stat("/dev/tty").dev_minor #=> 0
727 */
728
729static VALUE
730rb_stat_dev_minor(VALUE self)
731{
732#if RUBY_USE_STATX
733 return UINT2NUM(get_stat(self)->stx_dev_minor);
734#elif defined(minor)
735 return UINT2NUM(minor(get_stat(self)->st_dev));
736#else
737 return Qnil;
738#endif
739}
740
741/*
742 * call-seq:
743 * stat.ino -> integer
744 *
745 * Returns the inode number for <i>stat</i>.
746 *
747 * File.stat("testfile").ino #=> 1083669
748 *
749 */
750
751static VALUE
752rb_stat_ino(VALUE self)
753{
754 rb_io_stat_data *ptr = get_stat(self);
755#ifdef HAVE_STRUCT_STAT_ST_INOHIGH
756 /* assume INTEGER_PACK_LSWORD_FIRST and st_inohigh is just next of st_ino */
757 return rb_integer_unpack(&ptr->st_ino, 2,
758 SIZEOF_STRUCT_STAT_ST_INO, 0,
761#else
762 return UIANY2NUM(ptr->ST_(ino));
763#endif
764}
765
766/*
767 * call-seq:
768 * stat.mode -> integer
769 *
770 * Returns an integer representing the permission bits of
771 * <i>stat</i>. The meaning of the bits is platform dependent; on
772 * Unix systems, see <code>stat(2)</code>.
773 *
774 * File.chmod(0644, "testfile") #=> 1
775 * s = File.stat("testfile")
776 * sprintf("%o", s.mode) #=> "100644"
777 */
778
779static VALUE
780rb_stat_mode(VALUE self)
781{
782 return UINT2NUM(ST2UINT(get_stat(self)->ST_(mode)));
783}
784
785/*
786 * call-seq:
787 * stat.nlink -> integer
788 *
789 * Returns the number of hard links to <i>stat</i>.
790 *
791 * File.stat("testfile").nlink #=> 1
792 * File.link("testfile", "testfile.bak") #=> 0
793 * File.stat("testfile").nlink #=> 2
794 *
795 */
796
797static VALUE
798rb_stat_nlink(VALUE self)
799{
800 /* struct stat::st_nlink is nlink_t in POSIX. Not the case for Windows. */
801 const rb_io_stat_data *ptr = get_stat(self);
802
803 return UIANY2NUM(ptr->ST_(nlink));
804}
805
806/*
807 * call-seq:
808 * stat.uid -> integer
809 *
810 * Returns the numeric user id of the owner of <i>stat</i>.
811 *
812 * File.stat("testfile").uid #=> 501
813 *
814 */
815
816static VALUE
817rb_stat_uid(VALUE self)
818{
819 return UIDT2NUM(get_stat(self)->ST_(uid));
820}
821
822/*
823 * call-seq:
824 * stat.gid -> integer
825 *
826 * Returns the numeric group id of the owner of <i>stat</i>.
827 *
828 * File.stat("testfile").gid #=> 500
829 *
830 */
831
832static VALUE
833rb_stat_gid(VALUE self)
834{
835 return GIDT2NUM(get_stat(self)->ST_(gid));
836}
837
838/*
839 * call-seq:
840 * stat.rdev -> integer or nil
841 *
842 * Returns an integer representing the device type on which
843 * <i>stat</i> resides. Returns +nil+ if the operating system doesn't
844 * support this feature.
845 *
846 * File.stat("/dev/fd1").rdev #=> 513
847 * File.stat("/dev/tty").rdev #=> 1280
848 */
849
850static VALUE
851rb_stat_rdev(VALUE self)
852{
853#if RUBY_USE_STATX
854 unsigned int m = get_stat(self)->stx_rdev_major;
855 unsigned int n = get_stat(self)->stx_rdev_minor;
856 return ULL2NUM(makedev(m, n));
857#elif !defined(HAVE_STRUCT_STAT_ST_RDEV)
858 return Qnil;
859#elif SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_DEV_T
860 return DEVT2NUM(get_stat(self)->ST_(rdev));
861#elif SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_LONG
862 return ULONG2NUM(get_stat(self)->ST_(rdev));
863#else
864 return ULL2NUM(get_stat(self)->ST_(rdev));
865#endif
866}
867
868/*
869 * call-seq:
870 * stat.rdev_major -> integer
871 *
872 * Returns the major part of File::Stat#rdev or +nil+.
873 *
874 * File.stat("/dev/fd1").rdev_major #=> 2
875 * File.stat("/dev/tty").rdev_major #=> 5
876 */
877
878static VALUE
879rb_stat_rdev_major(VALUE self)
880{
881#if RUBY_USE_STATX
882 return UINT2NUM(get_stat(self)->stx_rdev_major);
883#elif defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(major)
884 return UINT2NUM(major(get_stat(self)->ST_(rdev)));
885#else
886 return Qnil;
887#endif
888}
889
890/*
891 * call-seq:
892 * stat.rdev_minor -> integer
893 *
894 * Returns the minor part of File::Stat#rdev or +nil+.
895 *
896 * File.stat("/dev/fd1").rdev_minor #=> 1
897 * File.stat("/dev/tty").rdev_minor #=> 0
898 */
899
900static VALUE
901rb_stat_rdev_minor(VALUE self)
902{
903#if RUBY_USE_STATX
904 return UINT2NUM(get_stat(self)->stx_rdev_minor);
905#elif defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(minor)
906 return UINT2NUM(minor(get_stat(self)->ST_(rdev)));
907#else
908 return Qnil;
909#endif
910}
911
912/*
913 * :markup: markdown
914 *
915 * call-seq:
916 * size -> integer
917 *
918 * Returns the size of `self` in bytes:
919 *
920 * ```ruby
921 * File.stat('doc/maintainers.md').size # => 14900 # Regular file.
922 * File.stat('doc/syntax/').size # => 4096 # Directory.
923 * # When the file size changes.
924 * path = '/tmp/t.tmp'
925 * file = File.new(path, 'w+')
926 * file.write('foo')
927 * stat = File.stat(path) # Take snapshot.
928 * stat.size # => 3
929 * file.write('bar') # Change file size.
930 * file.size # => 6
931 * stat.size # => 3 # Snapshot unchanged.
932 * stat = File.stat(path) # Fresh snapshot.
933 * stat.size # => 6 # Shapshot different.
934 * # Clean up.
935 * file.close
936 * File.delete(path)
937 * ```
938 *
939 */
940
941static VALUE
942rb_stat_size(VALUE self)
943{
944 return OFFT2NUM(get_stat(self)->ST_(size));
945}
946
947/*
948 * call-seq:
949 * stat.blksize -> integer or nil
950 *
951 * Returns the native file system's block size. Will return +nil+ on
952 * platforms that don't support this information.
953 *
954 * File.stat("testfile").blksize #=> 4096
955 *
956 */
957
958static VALUE
959rb_stat_blksize(VALUE self)
960{
961#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
962 return ULONG2NUM(get_stat(self)->ST_(blksize));
963#else
964 return Qnil;
965#endif
966}
967
968/*
969 * call-seq:
970 * stat.blocks -> integer or nil
971 *
972 * Returns the number of native file system blocks allocated for this
973 * file, or +nil+ if the operating system doesn't support this
974 * feature.
975 *
976 * File.stat("testfile").blocks #=> 2
977 */
978
979static VALUE
980rb_stat_blocks(VALUE self)
981{
982#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
983# if SIZEOF_STRUCT_STAT_ST_BLOCKS > SIZEOF_LONG
984 return ULL2NUM(get_stat(self)->ST_(blocks));
985# else
986 return ULONG2NUM(get_stat(self)->ST_(blocks));
987# endif
988#else
989 return Qnil;
990#endif
991}
992
993static stat_timestamp
994stat_atimespec(const struct stat *st)
995{
997 ts.tv_sec = st->st_atime;
998#if defined(HAVE_STRUCT_STAT_ST_ATIM)
999 ts.tv_nsec = (uint32_t)st->st_atim.tv_nsec;
1000#elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
1001 ts.tv_nsec = (uint32_t)st->st_atimespec.tv_nsec;
1002#elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
1003 ts.tv_nsec = (uint32_t)st->st_atimensec;
1004#else
1005 ts.tv_nsec = 0
1006#endif
1007 return ts;
1008}
1009
1010#if RUBY_USE_STATX
1011static stat_timestamp
1012statx_atimespec(const rb_io_stat_data *st)
1013{
1014 return st->stx_atime;
1015}
1016#else
1017# define statx_atimespec stat_atimespec
1018#endif
1019
1020static VALUE
1021stat_time(const stat_timestamp ts)
1022{
1023 return rb_time_nano_new(ts.tv_sec, ts.tv_nsec);
1024}
1025
1026static VALUE
1027stat_atime(const struct stat *st)
1028{
1029 return stat_time(stat_atimespec(st));
1030}
1031
1032static stat_timestamp
1033stat_mtimespec(const struct stat *st)
1034{
1035 stat_timestamp ts;
1036 ts.tv_sec = st->st_mtime;
1037#if defined(HAVE_STRUCT_STAT_ST_MTIM)
1038 ts.tv_nsec = (uint32_t)st->st_mtim.tv_nsec;
1039#elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
1040 ts.tv_nsec = (uint32_t)st->st_mtimespec.tv_nsec;
1041#elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
1042 ts.tv_nsec = (uint32_t)st->st_mtimensec;
1043#else
1044 ts.tv_nsec = 0;
1045#endif
1046 return ts;
1047}
1048
1049static VALUE
1050stat_mtime(const struct stat *st)
1051{
1052 return stat_time(stat_mtimespec(st));
1053}
1054
1055static stat_timestamp
1056stat_ctimespec(const struct stat *st)
1057{
1058 stat_timestamp ts;
1059 ts.tv_sec = st->st_ctime;
1060#if defined(HAVE_STRUCT_STAT_ST_CTIM)
1061 ts.tv_nsec = (uint32_t)st->st_ctim.tv_nsec;
1062#elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
1063 ts.tv_nsec = (uint32_t)st->st_ctimespec.tv_nsec;
1064#elif defined(HAVE_STRUCT_STAT_ST_CTIMENSEC)
1065 ts.tv_nsec = (uint32_t)st->st_ctimensec;
1066#else
1067 ts.tv_nsec = 0;
1068#endif
1069 return ts;
1070}
1071
1072#if RUBY_USE_STATX
1073static stat_timestamp
1074statx_ctimespec(const rb_io_stat_data *st)
1075{
1076 return st->stx_ctime;
1077}
1078#else
1079# define statx_ctimespec stat_ctimespec
1080#endif
1081
1082static VALUE
1083stat_ctime(const struct stat *st)
1084{
1085 return stat_time(stat_ctimespec(st));
1086}
1087
1088#define HAVE_STAT_BIRTHTIME
1089#if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1090static VALUE
1091statx_birthtime(const rb_io_stat_data *st)
1092{
1093 const stat_timestamp *ts = &st->ST_(birthtimespec);
1094 return rb_time_nano_new(ts->tv_sec, ts->tv_nsec);
1095}
1096#elif defined(HAVE_STRUCT_STATX_STX_BTIME)
1097static VALUE statx_birthtime(const rb_io_stat_data *st);
1098#elif defined(_WIN32)
1099# define statx_birthtime stat_ctime
1100#else
1101# undef HAVE_STAT_BIRTHTIME
1102#endif /* defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) */
1103
1104/*
1105 * call-seq:
1106 * atime -> time
1107 *
1108 * Returns a new Time object containing the access time
1109 * of the object represented by +self+
1110 * at the time +self+ was created;
1111 * see {Snapshot}[rdoc-ref:File::Stat@Snapshot].
1112 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
1113 *
1114 * Access time for a file is established when it is created,
1115 * and may be updated when the file content is read:
1116 *
1117 * filepath = 't.tmp'
1118 * File.exist?(filepath) # => false
1119 * file = File.open(filepath, 'w+') # Create by writing; establishes access time.
1120 * file.atime # => 2026-08-14 11:55:55.436283939 -0500
1121 * stat0 = File::Stat.new(filepath) # Take snapshot.
1122 * stat0.atime # => 2026-08-14 11:55:55.436283939 -0500
1123 * file.read # Read file content; updates file access time.
1124 * file.atime # => 2026-08-14 11:56:22.74241085 -0500
1125 * stat0.atime # => 2026-08-14 11:55:55.436283939 -0500 # Not updated.
1126 * stat1 = File::Stat.new(filepath) # Take new snapshot.
1127 * stat1.atime # => 2026-08-14 11:56:22.74241085 -0500 # Updated.
1128 * # Clean up.
1129 * file.close
1130 * File.delete(filepath)
1131 *
1132 * Access time for a directory is established when it is created,
1133 * and may be updated when its entries are read:
1134 *
1135 * dirpath = 'foo'
1136 * File.exist?(dirpath) # => false
1137 * FileUtils.cp_r('doc', 'foo') # Create directory by copying.
1138 * File.atime(dirpath) # => 2026-08-15 14:10:04.832180372 -0500
1139 * stat = File::Stat.new(dirpath)
1140 * stat.atime # => 2026-08-15 14:10:04.832180372 -0500
1141 * # Clean up.
1142 * FileUtils.rm_rf(dirpath)
1143 * dir.close
1144 *
1145 */
1146
1147static VALUE
1148rb_stat_atime(VALUE self)
1149{
1150 return stat_time(statx_atimespec(get_stat(self)));
1151}
1152
1153/*
1154 * :markup: markdown
1155
1156 * call-seq:
1157 * mtime -> time
1158 *
1159 * Returns a new Time object containing the modification time
1160 * of the object represented by `self`
1161 * at the time `self` was created;
1162 * see [Snapshot](rdoc-ref:File::Stat@Snapshot):
1163 *
1164 * ```ruby
1165 * path = 't.tmp'
1166 * file = File.new(path, 'w+')
1167 * stat = File.stat(path)
1168 * stat.mtime # => 2026-09-19 08:49:08.846933858 -0500
1169 * file.write('foo')
1170 * file.flush
1171 * File.mtime(path) # => 2026-09-19 08:50:14.381365572 -0500
1172 * stat.mtime # => 2026-09-19 08:49:08.846933858 -0500
1173 * stat = File.stat(path)
1174 * stat.mtime # => 2026-09-19 08:50:14.381365572 -0500
1175 * File.unlink(path) # Clean up.
1176 * ```
1177 *
1178 */
1179
1180static VALUE
1181rb_stat_mtime(VALUE self)
1182{
1183 return stat_time(statx_mtimespec(get_stat(self)));
1184}
1185
1186/*
1187 * call-seq:
1188 * stat.ctime -> time
1189 *
1190 * Returns the change time for <i>stat</i> (that is, the time
1191 * directory information about the file was changed, not the file
1192 * itself).
1193 *
1194 * Note that on Windows (NTFS), returns creation time (birth time).
1195 *
1196 * File.stat("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
1197 *
1198 */
1199
1200static VALUE
1201rb_stat_ctime(VALUE self)
1202{
1203 return stat_time(statx_ctimespec(get_stat(self)));
1204}
1205
1206#if defined(HAVE_STAT_BIRTHTIME)
1207/*
1208 * call-seq:
1209 * birthtime -> new_time
1210 *
1211 * Returns a new Time object containing the create time
1212 * of the object represented by +self+
1213 * at the time +self+ was created;
1214 * see {Snapshot}[rdoc-ref:File::Stat@Snapshot]:
1215 *
1216 * filename = 't.tmp'
1217 * stat = File::Stat.new(filename) # Raises Errno::ENOENT: No such file or directory
1218 * File.write(filename, 'foo')
1219 * stat = File::Stat.new(filename)
1220 * stat.birthtime # => 2026-04-14 10:41:55.5146554 -0500
1221 * File.delete(filename)
1222 * stat.birthtime # => 2026-04-14 10:41:55.5146554 -0500
1223 *
1224 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
1225 */
1226
1227static VALUE
1228rb_stat_birthtime(VALUE self)
1229{
1230 return statx_birthtime(get_stat(self));
1231}
1232#else
1233# define rb_stat_birthtime rb_f_notimplement
1234#endif
1235
1236/*
1237 * call-seq:
1238 * stat.inspect -> string
1239 *
1240 * Produce a nicely formatted description of <i>stat</i>.
1241 *
1242 * File.stat("/etc/passwd").inspect
1243 * #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
1244 * # nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
1245 * # blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
1246 * # mtime=Fri Sep 12 15:41:41 CDT 2003,
1247 * # ctime=Mon Oct 27 11:20:27 CST 2003,
1248 * # birthtime=Mon Aug 04 08:13:49 CDT 2003>"
1249 */
1250
1251static VALUE
1252rb_stat_inspect(VALUE self)
1253{
1254 VALUE str;
1255 size_t i;
1256 static const struct {
1257 const char *name;
1258 VALUE (*func)(VALUE);
1259 } member[] = {
1260 {"dev", rb_stat_dev},
1261 {"ino", rb_stat_ino},
1262 {"mode", rb_stat_mode},
1263 {"nlink", rb_stat_nlink},
1264 {"uid", rb_stat_uid},
1265 {"gid", rb_stat_gid},
1266 {"rdev", rb_stat_rdev},
1267 {"size", rb_stat_size},
1268 {"blksize", rb_stat_blksize},
1269 {"blocks", rb_stat_blocks},
1270 {"atime", rb_stat_atime},
1271 {"mtime", rb_stat_mtime},
1272 {"ctime", rb_stat_ctime},
1273#if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1274 {"birthtime", rb_stat_birthtime},
1275#endif
1276 };
1277
1278 struct rb_stat* rb_st;
1279 TypedData_Get_Struct(self, struct rb_stat, &stat_data_type, rb_st);
1280 if (!rb_st->initialized) {
1281 return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
1282 }
1283
1284 str = rb_str_buf_new2("#<");
1286 rb_str_buf_cat2(str, " ");
1287
1288 for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) {
1289 VALUE v;
1290
1291 if (i > 0) {
1292 rb_str_buf_cat2(str, ", ");
1293 }
1294 rb_str_buf_cat2(str, member[i].name);
1295 rb_str_buf_cat2(str, "=");
1296 v = (*member[i].func)(self);
1297 if (i == 2) { /* mode */
1298 rb_str_catf(str, "0%lo", (unsigned long)NUM2ULONG(v));
1299 }
1300 else if (i == 0 || i == 6) { /* dev/rdev */
1301 rb_str_catf(str, "0x%"PRI_DEVT_PREFIX"x", NUM2DEVT(v));
1302 }
1303 else {
1304 rb_str_append(str, rb_inspect(v));
1305 }
1306 }
1307 rb_str_buf_cat2(str, ">");
1308
1309 return str;
1310}
1311
1312typedef struct no_gvl_stat_data {
1313 struct stat *st;
1314 union {
1315 const char *path;
1316 int fd;
1317 } file;
1319
1320static VALUE
1321no_gvl_fstat(void *data)
1322{
1323 no_gvl_stat_data *arg = data;
1324 return (VALUE)fstat(arg->file.fd, arg->st);
1325}
1326
1327static int
1328fstat_without_gvl(rb_io_t *fptr, struct stat *st)
1329{
1330 no_gvl_stat_data data;
1331
1332 data.file.fd = fptr->fd;
1333 data.st = st;
1334
1335 return (int)rb_io_blocking_region(fptr, no_gvl_fstat, &data);
1336}
1337
1338static void *
1339no_gvl_stat(void * data)
1340{
1341 no_gvl_stat_data *arg = data;
1342 return (void *)(VALUE)STAT(arg->file.path, arg->st);
1343}
1344
1345static int
1346stat_without_gvl(const char *path, struct stat *st)
1347{
1348 no_gvl_stat_data data;
1349
1350 data.file.path = path;
1351 data.st = st;
1352
1353 return IO_WITHOUT_GVL_INT(no_gvl_stat, &data);
1354}
1355
1356#if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1357 defined(HAVE_STRUCT_STATX_STX_BTIME)
1358
1359# define STATX(path, st, mask) statx(AT_FDCWD, path, 0, mask, st)
1360
1361# ifndef HAVE_STATX
1362# ifdef HAVE_SYSCALL_H
1363# include <syscall.h>
1364# elif defined HAVE_SYS_SYSCALL_H
1365# include <sys/syscall.h>
1366# endif
1367# if defined __linux__
1368# include <linux/stat.h>
1369static inline int
1370statx(int dirfd, const char *pathname, int flags,
1371 unsigned int mask, struct statx *statxbuf)
1372{
1373 return (int)syscall(__NR_statx, dirfd, pathname, flags, mask, statxbuf);
1374}
1375# endif /* __linux__ */
1376# endif /* HAVE_STATX */
1377
1378typedef struct no_gvl_rb_io_stat_data {
1379 struct statx *stx;
1380 int fd;
1381 const char *path;
1382 int flags;
1383 unsigned int mask;
1384} no_gvl_rb_io_stat_data;
1385
1386static VALUE
1387io_blocking_statx(void *data)
1388{
1389 no_gvl_rb_io_stat_data *arg = data;
1390 return (VALUE)statx(arg->fd, arg->path, arg->flags, arg->mask, arg->stx);
1391}
1392
1393static void *
1394no_gvl_statx(void *data)
1395{
1396 return (void *)io_blocking_statx(data);
1397}
1398
1399static int
1400statx_without_gvl(const char *path, rb_io_stat_data *stx, unsigned int mask)
1401{
1402 no_gvl_rb_io_stat_data data = {stx, AT_FDCWD, path, 0, mask};
1403
1404 /* call statx(2) with pathname */
1405 return IO_WITHOUT_GVL_INT(no_gvl_statx, &data);
1406}
1407
1408static int
1409lstatx_without_gvl(const char *path, rb_io_stat_data *stx, unsigned int mask)
1410{
1411 no_gvl_rb_io_stat_data data = {stx, AT_FDCWD, path, AT_SYMLINK_NOFOLLOW, mask};
1412
1413 /* call statx(2) with pathname */
1414 return IO_WITHOUT_GVL_INT(no_gvl_statx, &data);
1415}
1416
1417static int
1418fstatx_without_gvl(rb_io_t *fptr, rb_io_stat_data *stx, unsigned int mask)
1419{
1420 no_gvl_rb_io_stat_data data = {stx, fptr->fd, "", AT_EMPTY_PATH, mask};
1421
1422 /* call statx(2) with fd */
1423 return (int)rb_io_blocking_region(fptr, io_blocking_statx, &data);
1424}
1425
1426#define FSTATX(fd, st) statx(fd, "", AT_EMPTY_PATH, STATX_ALL, st)
1427
1428static int
1429rb_statx(VALUE file, struct statx *stx, unsigned int mask)
1430{
1431 VALUE tmp;
1432 int result;
1433
1434 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1435 if (!NIL_P(tmp)) {
1436 rb_io_t *fptr;
1437
1438 GetOpenFile(tmp, fptr);
1439 result = fstatx_without_gvl(fptr, stx, mask);
1440 file = tmp;
1441 }
1442 else {
1443 FilePathValue(file);
1444 file = rb_str_encode_ospath(file);
1445 result = statx_without_gvl(RSTRING_PTR(file), stx, mask);
1446 }
1447 RB_GC_GUARD(file);
1448 return result;
1449}
1450
1451# define statx_has_birthtime(st) ((st)->stx_mask & STATX_BTIME)
1452
1453NORETURN(static void statx_notimplement(const char *field_name));
1454
1455/* rb_notimplement() shows "function is unimplemented on this machine".
1456 It is not applicable to statx which behavior depends on the filesystem. */
1457static void
1458statx_notimplement(const char *field_name)
1459{
1460 rb_raise(rb_eNotImpError,
1461 "%s is unimplemented on this filesystem",
1462 field_name);
1463}
1464
1465static VALUE
1466statx_birthtime(const rb_io_stat_data *stx)
1467{
1468 if (!statx_has_birthtime(stx)) {
1469 /* birthtime is not supported on the filesystem */
1470 statx_notimplement("birthtime");
1471 }
1472 return rb_time_nano_new((time_t)stx->stx_btime.tv_sec, stx->stx_btime.tv_nsec);
1473}
1474
1475#else
1476
1477# define statx_without_gvl(path, st, mask) stat_without_gvl(path, st)
1478# define fstatx_without_gvl(fptr, st, mask) fstat_without_gvl(fptr, st)
1479# define lstatx_without_gvl(path, st, mask) lstat_without_gvl(path, st)
1480# define rb_statx(file, stx, mask) rb_stat(file, stx)
1481# define STATX(path, st, mask) STAT(path, st)
1482
1483#if defined(HAVE_STAT_BIRTHTIME)
1484# define statx_has_birthtime(st) 1
1485#else
1486# define statx_has_birthtime(st) 0
1487#endif
1488
1489#endif /* !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1490 defined(HAVE_STRUCT_STATX_STX_BTIME) */
1491
1492#ifndef FSTAT
1493# define FSTAT(fd, st) fstat(fd, st)
1494#endif
1495
1496static int
1497rb_stat(VALUE file, struct stat *st)
1498{
1499 VALUE tmp;
1500 int result;
1501
1502 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1503 if (!NIL_P(tmp)) {
1504 rb_io_t *fptr;
1505
1506 GetOpenFile(tmp, fptr);
1507 result = fstat_without_gvl(fptr, st);
1508 file = tmp;
1509 }
1510 else {
1511 FilePathValue(file);
1512 file = rb_str_encode_ospath(file);
1513 result = stat_without_gvl(RSTRING_PTR(file), st);
1514 }
1515 RB_GC_GUARD(file);
1516 return result;
1517}
1518
1519/*
1520 * :markup: markdown
1521 *
1522 * call-seq:
1523 * File.stat(path) -> stat
1524 *
1525 * Returns a new File::Stat object for the entry at `path`.
1526 * Unlike File.lstat, _does follow_ [symbolic links](file/symbolic_links.md);
1527 * therefore if the entry is a symbolic link,
1528 * the returned object contains information for the target entry, not the symbolic link:
1529 *
1530 * ```ruby
1531 * filepath = '/etc/passwd'
1532 * linkpath = '/tmp/foo'
1533 * File.symlink(filepath, linkpath)
1534 * # Method File.stat follows the symlink, so the birthtimes are the same.
1535 * File.stat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1536 * File.stat(linkpath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1537 * # Method File.lstat does not follow the symlink, so the birthtimes are different.
1538 * File.lstat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1539 * File.lstat(linkpath).birthtime # => 2026-09-23 14:01:18.248754979 -0500
1540 * File.delete(linkpath) # Clean up.
1541 * ```
1542 *
1543 */
1544
1545static VALUE
1546rb_file_s_stat(VALUE klass, VALUE fname)
1547{
1548 rb_io_stat_data st;
1549
1550 FilePathValue(fname);
1551 fname = rb_str_encode_ospath(fname);
1552 if (statx_without_gvl(RSTRING_PTR(fname), &st, STATX_ALL) < 0) {
1553 rb_sys_fail_path(fname);
1554 }
1555 return rb_statx_new(&st);
1556}
1557
1558/*
1559 * :markup: markdown
1560 *
1561 * call-seq:
1562 * stat -> stat
1563 *
1564 * Returns a new File::Stat object for `self`.
1565 * Unlike File#lstat, _does follow_ symbolic links;
1566 * therefore if `self` is a symbolic link,
1567 * the returned object contains information for the target entry, not `self`:
1568 *
1569 * ```ruby
1570 * file_path = '/etc/passwd'
1571 * link_path = '/tmp/foo'
1572 * File.symlink(file_path, link_path)
1573 * file = File.new(file_path) # => #<File:/etc/passwd>
1574 * link = File.new(link_path) # => #<File:/tmp/foo>
1575 * # Method stat does follow the symlink, so the birthtimes are the same.
1576 * file.stat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1577 * link.stat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1578 * # Method lstat does not follow the symlink, so the birthtimes are different.
1579 * file.lstat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1580 * link.lstat.birthtime # => 2026-09-23 16:35:59.321566598 -0500
1581 * File.delete(link_path) # Clean up.
1582 * ```
1583 *
1584 */
1585
1586static VALUE
1587rb_io_stat(VALUE obj)
1588{
1589 rb_io_t *fptr;
1590 rb_io_stat_data st;
1591
1592 GetOpenFile(obj, fptr);
1593 if (fstatx_without_gvl(fptr, &st, STATX_ALL) == -1) {
1594 rb_sys_fail_path(fptr->pathv);
1595 }
1596 return rb_statx_new(&st);
1597}
1598
1599#ifdef HAVE_LSTAT
1600static void *
1601no_gvl_lstat(void *ptr)
1602{
1603 no_gvl_stat_data *arg = ptr;
1604 return (void *)(VALUE)lstat(arg->file.path, arg->st);
1605}
1606
1607static int
1608lstat_without_gvl(const char *path, struct stat *st)
1609{
1610 no_gvl_stat_data data;
1611
1612 data.file.path = path;
1613 data.st = st;
1614
1615 return IO_WITHOUT_GVL_INT(no_gvl_lstat, &data);
1616}
1617#endif /* HAVE_LSTAT */
1618
1619/*
1620 * :markup: markdown
1621 *
1622 * call-seq:
1623 * File.lstat(path) -> stat
1624 *
1625 * Returns a new File::Stat object for the entry at `path`.
1626 * Unline File.stat, _does not follow_ [symbolic links](file/symbolic_links.md);
1627 * therefore the returned object contains information for the entry at `path`,
1628 * regardless of whether is a symbolic link:
1629 *
1630 * ```ruby
1631 * filepath = '/etc/passwd'
1632 * linkpath = '/tmp/foo'
1633 * File.symlink(filepath, linkpath)
1634 * # Method File.lstat does not follow the symlink, so the birthtimes are different.
1635 * File.lstat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1636 * File.lstat(linkpath).birthtime # => 2026-09-23 14:01:18.248754979 -0500
1637 * # Method File.stat follows the symlink, so the birthtimes are the same.
1638 * File.stat(filepath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1639 * File.stat(linkpath).birthtime # => 2025-06-10 11:10:47.358999941 -0500
1640 * File.delete(linkpath) # Clean up.
1641 * ```
1642 *
1643 */
1644
1645static VALUE
1646rb_file_s_lstat(VALUE klass, VALUE fname)
1647{
1648#ifdef HAVE_LSTAT
1649 rb_io_stat_data st;
1650
1651 FilePathValue(fname);
1652 fname = rb_str_encode_ospath(fname);
1653 if (lstatx_without_gvl(StringValueCStr(fname), &st, STATX_ALL) == -1) {
1654 rb_sys_fail_path(fname);
1655 }
1656 return rb_statx_new(&st);
1657#else
1658 return rb_file_s_stat(klass, fname);
1659#endif
1660}
1661
1662/*
1663 * :markup: markdown
1664
1665 * call-seq:
1666 * lstat -> stat
1667 *
1668 * Returns a new File::Stat object for `self`.
1669 * Unlike File#stat, _does not follow_ symbolic links;
1670 * therefore if `self` is a symbolic link,
1671 * the returned object contains information for `self`, not the target entry:
1672 *
1673 * ```ruby
1674 * file_path = '/etc/passwd'
1675 * link_path = '/tmp/foo'
1676 * File.symlink(file_path, link_path)
1677 * file = File.new(file_path) # => #<File:/etc/passwd>
1678 * link = File.new(link_path) # => #<File:/tmp/foo>
1679 * # Method lstat does not follow the symlink, so the birthtimes are different.
1680 * file.lstat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1681 * link.lstat.birthtime # => 2026-09-23 16:35:59.321566598 -0500
1682 * # Method stat does follow the symlink, so the birthtimes are the same.
1683 * file.stat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1684 * link.stat.birthtime # => 2025-06-10 11:10:47.358999941 -0500
1685 * File.delete(link_path) # Clean up.
1686 * ```
1687 *
1688 */
1689
1690static VALUE
1691rb_file_lstat(VALUE obj)
1692{
1693#ifdef HAVE_LSTAT
1694 rb_io_t *fptr;
1695 rb_io_stat_data st;
1696 VALUE path;
1697
1698 GetOpenFile(obj, fptr);
1699 if (NIL_P(fptr->pathv)) return Qnil;
1700 path = rb_str_encode_ospath(fptr->pathv);
1701 if (lstatx_without_gvl(RSTRING_PTR(path), &st, STATX_ALL) == -1) {
1702 rb_sys_fail_path(fptr->pathv);
1703 }
1704 return rb_statx_new(&st);
1705#else
1706 return rb_io_stat(obj);
1707#endif
1708}
1709
1710static int
1711rb_group_member(GETGROUPS_T gid)
1712{
1713#if !defined(HAVE_GETGROUPS)
1714 return FALSE;
1715#else
1716 int rv = FALSE;
1717 int groups;
1718 VALUE v = 0;
1719 GETGROUPS_T *gary;
1720 int anum = -1;
1721
1722 if (getgid() == gid || getegid() == gid)
1723 return TRUE;
1724
1725 groups = getgroups(0, NULL);
1726 gary = ALLOCV_N(GETGROUPS_T, v, groups);
1727 anum = getgroups(groups, gary);
1728 while (--anum >= 0) {
1729 if (gary[anum] == gid) {
1730 rv = TRUE;
1731 break;
1732 }
1733 }
1734 if (v)
1735 ALLOCV_END(v);
1736
1737 return rv;
1738#endif /* !defined(HAVE_GETGROUPS) */
1739}
1740
1741#ifndef S_IXUGO
1742# define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
1743#endif
1744
1745#if defined(S_IXGRP) && !defined(_WIN32) && !defined(__CYGWIN__)
1746#define USE_GETEUID 1
1747#endif
1748
1749#ifndef HAVE_EACCESS
1750int
1751eaccess(const char *path, int mode)
1752{
1753#ifdef USE_GETEUID
1754 struct stat st;
1755 rb_uid_t euid;
1756
1757 euid = geteuid();
1758
1759 /* no setuid nor setgid. run shortcut. */
1760 if (getuid() == euid && getgid() == getegid())
1761 return access(path, mode);
1762
1763 if (STAT(path, &st) < 0)
1764 return -1;
1765
1766 if (euid == 0) {
1767 /* Root can read or write any file. */
1768 if (!(mode & X_OK))
1769 return 0;
1770
1771 /* Root can execute any file that has any one of the execute
1772 bits set. */
1773 if (st.st_mode & S_IXUGO)
1774 return 0;
1775
1776 return -1;
1777 }
1778
1779 if (st.st_uid == euid) /* owner */
1780 mode <<= 6;
1781 else if (rb_group_member(st.st_gid))
1782 mode <<= 3;
1783
1784 if ((int)(st.st_mode & mode) == mode) return 0;
1785
1786 return -1;
1787#else
1788 return access(path, mode);
1789#endif /* USE_GETEUID */
1790}
1791#endif /* HAVE_EACCESS */
1792
1794 const char *path;
1795 int mode;
1796};
1797
1798static void *
1799nogvl_eaccess(void *ptr)
1800{
1801 struct access_arg *aa = ptr;
1802
1803 return (void *)(VALUE)eaccess(aa->path, aa->mode);
1804}
1805
1806static int
1807rb_eaccess(VALUE fname, int mode)
1808{
1809 struct access_arg aa;
1810
1811 FilePathValue(fname);
1812 fname = rb_str_encode_ospath(fname);
1813 aa.path = StringValueCStr(fname);
1814 aa.mode = mode;
1815
1816 return IO_WITHOUT_GVL_INT(nogvl_eaccess, &aa);
1817}
1818
1819static void *
1820nogvl_access(void *ptr)
1821{
1822 struct access_arg *aa = ptr;
1823
1824 return (void *)(VALUE)access(aa->path, aa->mode);
1825}
1826
1827static int
1828rb_access(VALUE fname, int mode)
1829{
1830 struct access_arg aa;
1831
1832 FilePathValue(fname);
1833 fname = rb_str_encode_ospath(fname);
1834 aa.path = StringValueCStr(fname);
1835 aa.mode = mode;
1836
1837 return IO_WITHOUT_GVL_INT(nogvl_access, &aa);
1838}
1839
1840/*
1841 * Document-class: FileTest
1842 *
1843 * FileTest implements file test operations similar to those used in
1844 * File::Stat. It exists as a standalone module, and its methods are
1845 * also insinuated into the File class. (Note that this is not done
1846 * by inclusion: the interpreter cheats).
1847 *
1848 */
1849
1850/*
1851 * call-seq:
1852 * File.directory?(object) -> true or false
1853 *
1854 * Returns whether the given +object+ represents a directory;
1855 * +object+ may be a string path or an IO object:
1856 *
1857 * File.directory?('/etc') # => true
1858 * File.directory?('lib') # => true
1859 * File.directory?('README.md') # => false
1860 * File.directory?('nosuch') # => false
1861 * File.directory?($stdin) # => false
1862 *
1863 * Follows symbolic links:
1864 *
1865 * dirpath = 'doc/dirname'
1866 * File.symlink('.', dirpath)
1867 * File.directory?(dirpath) # => true
1868 * File.unlink(dirpath)
1869 * filepath = 't.tmp'
1870 * File.symlink('README.md', filepath)
1871 * File.directory?(filepath) # => false
1872 * File.unlink(filepath)
1873 *
1874 */
1875
1876VALUE
1877rb_file_directory_p(VALUE obj, VALUE fname)
1878{
1879#ifndef S_ISDIR
1880# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1881#endif
1882
1883 struct stat st;
1884
1885 if (rb_stat(fname, &st) < 0) return Qfalse;
1886 if (S_ISDIR(st.st_mode)) return Qtrue;
1887 return Qfalse;
1888}
1889
1890/*
1891 * :markup: markdown
1892 *
1893 * call-seq:
1894 * File.pipe?(path) -> true or false
1895 *
1896 * Returns whether the entry at the given `path` is a pipe:
1897 *
1898 * ```ruby
1899 * File.pipe?('doc/syntax/') # => false # Directory.
1900 * File.pipe?('doc/maintainers.md') # => false # Regular file.
1901 * File.pipe?('nosuch') # => false # Non-existent.
1902 * path = '/tmp/foo'
1903 * File.mkfifo(path)
1904 * File.pipe?(path) # => true
1905 * File.delete(path) # Clean up.
1906 * ```
1907 *
1908 */
1909
1910static VALUE
1911rb_file_pipe_p(VALUE obj, VALUE fname)
1912{
1913#ifdef S_IFIFO
1914# ifndef S_ISFIFO
1915# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
1916# endif
1917
1918 struct stat st;
1919
1920 if (rb_stat(fname, &st) < 0) return Qfalse;
1921 if (S_ISFIFO(st.st_mode)) return Qtrue;
1922
1923#endif
1924 return Qfalse;
1925}
1926
1927/*
1928 * :markup: markdown
1929 *
1930 * call-seq:
1931 * File.symlink?(path) -> true or false
1932 *
1933 * Returns whether the entry at `path`
1934 * is a [symbolic link](rdoc-ref:file/symbolic_links.md):
1935 *
1936 * ```ruby
1937 * filepath = '/etc/passwd'
1938 * linkpath = '/tmp/foo'
1939 * File.symlink(filepath, linkpath)
1940 * File.symlink?(filepath) # => false
1941 * File.symlink?(linkpath) # => true
1942 * File.symlink?('.') # => false
1943 * File.delete(linkpath) # Clean up.
1944 * ```
1945 *
1946 */
1947
1948static VALUE
1949rb_file_symlink_p(VALUE obj, VALUE fname)
1950{
1951#ifndef S_ISLNK
1952# ifdef _S_ISLNK
1953# define S_ISLNK(m) _S_ISLNK(m)
1954# else
1955# ifdef _S_IFLNK
1956# define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
1957# else
1958# ifdef S_IFLNK
1959# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
1960# endif
1961# endif
1962# endif
1963#endif
1964
1965#ifdef S_ISLNK
1966 struct stat st;
1967
1968 FilePathValue(fname);
1969 fname = rb_str_encode_ospath(fname);
1970 if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse;
1971 if (S_ISLNK(st.st_mode)) return Qtrue;
1972#endif
1973
1974 return Qfalse;
1975}
1976
1977/*
1978 * :markup: markdown
1979 *
1980 * call-seq:
1981 * File.socket?(object) -> true or false
1982 *
1983 * Returns whether the given `object` represents a socket;
1984 * the `object` may be a path or an IO object:
1985 *
1986 * ```ruby
1987 * require 'socket'
1988 * sock_path = '/tmp/socket'
1989 * server = UNIXServer.new(sock_path)
1990 * File.socket?(sock_path) # => true
1991 * File.delete(sock_path) # Clean up.
1992 * file_path = '/etc/passwd'
1993 * File.file?(file_path) # => true
1994 * File.socket?(file_path) # => false
1995 * File.socket?($stdin) # => false
1996 * File.socket?('nosuch') # => false
1997 * ```
1998 *
1999 */
2000
2001static VALUE
2002rb_file_socket_p(VALUE obj, VALUE fname)
2003{
2004#ifndef S_ISSOCK
2005# ifdef _S_ISSOCK
2006# define S_ISSOCK(m) _S_ISSOCK(m)
2007# else
2008# ifdef _S_IFSOCK
2009# define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
2010# else
2011# ifdef S_IFSOCK
2012# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
2013# endif
2014# endif
2015# endif
2016#endif
2017
2018#ifdef S_ISSOCK
2019 struct stat st;
2020
2021 if (rb_stat(fname, &st) < 0) return Qfalse;
2022 if (S_ISSOCK(st.st_mode)) return Qtrue;
2023#endif
2024
2025 return Qfalse;
2026}
2027
2028/*
2029 * call-seq:
2030 * File.blockdev?(object) -> true or false
2031 *
2032 * Returns whether +object+ (a path or IO object)
2033 * represents a block device (i.e., a direct-access device):
2034 *
2035 * File.blockdev?('/dev/nvme0n1') # => true
2036 * File.blockdev?('/dev/loop0') # => true
2037 * File.blockdev?('/dev/tty') # => false
2038 * File.blockdev?('/dev/null') # => false
2039 * File.blockdev?('nosuch') # => false
2040 * File.blockdev?($stdin) # => false
2041 *
2042 * The returned value is filesystem-dependent; on Windows, always +false+.
2043 */
2044
2045static VALUE
2046rb_file_blockdev_p(VALUE obj, VALUE fname)
2047{
2048#ifndef S_ISBLK
2049# ifdef S_IFBLK
2050# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
2051# else
2052# define S_ISBLK(m) (0) /* anytime false */
2053# endif
2054#endif
2055
2056#ifdef S_ISBLK
2057 struct stat st;
2058
2059 if (rb_stat(fname, &st) < 0) return Qfalse;
2060 if (S_ISBLK(st.st_mode)) return Qtrue;
2061
2062#endif
2063 return Qfalse;
2064}
2065
2066/*
2067 * call-seq:
2068 * File.chardev?(object) -> true or false
2069 *
2070 * Returns whether +object+ (a path or IO object)
2071 * represents a character device (i.e., a sequential-access device):
2072 *
2073 * File.chardev?('/dev/tty') # => true
2074 * File.chardev?('/dev/null') # => true
2075 * File.chardev?($stdin) # => true
2076 * File.chardev?('/dev/nvme0n1') # => false
2077 * File.chardev?('/dev/loop0') # => false
2078 * File.chardev?('nosuch') # => false
2079 *
2080 *
2081 * The returned value is filesystem-dependent; on Windows, always +false+.
2082 */
2083static VALUE
2084rb_file_chardev_p(VALUE obj, VALUE fname)
2085{
2086#ifndef S_ISCHR
2087# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
2088#endif
2089
2090 struct stat st;
2091
2092 if (rb_stat(fname, &st) < 0) return Qfalse;
2093 if (S_ISCHR(st.st_mode)) return Qtrue;
2094
2095 return Qfalse;
2096}
2097
2098/*
2099 * call-seq:
2100 * File.exist?(object) -> true or false
2101 *
2102 * Return whether the specified +object+, a string path or IO object, exists:
2103 *
2104 * # String paths.
2105 * File.exist?('README.md') # => true
2106 * File.exist?('.') # => true
2107 * filepath = 't.tmp'
2108 * File.exist?(filepath) # => false
2109 * File.write(filepath, 'foo')
2110 * File.exist?(filepath) # => true
2111 * # File (IO object).
2112 * file = File.new(filepath)
2113 * File.exist?(file) # => true
2114 * file.close # Clean up.
2115 * File.unlink(filepath) # Clean up.
2116 *
2117 * Follows symbolic links:
2118 *
2119 * # Symbolic links.
2120 * File.symlink('README.md', 'README.link')
2121 * File.symlink('nosuch', 'BROKEN.link')
2122 * File.exist?('README.link') # => true
2123 * File.exist?('BROKEN.link') # => false
2124 * File.unlink('README.link') # Clean up.
2125 * File.unlink('BROKEN.link') # Clean up.
2126 *
2127 */
2128
2129static VALUE
2130rb_file_exist_p(VALUE obj, VALUE fname)
2131{
2132 struct stat st;
2133
2134 if (rb_stat(fname, &st) < 0) return Qfalse;
2135 return Qtrue;
2136}
2137
2138/*
2139 * :markup: markdown
2140 *
2141 * call-seq:
2142 * File.readable?(path) -> true or false
2143 *
2144 * Returns whether the entry at the given `path`
2145 * exists and is readable by the owner and group of the current process;
2146 * see [Permissions](rdoc-ref:file/filesystem_modes.md@Permissions):
2147 *
2148 * ```ruby
2149 * path = '/tmp/secret.txt'
2150 * File.write(path, 'foo')
2151 * File.readable?(path) # => true
2152 * File.chmod(0o000, path)
2153 * File.readable?(path) # => false
2154 * File.delete(path) # Clean up.
2155 * File.readable?('nosuch') # => false
2156 * ```
2157 *
2158 */
2159
2160static VALUE
2161rb_file_readable_p(VALUE obj, VALUE fname)
2162{
2163 return RBOOL(rb_eaccess(fname, R_OK) >= 0);
2164}
2165
2166/*
2167 * :markup: markdown
2168 *
2169 * call-seq:
2170 * File.readable_real?(path) -> true or false
2171 *
2172 * Like File.readable?, but checks against the real user and group ids
2173 * instead of the effective ids.
2174 */
2175
2176static VALUE
2177rb_file_readable_real_p(VALUE obj, VALUE fname)
2178{
2179 return RBOOL(rb_access(fname, R_OK) >= 0);
2180}
2181
2182#ifndef S_IRUGO
2183# define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
2184#endif
2185
2186#ifndef S_IWUGO
2187# define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
2188#endif
2189
2190/*
2191 * call-seq:
2192 * File.world_readable?(file_name) -> integer or nil
2193 *
2194 * If <i>file_name</i> is readable by others, returns an integer
2195 * representing the file permission bits of <i>file_name</i>. Returns
2196 * +nil+ otherwise. The meaning of the bits is platform dependent; on
2197 * Unix systems, see <code>stat(2)</code>.
2198 *
2199 * _file_name_ can be an IO object.
2200 *
2201 * File.world_readable?("/etc/passwd") #=> 420
2202 * m = File.world_readable?("/etc/passwd")
2203 * sprintf("%o", m) #=> "644"
2204 */
2205
2206static VALUE
2207rb_file_world_readable_p(VALUE obj, VALUE fname)
2208{
2209#ifdef S_IROTH
2210 struct stat st;
2211
2212 if (rb_stat(fname, &st) < 0) return Qnil;
2213 if ((st.st_mode & (S_IROTH)) == S_IROTH) {
2214 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
2215 }
2216#endif
2217 return Qnil;
2218}
2219
2220/*
2221 * call-seq:
2222 * File.writable?(file_name) -> true or false
2223 *
2224 * Returns +true+ if the named file is writable by the effective user and
2225 * group id of this process. See <code>eaccess(3)</code>.
2226 *
2227 * Note that some OS-level security features may cause this to return true
2228 * even though the file is not writable by the effective user/group.
2229 */
2230
2231static VALUE
2232rb_file_writable_p(VALUE obj, VALUE fname)
2233{
2234 return RBOOL(rb_eaccess(fname, W_OK) >= 0);
2235}
2236
2237/*
2238 * call-seq:
2239 * File.writable_real?(file_name) -> true or false
2240 *
2241 * Returns +true+ if the named file is writable by the real user and group id
2242 * of this process. See <code>access(3)</code>.
2243 *
2244 * Note that some OS-level security features may cause this to return true
2245 * even though the file is not writable by the real user/group.
2246 */
2247
2248static VALUE
2249rb_file_writable_real_p(VALUE obj, VALUE fname)
2250{
2251 return RBOOL(rb_access(fname, W_OK) >= 0);
2252}
2253
2254/*
2255 * call-seq:
2256 * File.world_writable?(file_name) -> integer or nil
2257 *
2258 * If <i>file_name</i> is writable by others, returns an integer
2259 * representing the file permission bits of <i>file_name</i>. Returns
2260 * +nil+ otherwise. The meaning of the bits is platform dependent; on
2261 * Unix systems, see <code>stat(2)</code>.
2262 *
2263 * _file_name_ can be an IO object.
2264 *
2265 * File.world_writable?("/tmp") #=> 511
2266 * m = File.world_writable?("/tmp")
2267 * sprintf("%o", m) #=> "777"
2268 */
2269
2270static VALUE
2271rb_file_world_writable_p(VALUE obj, VALUE fname)
2272{
2273#ifdef S_IWOTH
2274 struct stat st;
2275
2276 if (rb_stat(fname, &st) < 0) return Qnil;
2277 if ((st.st_mode & (S_IWOTH)) == S_IWOTH) {
2278 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
2279 }
2280#endif
2281 return Qnil;
2282}
2283
2284/*
2285 * call-seq:
2286 * File.executable?(path) -> true or false
2287 *
2288 * Returns whether the filesystem entry at the given string +path+
2289 * exists and is executable.
2290 *
2291 * On Windows, the entry is executable if its path has file extension
2292 * +.bat+, +.cmd+, +.com+, or +.exe+:
2293 *
2294 * File.executable?('win32/rtname.cmd') # => true
2295 * File.executable?('win32/rtname') # => false
2296 * File.executable?('win32/nosuch.cmd') # => false
2297 *
2298 * On other systems, the entry is executable if it has the execute/search
2299 * permission for the effective user and group id of the current process;
2300 * see {Permissions}[rdoc-ref:file/filesystem_modes.md@Permissions].
2301 *
2302 * These examples use
2303 * a {helper method}[rdoc-ref:file/filesystem_modes.md@Helper+Method], +mode+,
2304 * that displays a mode both in octal digits and in characters:
2305 *
2306 * File.executable?('.') # => true
2307 * mode('.') # => "040775 drwxrwxr-x"
2308 * File.executable?('bin/gem') # => true
2309 * mode('bin/gem') # => "100775 -rwxrwxr-x"
2310 * File.executable?('/etc/passwd') # => false
2311 * mode('/etc/passwd') # => "100644 -rw-r--r--"
2312 * File.executable?('nosuch') # => false
2313 *
2314 * Note that some filesystem settings may cause this method to return +true+
2315 * even though the entry is not executable by the effective user/group.
2316 */
2317
2318static VALUE
2319rb_file_executable_p(VALUE obj, VALUE fname)
2320{
2321 return RBOOL(rb_eaccess(fname, X_OK) >= 0);
2322}
2323
2324/*
2325 * call-seq:
2326 * File.executable_real?(file_name) -> true or false
2327 *
2328 * Returns +true+ if the named file is executable by the real user and group
2329 * id of this process. See <code>access(3)</code>.
2330 *
2331 * Windows does not support execute permissions separately from read
2332 * permissions. On Windows, a file is only considered executable if it ends in
2333 * .bat, .cmd, .com, or .exe.
2334 *
2335 * Note that some OS-level security features may cause this to return true
2336 * even though the file is not executable by the real user/group.
2337 */
2338
2339static VALUE
2340rb_file_executable_real_p(VALUE obj, VALUE fname)
2341{
2342 return RBOOL(rb_access(fname, X_OK) >= 0);
2343}
2344
2345#ifndef S_ISREG
2346# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
2347#endif
2348
2349/*
2350 * call-seq:
2351 * File.file?(object) -> true or false
2352 *
2353 * Returns whether the given +object+, a string path or IO object,
2354 * represents a filesystem entry that exists and is a regular file;
2355 * see File.ftype:
2356 *
2357 * # Paths.
2358 * File.file?('README.md') # => true
2359 * File.file?('doc/') # => false
2360 * File.file?('nosuch') # => false
2361 * # IO objects.
2362 * file = File.new('README.md')
2363 * File.file?(file) # => true
2364 * dir = Dir.new('doc/')
2365 * File.file?(dir) # => false
2366 * # Clean up.
2367 * file.close
2368 * dir.close
2369 *
2370 */
2371
2372static VALUE
2373rb_file_file_p(VALUE obj, VALUE fname)
2374{
2375 struct stat st;
2376
2377 if (rb_stat(fname, &st) < 0) return Qfalse;
2378 return RBOOL(S_ISREG(st.st_mode));
2379}
2380
2381/*
2382 * call-seq:
2383 * File.empty?(object) -> true or false
2384 * File.zero?(object) -> true or false
2385 *
2386 * Returns whether the given +object+ exists and has size zero.
2387 *
2388 * The given +object+ may be the path to a directory (possibly non-existent):
2389 *
2390 * dirpath = 'foo'
2391 * File.empty?(dirpath) # => false # Directory does not exist.
2392 * dir = Dir.mkdir(dirpath)
2393 * # The directory size is filesystem-dependent;
2394 * # for a directory with no children, may or may not be zero.
2395 * File.size(dirpath) # => 4096
2396 * File.empty?(dirpath) # => false
2397 *
2398 * The given +object+ may be the path to a file (possibly non-existent):
2399 *
2400 * filepath = File.join(dirpath, 't.tmp')
2401 * File.empty?(filepath) # => false # File does not exist.
2402 * File.write(filepath, '')
2403 * File.size(filepath) # => 0
2404 * File.empty?(filepath) # => true # File exists; size zero.
2405 * File.size(dirpath) # => 4096
2406 * File.empty?(dirpath) # => false
2407 * File.write(filepath, 'bar')
2408 * File.size(filepath) # => 3
2409 * File.empty?(filepath) # => false # File exists; size non-zero.
2410 * FileUtils.rm_rf(dirpath) # Clean up.
2411 *
2412 * The given +object+ may be an IO object:
2413 *
2414 * File.empty?($stdin) # => true
2415 *
2416 */
2417
2418static VALUE
2419rb_file_zero_p(VALUE obj, VALUE fname)
2420{
2421 struct stat st;
2422
2423 if (rb_stat(fname, &st) < 0) return Qfalse;
2424 return RBOOL(st.st_size == 0);
2425}
2426
2427/*
2428 * :markup: markdown
2429 *
2430 * call-seq:
2431 * File.size?(object) -> integer or nil
2432 *
2433 * Returns the size in bytes of the given `object`
2434 * if the entry exists and has non-zero size, `nil` otherwise;
2435 * the `object` may be a path or an IO object:
2436 *
2437 * ```ruby
2438 * # Regular file.
2439 * path = '/tmp/t.tmp'
2440 * File.write(path, 'foo')
2441 * File.size?(path) # => 3 # Non-zero size.
2442 * File.write(path, '')
2443 * File.size?(path) # => nil # Zero size.
2444 * File.delete(path) # Clean up.
2445 * File.size?(path) # => nil # Non-existent.
2446 * # Directory.
2447 * path = '/tmp/foo/'
2448 * Dir.mkdir(path)
2449 * File.size?(path) # => 4096 # Non-zero size.
2450 * Dir.rmdir(path) # Clean up.
2451 * File.size?(path) # => nil # Non-existent.
2452 * ```
2453 *
2454 */
2455
2456static VALUE
2457rb_file_size_p(VALUE obj, VALUE fname)
2458{
2459 struct stat st;
2460
2461 if (rb_stat(fname, &st) < 0) return Qnil;
2462 if (st.st_size == 0) return Qnil;
2463 return OFFT2NUM(st.st_size);
2464}
2465
2466/*
2467 * :markup: markdown
2468 *
2469 * call-seq:
2470 * File.owned?(object) -> true or false
2471 *
2472 * Returns whether the given `object` represents a filesystem entry or IO object
2473 * that exists and is owned by the user of the current process:
2474 *
2475 * ```ruby
2476 * filepath = 'doc/t.tmp'
2477 * File.write(filepath, 'foo')
2478 * File.owned?(filepath) # => true
2479 * File.delete(filepath) # Clean up.
2480 * dirpath = 'doc/tmp'
2481 * Dir.mkdir(dirpath)
2482 * File.owned?(dirpath) # => true
2483 * Dir.rmdir(dirpath) # Clean up.
2484 * File.owned?($stdin) # => true
2485 * File.owned?('/etc') # => false
2486 * ```
2487 *
2488 */
2489
2490static VALUE
2491rb_file_owned_p(VALUE obj, VALUE fname)
2492{
2493 struct stat st;
2494
2495 if (rb_stat(fname, &st) < 0) return Qfalse;
2496 return RBOOL(st.st_uid == geteuid());
2497}
2498
2499static VALUE
2500rb_file_rowned_p(VALUE obj, VALUE fname)
2501{
2502 struct stat st;
2503
2504 if (rb_stat(fname, &st) < 0) return Qfalse;
2505 return RBOOL(st.st_uid == getuid());
2506}
2507
2508/*
2509 * call-seq:
2510 * File.grpowned?(object) -> true or false
2511 *
2512 * Returns whether the filesystem entry for the given +object+ exists,
2513 * and the effective group id of the calling process is the owner of the entry.
2514 *
2515 * The given +object+ may be the string path to a file or directory entry:
2516 *
2517 * File.grpowned?('lib') # => true
2518 * File.grpowned?('README.md') # => true
2519 * File.grpowned?('/etc/passwd') # => false
2520 * File.grpowned?('nosuch') # => false
2521 *
2522 * Or an open IO stream:
2523 *
2524 * File.open('README.md', 'r') {|file| File.grpowned?(file) } # => true
2525 * File.open('/etc/passwd', 'r') {|file| File.grpowned?(file) } # => false
2526 *
2527 * Returns +false+ on Windows.
2528 */
2529
2530static VALUE
2531rb_file_grpowned_p(VALUE obj, VALUE fname)
2532{
2533#ifndef _WIN32
2534 struct stat st;
2535
2536 if (rb_stat(fname, &st) < 0) return Qfalse;
2537 if (rb_group_member(st.st_gid)) return Qtrue;
2538#endif
2539 return Qfalse;
2540}
2541
2542#if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2543static VALUE
2544check3rdbyte(VALUE fname, int mode)
2545{
2546 struct stat st;
2547
2548 if (rb_stat(fname, &st) < 0) return Qfalse;
2549 return RBOOL(st.st_mode & mode);
2550}
2551#endif
2552
2553/*
2554 * :markup: markdown
2555 *
2556 * call-seq:
2557 * File.setuid?(object) -> true or false
2558 *
2559 * Returns whether the setuid bit is set
2560 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
2561 * for the given `object`, which may be a path or an IO object:
2562 *
2563 * ```ruby
2564 * path = '/tmp/t.tmp'
2565 * File.write(path, 'foo')
2566 * mode = File.stat(path).mode.to_s(8) # => "100664"
2567 * File.setuid?(path) # => false
2568 * File.chmod(0o4644, path) # Set the bit.
2569 * mode = File.stat(path).mode.to_s(8) # => "104644"
2570 * File.setuid?(path) # => true
2571 * File.delete(path) # Clean up.
2572 * File.setuid?($stdin) # => false
2573 * ```
2574 *
2575 * On Windows, the bit is never set; the method always returns `false`.
2576 */
2577
2578static VALUE
2579rb_file_suid_p(VALUE obj, VALUE fname)
2580{
2581#ifdef S_ISUID
2582 return check3rdbyte(fname, S_ISUID);
2583#else
2584 return Qfalse;
2585#endif
2586}
2587
2588/*
2589 * :markup: markdown
2590 *
2591 * call-seq:
2592 * File.setgid?(object) -> true or false
2593 *
2594 * Returns whether the setgid bit is set
2595 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
2596 * for the given `object`, which may be a path or an IO object:
2597 *
2598 * ```ruby
2599 * path = '/tmp/t.tmp'
2600 * File.write(path, 'foo')
2601 * mode = File.stat(path).mode.to_s(8) # => "100664"
2602 * File.setgid?(path) # => false
2603 * File.chmod(0o2644, path) # Set the bit.
2604 * mode = File.stat(path).mode.to_s(8) # => "102644"
2605 * File.setgid?(path) # => true
2606 * File.delete(path) # Clean up.
2607 * File.setgid?($stdin) # => false
2608 * ```
2609 *
2610 * On Windows, the bit is never set; the method always returns `false`.
2611 */
2612
2613static VALUE
2614rb_file_sgid_p(VALUE obj, VALUE fname)
2615{
2616#ifdef S_ISGID
2617 return check3rdbyte(fname, S_ISGID);
2618#else
2619 return Qfalse;
2620#endif
2621}
2622
2623/*
2624 * :markup: markdown
2625
2626 * call-seq:
2627 * File.sticky?(object) -> true or false
2628 *
2629 * Returns whether the sticky bit is set
2630 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
2631 * for the given `object`, which may be a path or an IO object:
2632 *
2633 * ```ruby
2634 * filepath = '/tmp/t.tmp'
2635 * File.write(filepath, 'foo')
2636 * mode = File.stat(filepath).mode.to_s(8) # => "100664"
2637 * File.sticky?(filepath) # => false
2638 * File.chmod(01644, filepath) # Set sticky bit.
2639 * mode = File.stat(filepath).mode.to_s(8) # => "101644"
2640 * File.sticky?(filepath) # => true
2641 * File.delete(filepath) # Clean up.
2642 * File.sticky?($stdin) # => false
2643 * File.sticky?('nosuch') # => false
2644 * ```
2645 *
2646 * Returns `false` on Windows.
2647 */
2648
2649static VALUE
2650rb_file_sticky_p(VALUE obj, VALUE fname)
2651{
2652#ifdef S_ISVTX
2653 return check3rdbyte(fname, S_ISVTX);
2654#else
2655 return Qfalse;
2656#endif
2657}
2658
2659/*
2660 * call-seq:
2661 * File.identical?(object_0, object_1) -> true or false
2662 *
2663 * Returns whether the given objects represent filesystem entries that are identical;
2664 * each object may be a string path or an IO object:
2665 *
2666 * # Paths.
2667 * File.identical?('README.md', 'README.md') # => true # Same path.
2668 * File.identical?('README.md', './README.md') # => true # Same entry.
2669 * File.identical?('.', '.') # => true # Directory.
2670 * File.identical?('README.md', 'LEGAL') # => false
2671 * File.identical?('README.md', 'nosuch') # => false # Non-existent entry.
2672 * # Links and File object.
2673 * File.link('README.md', 'link') # Symbolic link.
2674 * File.symlink('README.md', 'symlink') # Hard link.
2675 * file = File.open('README.md', 'r') # File object.
2676 * File.identical?('README.md', 'link') # => true
2677 * File.identical?('README.md', 'symlink') # => true
2678 * File.identical?('README.md', file) # => true
2679 * # Clean up.
2680 * File.unlink('link')
2681 * File.unlink('symlink')
2682 * file.close
2683 *
2684 */
2685
2686static VALUE
2687rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2)
2688{
2689#ifndef _WIN32
2690 struct stat st1, st2;
2691
2692 if (rb_stat(fname1, &st1) < 0) return Qfalse;
2693 if (rb_stat(fname2, &st2) < 0) return Qfalse;
2694 if (st1.st_dev != st2.st_dev) return Qfalse;
2695 if (st1.st_ino != st2.st_ino) return Qfalse;
2696 return Qtrue;
2697#else
2698 extern VALUE rb_w32_file_identical_p(VALUE, VALUE);
2699 return rb_w32_file_identical_p(fname1, fname2);
2700#endif
2701}
2702
2703/*
2704 * :markup: markdown
2705 *
2706 * call-seq:
2707 * File.size(object) -> integer
2708 *
2709 * Returns the size in bytes of the given `object`,
2710 * which may be a path or an IO object:
2711 *
2712 * ```ruby
2713 * File.size('doc/maintainers.md') # => 14900 # Regular file.
2714 * File.size('doc/syntax/') # => 4096 # Directory.
2715 * File.size($stdin) # => 0 # IO object.
2716 * ```
2717 *
2718 */
2719
2720static VALUE
2721rb_file_s_size(VALUE klass, VALUE fname)
2722{
2723 struct stat st;
2724
2725 if (rb_stat(fname, &st) < 0) {
2726 int e = errno;
2727 FilePathValue(fname);
2728 rb_syserr_fail_path(e, fname);
2729 }
2730 return OFFT2NUM(st.st_size);
2731}
2732
2733static VALUE
2734rb_file_ftype(mode_t mode)
2735{
2736 const char *t;
2737
2738 if (S_ISREG(mode)) {
2739 t = "file";
2740 }
2741 else if (S_ISDIR(mode)) {
2742 t = "directory";
2743 }
2744 else if (S_ISCHR(mode)) {
2745 t = "characterSpecial";
2746 }
2747#ifdef S_ISBLK
2748 else if (S_ISBLK(mode)) {
2749 t = "blockSpecial";
2750 }
2751#endif
2752#ifdef S_ISFIFO
2753 else if (S_ISFIFO(mode)) {
2754 t = "fifo";
2755 }
2756#endif
2757#ifdef S_ISLNK
2758 else if (S_ISLNK(mode)) {
2759 t = "link";
2760 }
2761#endif
2762#ifdef S_ISSOCK
2763 else if (S_ISSOCK(mode)) {
2764 t = "socket";
2765 }
2766#endif
2767 else {
2768 t = "unknown";
2769 }
2770
2771 return rb_fstring_cstr(t);
2772}
2773
2774/*
2775 * call-seq:
2776 * File.ftype(path) -> string
2777 *
2778 * Returns the string type of the object at +path+, one of:
2779 *
2780 * - <tt>'file'</tt>.
2781 * - <tt>'directory'</tt>.
2782 * - <tt>'characterSpecial'</tt>.
2783 * - <tt>'blockSpecial'</tt>.
2784 * - <tt>'fifo'</tt>.
2785 * - <tt>'link'</tt>.
2786 * - <tt>'socket'</tt>.
2787 *
2788 * Examples:
2789 *
2790 * File.ftype('README.md') # => "file"
2791 * File.ftype('lib') # => "directory"
2792 * File.ftype("/dev/null") # => "characterSpecial"
2793 * File.ftype("/dev/loop0") # => "blockSpecial"
2794 *
2795 * File.mkfifo('/tmp/pipe', 0666)
2796 * File.ftype('/tmp/pipe') # => "fifo"
2797 *
2798 * File.symlink('lib', 'lib_link')
2799 * File.ftype('lib_link') # => "link"
2800 *
2801 * UNIXServer.new('/tmp/socket')
2802 * File.ftype('/tmp/socket') # => "socket"
2803 *
2804 * Returns <tt>'unknown'</tt> if the type cannot be determined.
2805 */
2806
2807static VALUE
2808rb_file_s_ftype(VALUE klass, VALUE fname)
2809{
2810 struct stat st;
2811
2812 FilePathValue(fname);
2813 fname = rb_str_encode_ospath(fname);
2814 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
2815 rb_sys_fail_path(fname);
2816 }
2817
2818 return rb_file_ftype(st.st_mode);
2819}
2820
2821/*
2822 * call-seq:
2823 * File.atime(object) -> time
2824 *
2825 * Returns a new Time object containing the time of the most recent
2826 * access to the given +object+.
2827 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
2828 *
2829 * Access time for a file is established when it is created,
2830 * and may be updated when the file content is read:
2831 *
2832 * filepath = 't.tmp'
2833 * File.exist?(filepath) # => false
2834 * File.atime(filepath) # Raises Errno::ENOENT.
2835 * File.write(filepath, 'foo') # Create by writing; establishes access time.
2836 * File.atime(filepath) # => 2026-08-14 10:02:39.721407762 -0500
2837 * File.read(filepath) # Read file content; updates access time.
2838 * File.atime(filepath) # => 2026-08-14 10:03:02.520494995 -0500
2839 * File.delete(filepath) # Clean up.
2840 *
2841 * Access time for a directory is established when it is created,
2842 * and may updated when its entries are read:
2843 *
2844 * dirpath = 'foo'
2845 * File.exist?(dirpath) # => false
2846 * File.atime(dirpath) # Raises Errno::ENOENT.
2847 * FileUtils.cp_r('doc', 'foo') # Create by copying; establishes access time.
2848 * File.atime(dirpath) # => 2026-08-14 10:32:59.229951125 -0500
2849 * Dir.entries(dirpath) # Read directory entries; updates access time.
2850 * File.atime(dirpath) # => 2026-08-14 10:33:05.679978581 -0500
2851 * FileUtils.rm_rf(dirpath) # Clean up.
2852 *
2853 * Argument +object+ may be a string path (as above),
2854 * a File object, or a Dir object:
2855 *
2856 * File.atime(File.new('README.md')) # => 2026-03-31 11:15:27.8215934 -0500
2857 * File.atime(Dir.new('.')) # => 2026-03-31 12:39:45.5910591 -0500
2858 *
2859 */
2860
2861static VALUE
2862rb_file_s_atime(VALUE klass, VALUE fname)
2863{
2864 struct stat st;
2865
2866 if (rb_stat(fname, &st) < 0) {
2867 int e = errno;
2868 FilePathValue(fname);
2869 rb_syserr_fail_path(e, fname);
2870 }
2871 return stat_time(stat_atimespec(&st));
2872}
2873
2874/*
2875 * call-seq:
2876 * atime -> time
2877 *
2878 * Returns a new Time object containing the time of the most recent
2879 * access to +self+.
2880 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
2881 *
2882 * Access time for a file is established when it is created,
2883 * and may be updated when the file content is read:
2884 *
2885 * filepath = 't.tmp'
2886 * File.exist?(filepath) # => false
2887 * file = File.open(filepath, 'w+') # Create by opening; establishes access time.
2888 * file.atime # => 2026-08-14 11:15:48.422773736 -0500
2889 * file.read # Read file content; updates access time.
2890 * file.atime # => 2026-08-14 11:16:10.697861103 -0500
2891 * # Clean up.
2892 * file.close
2893 * File.delete(filepath)
2894 *
2895 */
2896
2897static VALUE
2898rb_file_atime(VALUE obj)
2899{
2900 rb_io_t *fptr;
2901 struct stat st;
2902
2903 GetOpenFile(obj, fptr);
2904 if (fstat(fptr->fd, &st) == -1) {
2905 rb_sys_fail_path(fptr->pathv);
2906 }
2907 return stat_time(stat_atimespec(&st));
2908}
2909
2910/*
2911 * :markup: markdown
2912 *
2913 * call-seq:
2914 * File.mtime(object) -> time
2915 *
2916 * Returns a new Time object containing the modification time for the given object,
2917 * which may be a string path or an IO object;
2918 * see [Modification Time](rdoc-ref:file/timestamps.md@Modification+Time):
2919 *
2920 * ```ruby
2921 * # Create directory; directory mtime established.
2922 * dirpath = 'doc/foo' # => "doc/foo"
2923 * Dir.mkdir(dirpath)
2924 * File.mtime(dirpath) # => 2026-09-19 09:01:30.045928322 -0500
2925 * # Create file therein; file mtime established, directory mtime updated.
2926 * filepath = File.join(dirpath, 't.tmp') # => "doc/foo/t.tmp"
2927 * File.write(filepath, 'foo')
2928 * File.mtime(filepath) # => 2026-09-19 09:02:32.860803131 -0500
2929 * File.mtime(dirpath) # => 2026-09-19 09:02:32.860803131 -0500
2930 * # Modify file; file mtime updated, directory mtime unchanged.
2931 * File.write(filepath, 'bar')
2932 * File.mtime(filepath) # => 2026-09-19 09:03:29.875611413 -0500
2933 * File.mtime(dirpath) # => 2026-09-19 09:02:32.860803131 -0500
2934 * FileUtils.rm_rf(dirpath) # Clean up.
2935 * File.mtime($stdout) # => 2026-09-19 09:27:52 -0500
2936 * $stdout.flush
2937 * File.mtime($stdout) # => 2026-09-19 09:28:08 -0500
2938 * ```
2939 *
2940 */
2941
2942static VALUE
2943rb_file_s_mtime(VALUE klass, VALUE fname)
2944{
2945 struct stat st;
2946
2947 if (rb_stat(fname, &st) < 0) {
2948 int e = errno;
2949 FilePathValue(fname);
2950 rb_syserr_fail_path(e, fname);
2951 }
2952 return stat_time(stat_mtimespec(&st));
2953}
2954
2955/*
2956 * :markup: markdown
2957 *
2958 * call-seq:
2959 * mtime -> time
2960 *
2961 * Returns a new Time object containing the modification time for `self`;
2962 * see [Modification Time](rdoc-ref:file/timestamps.md@Modification+Time):
2963 *
2964 * ```ruby
2965 * path = 't.tmp'
2966 * file = File.new(path, 'w+')
2967 * file.mtime # => 2026-09-19 08:41:29.357110007 -0500
2968 * file.write('foo')
2969 * file.flush
2970 * file.mtime # => 2026-09-19 08:41:46.321965574 -0500
2971 * File.unlink(path)
2972 * ```
2973 *
2974 */
2975
2976static VALUE
2977rb_file_mtime(VALUE obj)
2978{
2979 rb_io_t *fptr;
2980 struct stat st;
2981
2982 GetOpenFile(obj, fptr);
2983 if (fstat(fptr->fd, &st) == -1) {
2984 rb_sys_fail_path(fptr->pathv);
2985 }
2986 return stat_time(stat_mtimespec(&st));
2987}
2988
2989/*
2990 * call-seq:
2991 * File.ctime(object) -> time
2992 *
2993 * Returns a Time object, based on the given +object+,
2994 * which is a string path or an IO object.
2995 *
2996 * On Windows, returns the #birthtime for +object+.
2997 *
2998 * On other systems,
2999 * returns a new Time object containing the time of the most recent
3000 * metadata change to the entry represented by +object+;
3001 * see {File System Timestamps}[rdoc-ref:file/timestamps.md]:
3002 *
3003 * # Create directory; directory ctime established.
3004 * dirpath = 'doc/foo'
3005 * Dir.mkdir(dirpath)
3006 * File.ctime(dirpath) # => 2026-08-23 10:43:05.473815913 -0500
3007 * # Create file therein; file ctime established; directory ctime updated.
3008 * filepath = File.join(dirpath, 't.tmp') # => "doc/foo/t.tmp"
3009 * File.write(filepath, 'foo')
3010 * File.ctime(filepath) # => 2026-08-23 10:43:37.560429379 -0500
3011 * File.ctime(dirpath) # => 2026-08-23 10:43:37.560429379 -0500
3012 * # Write file; file ctime updated; directory ctime not updated.
3013 * File.write(filepath, 'bar')
3014 * File.ctime(filepath) # => 2026-08-23 10:46:49.299180833 -0500
3015 * File.ctime(dirpath) # => 2026-08-23 10:43:37.560429379 -0500
3016 * # Read file; neither ctime updated.
3017 * File.read(filepath)
3018 * File.ctime(filepath) # => 2026-08-23 10:46:49.299180833 -0500
3019 * File.ctime(dirpath) # => 2026-08-23 10:43:37.560429379 -0500
3020 * FileUtils.rm_rf(dirpath) # Clean up.
3021 *
3022 */
3023
3024static VALUE
3025rb_file_s_ctime(VALUE klass, VALUE fname)
3026{
3027 struct stat st;
3028
3029 if (rb_stat(fname, &st) < 0) {
3030 int e = errno;
3031 FilePathValue(fname);
3032 rb_syserr_fail_path(e, fname);
3033 }
3034 return stat_time(stat_ctimespec(&st));
3035}
3036
3037/*
3038 * call-seq:
3039 * file.ctime -> time
3040 *
3041 * Returns the change time for <i>file</i> (that is, the time directory
3042 * information about the file was changed, not the file itself).
3043 *
3044 * Note that on Windows (NTFS), returns creation time (birth time).
3045 *
3046 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
3047 *
3048 */
3049
3050static VALUE
3051rb_file_ctime(VALUE obj)
3052{
3053 rb_io_t *fptr;
3054 struct stat st;
3055
3056 GetOpenFile(obj, fptr);
3057 if (fstat(fptr->fd, &st) == -1) {
3058 rb_sys_fail_path(fptr->pathv);
3059 }
3060 return stat_time(stat_ctimespec(&st));
3061}
3062
3063#if defined(HAVE_STAT_BIRTHTIME)
3064/*
3065 * call-seq:
3066 * File.birthtime(path) -> time
3067 *
3068 * Returns a new Time object containing the create time
3069 * of the entry at the given +path+;
3070 * see {File System Timestamps}[rdoc-ref:file/timestamps.md]:
3071 *
3072 * filepath = 't.tmp'
3073 * File.birthtime(filepath) # Raises Errno::ENOENT: No such file or directory
3074 * File.write(filepath, 'foo')
3075 * File.birthtime(filepath) # => 2026-04-14 11:10:43.2891695 -0500
3076 * File.write(filepath, 'bar')
3077 * File.birthtime(filepath) # => 2026-04-14 11:10:43.2891695 -0500
3078 * File.delete(filepath)
3079 * File.birthtime(filepath) # Raises Errno::ENOENT: No such file or directory.
3080 *
3081 * dirpath = 'tmp'
3082 * Dir.mkdir(dirpath)
3083 * File.birthtime(dirpath) # => 2026-08-21 13:42:19.389324172 -0500
3084 * Dir.rmdir(dirpath)
3085 * File.birthtime(dirpath) # Raises Errno::ENOENT: No such file or directory.
3086 *
3087 */
3088
3089static VALUE
3090rb_file_s_birthtime(VALUE klass, VALUE fname)
3091{
3092 rb_io_stat_data st;
3093
3094 if (rb_statx(fname, &st, STATX_BTIME) < 0) {
3095 int e = errno;
3096 FilePathValue(fname);
3097 rb_syserr_fail_path(e, fname);
3098 }
3099 return statx_birthtime(&st);
3100}
3101#else
3102# define rb_file_s_birthtime rb_f_notimplement
3103#endif
3104
3105#if defined(HAVE_STAT_BIRTHTIME)
3106/*
3107 * call-seq:
3108 * birthtime -> new_time
3109 *
3110 * Returns a new Time object containing the create time for +self+:
3111 *
3112 * filepath = 't.tmp'
3113 * File.write(filepath, 'foo')
3114 * file = File.new(filepath)
3115 * file.birthtime # => 2026-04-14 15:53:45.002656 -0500
3116 * File.write(filepath, 'bar')
3117 * file.birthtime # => 2026-04-14 15:53:45.002656 -0500
3118 * file.close
3119 * File.delete(filepath)
3120 * file.birthtime # Raises IOError: closed stream
3121 *
3122 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
3123 */
3124
3125static VALUE
3126rb_file_birthtime(VALUE obj)
3127{
3128 rb_io_t *fptr;
3129 rb_io_stat_data st;
3130
3131 GetOpenFile(obj, fptr);
3132 if (fstatx_without_gvl(fptr, &st, STATX_BTIME) == -1) {
3133 rb_sys_fail_path(fptr->pathv);
3134 }
3135 return statx_birthtime(&st);
3136}
3137#else
3138# define rb_file_birthtime rb_f_notimplement
3139#endif
3140
3141rb_off_t
3142rb_file_size(VALUE file)
3143{
3144 if (RB_TYPE_P(file, T_FILE)) {
3145 rb_io_t *fptr;
3146 struct stat st;
3147
3148 RB_IO_POINTER(file, fptr);
3149 if (fptr->mode & FMODE_WRITABLE) {
3150 rb_io_flush_raw(file, 0);
3151 }
3152
3153 if (fstat(fptr->fd, &st) == -1) {
3154 rb_sys_fail_path(fptr->pathv);
3155 }
3156
3157 return st.st_size;
3158 }
3159 else {
3160 return NUM2OFFT(rb_funcall(file, idSize, 0));
3161 }
3162}
3163
3164/*
3165 * :markup: markdown
3166 *
3167 * call-seq:
3168 * size -> integer
3169 *
3170 * Returns the size of `self` in bytes:
3171 *
3172 * ```ruby
3173 * File.new('doc/maintainers.md').size # => 14900 # Regular file.
3174 * File.new('doc/syntax/').size # => 4096 # Directory.
3175 * ```
3176 *
3177 */
3178
3179static VALUE
3180file_size(VALUE self)
3181{
3182 return OFFT2NUM(rb_file_size(self));
3183}
3184
3186 const char *path;
3187 mode_t mode;
3188};
3189
3190static void *
3191nogvl_chmod(void *ptr)
3192{
3193 struct nogvl_chmod_data *data = ptr;
3194 int ret = chmod(data->path, data->mode);
3195 return (void *)(VALUE)ret;
3196}
3197
3198static int
3199rb_chmod(const char *path, mode_t mode)
3200{
3201 struct nogvl_chmod_data data = {
3202 .path = path,
3203 .mode = mode,
3204 };
3205 return IO_WITHOUT_GVL_INT(nogvl_chmod, &data);
3206}
3207
3208static int
3209chmod_internal(const char *path, void *mode)
3210{
3211 return chmod(path, *(mode_t *)mode);
3212}
3213
3214/*
3215 * call-seq:
3216 * File.chmod(mode, *paths) -> integer
3217 *
3218 * Changes the modes of each of the entries at each the given +paths+;
3219 * returns the count of the given +paths+.
3220 * See {Filesystem Modes}[rdoc-ref:file/filesystem_modes.md]
3221 * and especially {Setting a Mode}[rdoc-ref:file/filesystem_modes.md@Setting+a+Mode].
3222 *
3223 * These examples use
3224 * a {helper method}[rdoc-ref:file/filesystem_modes.md@Helper+Method], +mode+,
3225 * that displays a mode both in octal digits and in characters:
3226 *
3227 * dirpath = 'doc/foo'
3228 * filepath = File.join(dirpath, 't.tmp')
3229 * Dir.mkdir(dirpath) # Create directory.
3230 * mode(dirpath) # => "040775 drwxrwxr-x"
3231 * File.write(filepath, 'bar') # Create file.
3232 * mode(filepath) # => "100664 -rw-rw-r--"
3233 * File.chmod(0755, filepath) # Change file mode.
3234 * mode(filepath) # => "100755 -rwxr-xr-x"
3235 * File.chmod(0664, dirpath) # Change directory mode.
3236 * mode(dirpath) # => "040664 drw-rw-r--"
3237 * FileUtils.rm_rf(dirpath) # Clean up.
3238 *
3239 */
3240
3241static VALUE
3242rb_file_s_chmod(int argc, VALUE *argv, VALUE _)
3243{
3244 mode_t mode;
3245
3246 apply2args(1);
3247 mode = NUM2MODET(*argv++);
3248
3249 return apply2files(chmod_internal, argc, argv, &mode);
3250}
3251
3252#ifdef HAVE_FCHMOD
3253struct nogvl_fchmod_data {
3254 int fd;
3255 mode_t mode;
3256};
3257
3258static VALUE
3259io_blocking_fchmod(void *ptr)
3260{
3261 struct nogvl_fchmod_data *data = ptr;
3262 int ret = fchmod(data->fd, data->mode);
3263 return (VALUE)ret;
3264}
3265
3266static int
3267rb_fchmod(struct rb_io* io, mode_t mode)
3268{
3269 (void)rb_chmod; /* suppress unused-function warning when HAVE_FCHMOD */
3270 struct nogvl_fchmod_data data = {.fd = io->fd, .mode = mode};
3271 return (int)rb_thread_io_blocking_region(io, io_blocking_fchmod, &data);
3272}
3273#endif
3274
3275/*
3276 * call-seq:
3277 * chmod(mode) -> 0
3278 *
3279 * Changes the mode of +self+; returns '0'.
3280 * See {Filesystem Modes}[rdoc-ref:file/filesystem_modes.md]
3281 * and especially {Setting a Mode}[rdoc-ref:file/filesystem_modes.md@Setting+a+Mode].
3282 *
3283 * These examples use
3284 * a {helper method}[rdoc-ref:file/filesystem_modes.md@Helper+Method], +mode+,
3285 * that displays a mode both in octal digits and in characters:
3286 *
3287 * filepath = 'doc/t.tmp'
3288 * File.write(filepath, 'foo')
3289 * file = File.new(filepath)
3290 * mode(filepath) # => "100664 -rw-rw-r--"
3291 * file.chmod(0775)
3292 * mode(filepath) # => "100775 -rwxrwxr-x"
3293 * file.close
3294 * File.delete(filepath)
3295 *
3296 */
3297
3298static VALUE
3299rb_file_chmod(VALUE obj, VALUE vmode)
3300{
3301 rb_io_t *fptr;
3302 mode_t mode;
3303#if !defined HAVE_FCHMOD || !HAVE_FCHMOD
3304 VALUE path;
3305#endif
3306
3307 mode = NUM2MODET(vmode);
3308
3309 GetOpenFile(obj, fptr);
3310#ifdef HAVE_FCHMOD
3311 if (rb_fchmod(fptr, mode) == -1) {
3312 if (HAVE_FCHMOD || errno != ENOSYS)
3313 rb_sys_fail_path(fptr->pathv);
3314 }
3315 else {
3316 if (!HAVE_FCHMOD) return INT2FIX(0);
3317 }
3318#endif
3319#if !defined HAVE_FCHMOD || !HAVE_FCHMOD
3320 if (NIL_P(fptr->pathv)) return Qnil;
3321 path = rb_str_encode_ospath(fptr->pathv);
3322 if (rb_chmod(RSTRING_PTR(path), mode) == -1)
3323 rb_sys_fail_path(fptr->pathv);
3324#endif
3325
3326 return INT2FIX(0);
3327}
3328
3329#if defined(HAVE_LCHMOD)
3330static int
3331lchmod_internal(const char *path, void *mode)
3332{
3333 return lchmod(path, *(mode_t *)mode);
3334}
3335
3336/*
3337 * :markup: markdown
3338 *
3339 * call-seq:
3340 * File.lchmod(mode, *paths) -> paths_count
3341 *
3342 * Not supported on Linux or Windows (raises NotImplementedError).
3343 *
3344 * When supported: like File::chmod,
3345 * but does not follow [symbolic links](rdoc-ref:file/symbolic_links.md),
3346 * and therefore changes the mode of the entries given by `paths`;
3347 * returns the number of paths given:
3348 *
3349 * ```ruby
3350 * File.write('t.tmp', '')
3351 * File.symlink('t.tmp', 'link')
3352 * File.lstat('t.tmp').mode.to_s(8) # => "100664"
3353 * File.lstat('link').mode.to_s(8) # => "120755"
3354 * File.lchmod(0777, 'link')
3355 * File.lstat('t.tmp').mode.to_s(8) # => "100664"
3356 * File.lstat('link').mode.to_s(8) # => "120777"
3357 * File.delete('t.tmp')
3358 * File.delete('link')
3359 * ```
3360 */
3361
3362static VALUE
3363rb_file_s_lchmod(int argc, VALUE *argv, VALUE _)
3364{
3365 mode_t mode;
3366
3367 apply2args(1);
3368 mode = NUM2MODET(*argv++);
3369
3370 return apply2files(lchmod_internal, argc, argv, &mode);
3371}
3372#else
3373#define rb_file_s_lchmod rb_f_notimplement
3374#endif
3375
3376static inline rb_uid_t
3377to_uid(VALUE u)
3378{
3379 if (NIL_P(u)) {
3380 return (rb_uid_t)-1;
3381 }
3382 return NUM2UIDT(u);
3383}
3384
3385static inline rb_gid_t
3386to_gid(VALUE g)
3387{
3388 if (NIL_P(g)) {
3389 return (rb_gid_t)-1;
3390 }
3391 return NUM2GIDT(g);
3392}
3393
3395 rb_uid_t owner;
3396 rb_gid_t group;
3397};
3398
3399static int
3400chown_internal(const char *path, void *arg)
3401{
3402 struct chown_args *args = arg;
3403 return chown(path, args->owner, args->group);
3404}
3405
3406/*
3407 * call-seq:
3408 * File.chown(owner_int, group_int, *paths) -> integer
3409 *
3410 * Changes the owner and group of the entry at each of the given +paths+;
3411 * returns the count of the given +paths+:
3412 *
3413 * # Super user; all privileges.
3414 * Process.uid => 0
3415 * Process.gid => 0
3416 * # Create a directory and a file.
3417 * dirpath = 'doc/foo'
3418 * Dir.mkdir(dirpath)
3419 * filepath = 't.tmp'
3420 * File.write(filepath, 'foo')
3421 * # Get their user and group ids.
3422 * dirstat = File::Stat.new(dirpath)
3423 * dirstat.uid => 0
3424 * dirstat.gid => 0
3425 * filestat = File::Stat.new(filepath)
3426 * filestat.uid => 0
3427 * filestat.gid => 0
3428 * # Change ownership of both.
3429 * File.chown(1000, 1000, filepath, dirpath) => 2
3430 * dirstat = File::Stat.new(dirpath)
3431 * dirstat.uid => 1000
3432 * dirstat.gid => 1000
3433 * filestat = File::Stat.new(filepath)
3434 * filestat.uid => 1000
3435 * filestat.gid => 1000
3436 * # Clean up.
3437 * Dir.rmdir(dirpath)
3438 * File.delete(filepath)
3439 *
3440 * Notes:
3441 *
3442 * - On Windows, the owner and group are not changed.
3443 * - Only a process with superuser privileges can change the owner of an entry.
3444 * - The owner of an entry can change its group to any group
3445 * to which the owner belongs.
3446 * - A +nil+ or +-1+ owner or group id is ignored.
3447 * - The method follows symbolic links to the target entry.
3448 *
3449 */
3450
3451static VALUE
3452rb_file_s_chown(int argc, VALUE *argv, VALUE _)
3453{
3454 struct chown_args arg;
3455
3456 apply2args(2);
3457 arg.owner = to_uid(*argv++);
3458 arg.group = to_gid(*argv++);
3459
3460 return apply2files(chown_internal, argc, argv, &arg);
3461}
3462
3464 union {
3465 const char *path;
3466 int fd;
3467 } as;
3468 struct chown_args new;
3469};
3470
3471static void *
3472nogvl_chown(void *ptr)
3473{
3474 struct nogvl_chown_data *data = ptr;
3475 return (void *)(VALUE)chown(data->as.path, data->new.owner, data->new.group);
3476}
3477
3478static int
3479rb_chown(const char *path, rb_uid_t owner, rb_gid_t group)
3480{
3481 struct nogvl_chown_data data = {
3482 .as = {.path = path},
3483 .new = {.owner = owner, .group = group},
3484 };
3485 return IO_WITHOUT_GVL_INT(nogvl_chown, &data);
3486}
3487
3488#ifdef HAVE_FCHOWN
3489static void *
3490nogvl_fchown(void *ptr)
3491{
3492 struct nogvl_chown_data *data = ptr;
3493 return (void *)(VALUE)fchown(data->as.fd, data->new.owner, data->new.group);
3494}
3495
3496static int
3497rb_fchown(int fd, rb_uid_t owner, rb_gid_t group)
3498{
3499 (void)rb_chown; /* suppress unused-function warning when HAVE_FCHMOD */
3500 struct nogvl_chown_data data = {
3501 .as = {.fd = fd},
3502 .new = {.owner = owner, .group = group},
3503 };
3504 return IO_WITHOUT_GVL_INT(nogvl_fchown, &data);
3505}
3506#endif
3507
3508/*
3509 * call-seq:
3510 * file.chown(owner_int, group_int ) -> 0
3511 *
3512 * Changes the owner and group of <i>file</i> to the given numeric
3513 * owner and group id's. Only a process with superuser privileges may
3514 * change the owner of a file. The current owner of a file may change
3515 * the file's group to any group to which the owner belongs. A +nil+
3516 * or -1 owner or group id is ignored. Follows symbolic links. See
3517 * also File#lchown.
3518 *
3519 * File.new("testfile").chown(502, 1000)
3520 *
3521 */
3522
3523static VALUE
3524rb_file_chown(VALUE obj, VALUE owner, VALUE group)
3525{
3526 rb_io_t *fptr;
3527 rb_uid_t o;
3528 rb_gid_t g;
3529#ifndef HAVE_FCHOWN
3530 VALUE path;
3531#endif
3532
3533 o = to_uid(owner);
3534 g = to_gid(group);
3535 GetOpenFile(obj, fptr);
3536#ifndef HAVE_FCHOWN
3537 if (NIL_P(fptr->pathv)) return Qnil;
3538 path = rb_str_encode_ospath(fptr->pathv);
3539 if (rb_chown(RSTRING_PTR(path), o, g) == -1)
3540 rb_sys_fail_path(fptr->pathv);
3541#else
3542 if (rb_fchown(fptr->fd, o, g) == -1)
3543 rb_sys_fail_path(fptr->pathv);
3544#endif
3545
3546 return INT2FIX(0);
3547}
3548
3549#if defined(HAVE_LCHOWN)
3550static int
3551lchown_internal(const char *path, void *arg)
3552{
3553 struct chown_args *args = arg;
3554 return lchown(path, args->owner, args->group);
3555}
3556
3557/*
3558 * :markup: markdown
3559 *
3560 * call-seq:
3561 * File.lchown(uid, gid, *paths ) -> paths_count
3562 *
3563 * Not supported on some platforms (raises exception).
3564 *
3565 * Calling process must have superuser privileges.
3566 *
3567 * When supported: like File::chown,
3568 * but does not follow [symbolic links](rdoc-ref:file/symbolic_links.md),
3569 * and therefore changes the ownership of the entries given by `paths`;
3570 * returns the number of paths given:
3571 *
3572 * ```ruby
3573 * # Super user; all privileges.
3574 * Process.uid # => 0
3575 * Process.gid # => 0
3576 * # Create regular file and symbolic link to it.
3577 * File.write('t.tmp', '')
3578 * File.symlink('t.tmp', 'link')
3579 * Capture original statuses.
3580 * fstat0 = File.stat('t.tmp') # Method ::stat; status of file.
3581 * lstat0 = File.lstat('link') # Method ::lstat; status of link.
3582 * # Original user ids and group ids.
3583 * fstat0.uid => 0
3584 * fstat0.gid => 0
3585 * lstat0.uid => 0
3586 * lstat0.gid => 0
3587 * # Change ids for link.
3588 * File.lchown(1000, 1000, 'link') # => 1
3589 * # Capture new statuses.
3590 * fstat1 = File.stat('t.tmp')
3591 * lstat1 = File.stat('link')
3592 * # User id and group id for file not changed..
3593 * fstat1.uid # => 0
3594 * fstat1.gid # => 0
3595 * # User is and group id for link changed.
3596 * lstat1.uid # => 1000
3597 * lstat1.gid # => 1000
3598 * Clean up.
3599 * File.delete('t.tmp')
3600 * File.delete('link')
3601 * ```
3602 *
3603 */
3604
3605static VALUE
3606rb_file_s_lchown(int argc, VALUE *argv, VALUE _)
3607{
3608 struct chown_args arg;
3609
3610 apply2args(2);
3611 arg.owner = to_uid(*argv++);
3612 arg.group = to_gid(*argv++);
3613
3614 return apply2files(lchown_internal, argc, argv, &arg);
3615}
3616#else
3617#define rb_file_s_lchown rb_f_notimplement
3618#endif
3619
3621 const struct timespec* tsp;
3622 VALUE atime, mtime;
3623 int follow; /* Whether to act on symlinks (1) or their referent (0) */
3624};
3625
3626#ifdef UTIME_EINVAL
3627NORETURN(static void utime_failed(struct apply_arg *));
3628
3629static void
3630utime_failed(struct apply_arg *aa)
3631{
3632 int e = aa->errnum;
3633 VALUE path = aa->fn[aa->i].path;
3634 struct utime_args *ua = aa->arg;
3635
3636 if (ua->tsp && e == EINVAL) {
3637 VALUE e[2], a = Qnil, m = Qnil;
3638 int d = 0;
3639 VALUE atime = ua->atime;
3640 VALUE mtime = ua->mtime;
3641
3642 if (!NIL_P(atime)) {
3643 a = rb_inspect(atime);
3644 }
3645 if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) {
3646 m = rb_inspect(mtime);
3647 }
3648 if (NIL_P(a)) e[0] = m;
3649 else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a;
3650 else {
3651 e[0] = rb_str_plus(a, rb_str_new_cstr(" or "));
3652 rb_str_append(e[0], m);
3653 d = 1;
3654 }
3655 if (!NIL_P(e[0])) {
3656 if (path) {
3657 if (!d) e[0] = rb_str_dup(e[0]);
3658 rb_str_append(rb_str_cat2(e[0], " for "), path);
3659 }
3660 e[1] = INT2FIX(EINVAL);
3662 }
3663 }
3664 rb_syserr_fail_path(e, path);
3665}
3666#endif /* UTIME_EINVAL */
3667
3668#if defined(HAVE_UTIMES)
3669
3670# if !defined(HAVE_UTIMENSAT)
3671/* utimensat() is not found, runtime check is not needed */
3672# elif defined(__APPLE__) && \
3673 (!defined(MAC_OS_X_VERSION_13_0) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_13_0))
3674
3675# if __has_attribute(availability) && __has_warning("-Wunguarded-availability-new")
3676typedef int utimensat_func(int, const char *, const struct timespec [2], int);
3677
3679RBIMPL_WARNING_IGNORED(-Wunguarded-availability-new)
3680static inline utimensat_func *
3681rb_utimensat(void)
3682{
3683 return &utimensat;
3684}
3686
3687# define utimensat rb_utimensat()
3688# else /* __API_AVAILABLE macro does nothing on gcc */
3689__attribute__((weak)) int utimensat(int, const char *, const struct timespec [2], int);
3690# endif /* utimesat availability */
3691# endif /* __APPLE__ && < MAC_OS_X_VERSION_13_0 */
3692
3693static int
3694utime_internal(const char *path, void *arg)
3695{
3696 struct utime_args *v = arg;
3697 const struct timespec *tsp = v->tsp;
3698 struct timeval tvbuf[2], *tvp = NULL;
3699
3700#if defined(HAVE_UTIMENSAT)
3701# if defined(__APPLE__)
3702 const int try_utimensat = utimensat != NULL;
3703 const int try_utimensat_follow = utimensat != NULL;
3704# else /* !__APPLE__ */
3705# define TRY_UTIMENSAT 1
3706 static int try_utimensat = 1;
3707# ifdef AT_SYMLINK_NOFOLLOW
3708 static int try_utimensat_follow = 1;
3709# else
3710 const int try_utimensat_follow = 0;
3711# endif
3712# endif /* __APPLE__ */
3713 int flags = 0;
3714
3715 if (v->follow ? try_utimensat_follow : try_utimensat) {
3716# ifdef AT_SYMLINK_NOFOLLOW
3717 if (v->follow) {
3718 flags = AT_SYMLINK_NOFOLLOW;
3719 }
3720# endif
3721
3722 int result = utimensat(AT_FDCWD, path, tsp, flags);
3723# ifdef TRY_UTIMENSAT
3724 if (result < 0 && errno == ENOSYS) {
3725# ifdef AT_SYMLINK_NOFOLLOW
3726 try_utimensat_follow = 0;
3727# endif /* AT_SYMLINK_NOFOLLOW */
3728 if (!v->follow)
3729 try_utimensat = 0;
3730 }
3731 else
3732# endif /* TRY_UTIMESAT */
3733 return result;
3734 }
3735#endif /* defined(HAVE_UTIMENSAT) */
3736
3737 if (tsp) {
3738 tvbuf[0].tv_sec = tsp[0].tv_sec;
3739 tvbuf[0].tv_usec = (int)(tsp[0].tv_nsec / 1000);
3740 tvbuf[1].tv_sec = tsp[1].tv_sec;
3741 tvbuf[1].tv_usec = (int)(tsp[1].tv_nsec / 1000);
3742 tvp = tvbuf;
3743 }
3744#ifdef HAVE_LUTIMES
3745 if (v->follow) return lutimes(path, tvp);
3746#endif
3747 return utimes(path, tvp);
3748}
3749
3750#else /* !defined(HAVE_UTIMES) */
3751
3752#if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
3753struct utimbuf {
3754 long actime;
3755 long modtime;
3756};
3757#endif
3758
3759static int
3760utime_internal(const char *path, void *arg)
3761{
3762 struct utime_args *v = arg;
3763 const stat_timestamp *tsp = v->tsp;
3764 struct utimbuf utbuf, *utp = NULL;
3765 if (tsp) {
3766 utbuf.actime = tsp[0].tv_sec;
3767 utbuf.modtime = tsp[1].tv_sec;
3768 utp = &utbuf;
3769 }
3770 return utime(path, utp);
3771}
3772#endif /* !defined(HAVE_UTIMES) */
3773
3774static VALUE
3775utime_internal_i(int argc, VALUE *argv, int follow)
3776{
3777 struct utime_args args;
3778 struct timespec tss[2], *tsp = NULL;
3779
3780 apply2args(2);
3781 args.atime = *argv++;
3782 args.mtime = *argv++;
3783
3784 args.follow = follow;
3785
3786 if (!NIL_P(args.atime) || !NIL_P(args.mtime)) {
3787 tsp = tss;
3788 tsp[0] = rb_time_timespec(args.atime);
3789 if (args.atime == args.mtime)
3790 tsp[1] = tsp[0];
3791 else
3792 tsp[1] = rb_time_timespec(args.mtime);
3793 }
3794 args.tsp = tsp;
3795
3796 return apply2files(utime_internal, argc, argv, &args);
3797}
3798
3799/*
3800 * call-seq:
3801 * File.utime(atime, mtime, file_name, ...) -> integer
3802 *
3803 * Sets the access and modification times of each named file to the
3804 * first two arguments. If a file is a symlink, this method acts upon
3805 * its referent rather than the link itself; for the inverse
3806 * behavior see File.lutime. Returns the number of file
3807 * names in the argument list.
3808 */
3809
3810static VALUE
3811rb_file_s_utime(int argc, VALUE *argv, VALUE _)
3812{
3813 return utime_internal_i(argc, argv, FALSE);
3814}
3815
3816#if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
3817
3818/*
3819 * :markup: markdown
3820 *
3821 * call-seq:
3822 * File.lutime(atime, mtime, *paths) -> path_count
3823 *
3824 * Like File::utime,
3825 * but does not follow [symbolic links](rdoc-ref:file/symbolic_links.md),
3826 * and therefore changes the times of the entries given by `paths`,
3827 * regardless of whether they are symbolic links;
3828 * returns the number of `paths` given:
3829 *
3830 * ```ruby
3831 * # Create a file and a link to it.
3832 * file_path = 't.tmp'
3833 * File.write(file_path, '')
3834 * link_path = 'link'
3835 * File.symlink(file_path, link_path)
3836 * # Take snapshots of both.
3837 * file_stat = File.stat(file_path)
3838 * link_stat = File.lstat(link_path)
3839 * # Fetch access times and modification times of both.
3840 * file_stat.atime # => 2026-06-15 10:45:11.376753268 -0500
3841 * file_stat.mtime # => 2026-06-15 10:44:47.335854904 -0500
3842 * link_stat.atime # => 2026-06-15 10:44:59.788801128 -0500
3843 * link_stat.mtime # => 2026-06-15 10:44:49.367845961 -0500
3844 * # Update access time and modification time of the link.
3845 * time = Time.now # => 2026-06-15 10:48:57.847422496 -0500
3846 * File.lutime(time, time, link_path)
3847 * # Take fresh snapshots of both.
3848 * file_stat = File.stat(file_path)
3849 * link_stat = File.lstat(link_path)
3850 * # Fetch access time and modification time of file (not changed).
3851 * file_stat.atime # => 2026-06-15 10:45:11.376753268 -0500
3852 * file_stat.mtime # => 2026-06-15 10:44:47.335854904 -0500
3853 * # Fetch access time and modification time of link (changed).
3854 * link_stat.atime # => 2026-06-15 10:49:27.119146136 -0500
3855 * link_stat.mtime # => 2026-06-15 10:48:57.847422496 -0500
3856 * # Clean up.
3857 * File.delete(file_path)
3858 * File.delete(link_path)
3859 * ```
3860 *
3861 * Arguments `atime` and `mtime` may be Time objects (as above).
3862 *
3863 * Either or both may be integers;
3864 * when an integer `i` is passed, `Time.new(i)` is used.
3865 *
3866 * Either or both may be `nil`, in which case `Time.now` is used.
3867 *
3868 * See {File System Timestamps}[rdoc-ref:file/timestamps.md].
3869 */
3870
3871static VALUE
3872rb_file_s_lutime(int argc, VALUE *argv, VALUE _)
3873{
3874 return utime_internal_i(argc, argv, TRUE);
3875}
3876#else
3877#define rb_file_s_lutime rb_f_notimplement
3878#endif
3879
3880#ifdef RUBY_FUNCTION_NAME_STRING
3881# define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
3882#else
3883# define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
3884#endif
3885#define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
3886NORETURN(static void syserr_fail2_in(const char *,int,VALUE,VALUE));
3887static void
3888syserr_fail2_in(const char *func, int e, VALUE s1, VALUE s2)
3889{
3890 VALUE str;
3891#ifdef MAX_PATH
3892 const int max_pathlen = MAX_PATH;
3893#else
3894 const int max_pathlen = MAXPATHLEN;
3895#endif
3896
3897 if (e == EEXIST) {
3898 rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen));
3899 }
3900 str = rb_str_new_cstr("(");
3901 rb_str_append(str, rb_str_ellipsize(s1, max_pathlen));
3902 rb_str_cat2(str, ", ");
3903 rb_str_append(str, rb_str_ellipsize(s2, max_pathlen));
3904 rb_str_cat2(str, ")");
3905#ifdef RUBY_FUNCTION_NAME_STRING
3906 rb_syserr_fail_path_in(func, e, str);
3907#else
3908 rb_syserr_fail_path(e, str);
3909#endif
3910}
3911
3912#ifdef HAVE_LINK
3913/*
3914 * :markup: markdown
3915
3916 * call-seq:
3917 * File.link(path, new_path) -> 0
3918 *
3919 * Not available on some systems.
3920 *
3921 * Creates a new entry at `new_path` for the existing entry at `path`
3922 * using a [hard link](https://en.wikipedia.org/wiki/Hard_link):
3923 *
3924 * ```ruby
3925 * File.write('doc/t.tmp', 'foo')
3926 * File.link('doc/t.tmp', 'lib/u.tmp')
3927 * File.read('lib/u.tmp') # => "foo"
3928 * File.write('lib/u.tmp', 'bar')
3929 * File.read('doc/t.tmp') # => "bar"
3930 * File.delete('doc/t.tmp')
3931 * File.read('lib/u.tmp') # => "bar"
3932 * File.delete('lib/u.tmp')
3933 * ```
3934 *
3935 * Raises an exception if the entry at `new_path` exists.
3936 */
3937
3938static VALUE
3939rb_file_s_link(VALUE klass, VALUE from, VALUE to)
3940{
3941 FilePathValue(from);
3942 FilePathValue(to);
3943 from = rb_str_encode_ospath(from);
3944 to = rb_str_encode_ospath(to);
3945
3946 if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
3947 sys_fail2(from, to);
3948 }
3949 return INT2FIX(0);
3950}
3951#else
3952#define rb_file_s_link rb_f_notimplement
3953#endif
3954
3955#ifdef HAVE_SYMLINK
3956/*
3957 * :markup: markdown
3958 *
3959 * call-seq:
3960 * File.symlink(target_path, link_path) -> 0
3961 *
3962 * Not supported on some platforms.
3963 *
3964 * Creates a [symbolic link](rdoc-ref:file/symbolic_links.md)
3965 * at `link_path` to the entry at `target_path`:
3966 *
3967 * ```ruby
3968 * filepath = '/etc/passwd' # Regular file.
3969 * linkpath = '/tmp/foo'
3970 * File.symlink(filepath, linkpath)
3971 * File.readlink(linkpath) # => "/etc/passwd"
3972 * File.read(filepath) == File.read(linkpath) # => true
3973 * ```
3974 *
3975 * If the entry at `target_path` is itself a symbolic link,
3976 * that link is _not_ followed:
3977 *
3978 * ```ruby
3979 * link2path = '/tmp/bar'
3980 * File.symlink(linkpath, link2path)
3981 * File.readlink(link2path) # => "/tmp/foo"
3982 * File.read(filepath) == File.read(link2path) # => true
3983 * File.delete(linkpath, link2path) # Clean up.
3984 * ```
3985 *
3986 */
3987
3988static VALUE
3989rb_file_s_symlink(VALUE klass, VALUE from, VALUE to)
3990{
3991 FilePathValue(from);
3992 FilePathValue(to);
3993 from = rb_str_encode_ospath(from);
3994 to = rb_str_encode_ospath(to);
3995
3996 if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
3997 sys_fail2(from, to);
3998 }
3999 return INT2FIX(0);
4000}
4001#else
4002#define rb_file_s_symlink rb_f_notimplement
4003#endif
4004
4005#ifdef HAVE_READLINK
4006/*
4007 * :markup: markdown
4008 *
4009 * call-seq:
4010 * File.readlink(link_path) -> string
4011 *
4012 * Returns the string path to the entry referenced
4013 * by the [symbolic link](rdoc-ref:file/symbolic_links.md) at `link_path`:
4014 *
4015 * ```ruby
4016 * filepath = 'doc/maintainers.md'
4017 * linkpath = '/tmp/link'
4018 * File.symlink(filepath, linkpath)
4019 * File.readlink(linkpath) # => "doc/maintainers.md"
4020 * File.delete(linkpath) # Clean up.
4021 * ```
4022 *
4023 * Raises Errno::EINVAL if the entry referenced by `link_path`
4024 * is not a symbolic link.
4025 */
4026
4027static VALUE
4028rb_file_s_readlink(VALUE klass, VALUE path)
4029{
4030 return rb_readlink(path, rb_filesystem_encoding());
4031}
4032
4033struct readlink_arg {
4034 const char *path;
4035 char *buf;
4036 size_t size;
4037};
4038
4039static void *
4040nogvl_readlink(void *ptr)
4041{
4042 struct readlink_arg *ra = ptr;
4043
4044 return (void *)(VALUE)readlink(ra->path, ra->buf, ra->size);
4045}
4046
4047static ssize_t
4048readlink_without_gvl(VALUE path, VALUE buf, size_t size)
4049{
4050 struct readlink_arg ra;
4051
4052 ra.path = RSTRING_PTR(path);
4053 ra.buf = RSTRING_PTR(buf);
4054 ra.size = size;
4055
4056 return (ssize_t)IO_WITHOUT_GVL(nogvl_readlink, &ra);
4057}
4058
4059VALUE
4060rb_readlink(VALUE path, rb_encoding *enc)
4061{
4062 int size = 100;
4063 ssize_t rv;
4064 VALUE v;
4065
4066 FilePathValue(path);
4067 path = rb_str_encode_ospath(path);
4068 v = rb_enc_str_new(0, size, enc);
4069 while ((rv = readlink_without_gvl(path, v, size)) == size
4070#ifdef _AIX
4071 || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
4072#endif
4073 ) {
4074 rb_str_modify_expand(v, size);
4075 size *= 2;
4076 rb_str_set_len(v, size);
4077 }
4078 if (rv < 0) {
4079 int e = errno;
4080 rb_str_resize(v, 0);
4081 rb_syserr_fail_path(e, path);
4082 }
4083 rb_str_resize(v, rv);
4084
4085 return v;
4086}
4087#else
4088#define rb_file_s_readlink rb_f_notimplement
4089#endif
4090
4091static int
4092unlink_internal(const char *path, void *arg)
4093{
4094 return unlink(path);
4095}
4096
4097/*
4098 * :markup: markdown
4099 *
4100 * call-seq:
4101 * File.delete(*paths) -> integer
4102 * File.unlink(*paths) -> integer
4103 *
4104 * Removes the entry at each path in `paths`;
4105 * returns the count of removed entries.
4106 *
4107 * Does not follow [symbolic links](rdoc-ref:file/symbolic_links.md);
4108 * if an entry is a symlink, the link itself is removed.
4109 *
4110 * ```ruby
4111 * File.write('t.tmp', 'foo')
4112 * File.write('u.tmp', 'bar')
4113 * File.delete('t.tmp', 'u.tmp') # => 2
4114 * File.symlink('README.md', 'foo')
4115 * File.unlink('foo') # => 1
4116 * ```
4117 *
4118 * Raises an exception on any error;
4119 * some entries may have been deleted before the path causing the error.
4120 */
4121
4122static VALUE
4123rb_file_s_unlink(int argc, VALUE *argv, VALUE klass)
4124{
4125 return apply2files(unlink_internal, argc, argv, 0);
4126}
4127
4129 const char *src;
4130 const char *dst;
4131};
4132
4133static void *
4134no_gvl_rename(void *ptr)
4135{
4136 struct rename_args *ra = ptr;
4137
4138 return (void *)(VALUE)rename(ra->src, ra->dst);
4139}
4140
4141/*
4142 * :markup: markdown
4143 *
4144 * call-seq:
4145 * File.rename(path, new_path) -> 0
4146 *
4147 * Moves the entry at the given `path` to the given `new_path`.
4148 *
4149 * Does not follow [symbolic links](rdoc-ref:file/symbolic_links.md);
4150 * if the entry is a symlink, the link itself is renamed.
4151 *
4152 * The examples below use two temporary directories:
4153 *
4154 * ```ruby
4155 * src_dirpath = '/tmp/src/' # => "/tmp/src/"
4156 * dst_dirpath = '/tmp/dst/' # => "/tmp/dst/"
4157 * Dir.mkdir(src_dirpath)
4158 * Dir.mkdir(dst_dirpath)
4159 * ```
4160 *
4161 * The entry to be renamed may be a file:
4162 *
4163 * ```ruby
4164 * src_filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
4165 * File.write(src_filepath, 'foo')
4166 * dst_filepath = File.join(dst_dirpath, 'u.tmp') # => "/tmp/dst/u.tmp"
4167 * File.rename(src_filepath, dst_filepath)
4168 * File.exist?(src_filepath) # => false
4169 * File.exist?(dst_filepath) # => true
4170 * File.delete(dst_filepath) # Clean up.
4171 * ```
4172 *
4173 * The entry to be renamed may be a symbolic link:
4174 *
4175 * ```ruby
4176 * filepath = File.join(src_dirpath, 't.tmp') # => "/tmp/src/t.tmp"
4177 * File.write(src_filepath, 'foo')
4178 * linkpath = File.join(src_dirpath, 'u.tmp') # => "/tmp/src/u.tmp"
4179 * File.symlink(filepath, linkpath)
4180 * File.readlink(linkpath) # => "/tmp/src/t.tmp"
4181 * newpath = File.join(dst_dirpath, 'v.tmp') # => "/tmp/dst/v.tmp"
4182 * File.rename(linkpath, newpath) # Symlink not followed.
4183 * File.readlink(newpath) # => "/tmp/src/t.tmp"
4184 * File.delete(filepath, newpath) # Clean up.
4185 * ```
4186 *
4187 * The entry to be renamed may be a directory:
4188 *
4189 * ```ruby
4190 * old_dirpath = File.join(src_dirpath, 'olddir') # => "/tmp/src/olddir"
4191 * Dir.mkdir(old_dirpath)
4192 * new_dirpath = File.join(dst_dirpath, 'newdir') # => "/tmp/dst/newdir"
4193 * File.rename(old_dirpath, new_dirpath)
4194 * File.directory?(new_dirpath) # => true
4195 * Dir.rmdir(new_dirpath) # Clean up.
4196 * ```
4197 *
4198 * Clean up:
4199 *
4200 * ```ruby
4201 * FileUtils.rm_rf(src_dirpath) # => ["/tmp/src/"]
4202 * FileUtils.rm_rf(dst_dirpath) # => ["/tmp/dst/"]
4203 * ```
4204 *
4205 * Raises SystemCallError if the file cannot be renamed.
4206 */
4207
4208static VALUE
4209rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
4210{
4211 struct rename_args ra;
4212 VALUE f, t;
4213
4214 FilePathValue(from);
4215 FilePathValue(to);
4216 f = rb_str_encode_ospath(from);
4217 t = rb_str_encode_ospath(to);
4218 ra.src = StringValueCStr(f);
4219 ra.dst = StringValueCStr(t);
4220#if defined __CYGWIN__
4221 errno = 0;
4222#endif
4223 if (IO_WITHOUT_GVL_INT(no_gvl_rename, &ra) < 0) {
4224 int e = errno;
4225#if defined DOSISH
4226 switch (e) {
4227 case EEXIST:
4228 if (chmod(ra.dst, 0666) == 0 &&
4229 unlink(ra.dst) == 0 &&
4230 rename(ra.src, ra.dst) == 0)
4231 return INT2FIX(0);
4232 }
4233#endif
4234 syserr_fail2(e, from, to);
4235 }
4236
4237 return INT2FIX(0);
4238}
4239
4240/*
4241 * call-seq:
4242 * File.umask() -> integer
4243 * File.umask(integer) -> integer
4244 *
4245 * Returns the current umask value for this process. If the optional argument
4246 * is given, set the umask to that value and return the previous value. Umask
4247 * values are <em>subtracted</em> from the default permissions, so a umask of
4248 * +0222+ would make a file read-only for everyone.
4249 *
4250 * File.umask(0006) #=> 18
4251 * File.umask #=> 6
4252 */
4253
4254static VALUE
4255rb_file_s_umask(int argc, VALUE *argv, VALUE _)
4256{
4257 mode_t omask = 0;
4258
4259 switch (argc) {
4260 case 0:
4261 omask = umask(0);
4262 umask(omask);
4263 break;
4264 case 1:
4265 omask = umask(NUM2MODET(argv[0]));
4266 break;
4267 default:
4268 rb_error_arity(argc, 0, 1);
4269 }
4270 return MODET2NUM(omask);
4271}
4272
4273#ifdef __CYGWIN__
4274#undef DOSISH
4275#endif
4276#if defined __CYGWIN__ || defined DOSISH
4277#define DOSISH_UNC
4278#define DOSISH_DRIVE_LETTER
4279#define FILE_ALT_SEPARATOR '\\'
4280#endif
4281#ifdef FILE_ALT_SEPARATOR
4282#define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
4283# ifdef DOSISH
4284static const char file_alt_separator[] = {FILE_ALT_SEPARATOR, '\0'};
4285# endif
4286#else
4287#define isdirsep(x) ((x) == '/')
4288#endif
4289
4290#ifndef USE_NTFS
4291# if defined _WIN32
4292# define USE_NTFS 1
4293# else
4294# define USE_NTFS 0
4295# endif
4296#endif
4297
4298#if USE_NTFS
4299#define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
4300#define isADS(x) ((x) == ':')
4301#else
4302#define istrailinggarbage(x) 0
4303#endif
4304
4305#define enc_mbclen_needed(enc) (!rb_str_encindex_fastpath(rb_enc_to_index(enc)))
4306
4307#define Next(p, e, mb_enc, enc) ((p) + ((mb_enc) ? rb_enc_mbclen((p), (e), (enc)) : 1))
4308#define Inc(p, e, mb_enc, enc) ((p) = Next((p), (e), (mb_enc), (enc)))
4309
4310#if defined(DOSISH_UNC)
4311#define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
4312#else
4313#define has_unc(buf) 0
4314#endif
4315
4316#ifdef DOSISH_DRIVE_LETTER
4317static inline int
4318has_drive_letter(const char *buf)
4319{
4320 if (ISALPHA(buf[0]) && buf[1] == ':') {
4321 return 1;
4322 }
4323 else {
4324 return 0;
4325 }
4326}
4327
4328#ifndef _WIN32
4329static VALUE
4330getcwdofdrv(int drv)
4331{
4332 char drive[4];
4333 char *oldcwd;
4334 VALUE drvcwd;
4335
4336 drive[0] = drv;
4337 drive[1] = ':';
4338 drive[2] = '\0';
4339
4340 /* the only way that I know to get the current directory
4341 of a particular drive is to change chdir() to that drive,
4342 so save the old cwd before chdir()
4343 */
4344 oldcwd = ruby_getcwd();
4345 if (chdir(drive) == 0) {
4346 drvcwd = rb_dir_getwd_ospath();
4347 chdir(oldcwd);
4348 xfree(oldcwd);
4349 }
4350 else {
4351 /* perhaps the drive is not exist. we return only drive letter */
4352 drvcwd = rb_enc_str_new_cstr(drive, rb_filesystem_encoding());
4353 }
4354 return drvcwd;
4355}
4356
4357static inline int
4358not_same_drive(VALUE path, int drive)
4359{
4360 const char *p = RSTRING_PTR(path);
4361 if (RSTRING_LEN(path) < 2) return 0;
4362 if (has_drive_letter(p)) {
4363 return TOLOWER(p[0]) != TOLOWER(drive);
4364 }
4365 else {
4366 return has_unc(p);
4367 }
4368}
4369#endif /* _WIN32 */
4370#endif /* DOSISH_DRIVE_LETTER */
4371
4372static inline char *
4373skiproot(const char *path, const char *end)
4374{
4375#ifdef DOSISH_DRIVE_LETTER
4376 if (path + 2 <= end && has_drive_letter(path)) path += 2;
4377#endif
4378 while (path < end && isdirsep(*path)) path++;
4379 return (char *)path;
4380}
4381
4382static inline char *
4383enc_path_next(const char *s, const char *e, bool mb_enc, rb_encoding *enc)
4384{
4385 while (s < e && !isdirsep(*s)) {
4386 Inc(s, e, mb_enc, enc);
4387 }
4388 return (char *)s;
4389}
4390
4391#define nextdirsep rb_enc_path_next
4392char *
4393rb_enc_path_next(const char *s, const char *e, rb_encoding *enc)
4394{
4395 return enc_path_next(s, e, enc_mbclen_needed(enc), enc);
4396}
4397
4398#if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4399#define skipprefix enc_path_skip_prefix
4400#else
4401#define skipprefix(path, end, mb_enc, enc) (path)
4402#endif
4403static inline char *
4404enc_path_skip_prefix(const char *path, const char *end, bool mb_enc, rb_encoding *enc)
4405{
4406#if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4407#ifdef DOSISH_UNC
4408 if (path + 2 <= end && isdirsep(path[0]) && isdirsep(path[1])) {
4409 path += 2;
4410 while (path < end && isdirsep(*path)) path++;
4411 if ((path = enc_path_next(path, end, mb_enc, enc)) < end &&
4412 path + 2 <= end && !isdirsep(path[1])) {
4413 path = enc_path_next(path + 1, end, mb_enc, enc);
4414 }
4415 return (char *)path;
4416 }
4417#endif
4418#ifdef DOSISH_DRIVE_LETTER
4419 if (path + 2 <= end && has_drive_letter(path))
4420 return (char *)(path + 2);
4421#endif
4422#endif /* defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER) */
4423 return (char *)path;
4424}
4425
4426char *
4427rb_enc_path_skip_prefix(const char *path, const char *end, rb_encoding *enc)
4428{
4429 return enc_path_skip_prefix(path, end, enc_mbclen_needed(enc), enc);
4430}
4431
4432static inline char *
4433skipprefixroot(const char *path, const char *end, rb_encoding *enc)
4434{
4435#if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4436 char *p = skipprefix(path, end, enc_mbclen_needed(enc), enc);
4437 while (p < end && isdirsep(*p)) p++;
4438 return p;
4439#else
4440 return skiproot(path, end);
4441#endif
4442}
4443
4444char *
4445rb_enc_path_skip_prefix_root(const char *path, const char *end, rb_encoding *enc)
4446{
4447 return skipprefixroot(path, end, enc);
4448}
4449
4450static char *
4451enc_path_last_separator(const char *path, const char *end, bool mb_enc, rb_encoding *enc)
4452{
4453 char *last = NULL;
4454 while (path < end) {
4455 if (isdirsep(*path)) {
4456 const char *tmp = path++;
4457 while (path < end && isdirsep(*path)) path++;
4458 if (path >= end) break;
4459 last = (char *)tmp;
4460 }
4461 else {
4462 Inc(path, end, mb_enc, enc);
4463 }
4464 }
4465 return last;
4466}
4467char *
4468rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
4469{
4470 return enc_path_last_separator(path, end, enc_mbclen_needed(enc), enc);
4471}
4472
4473static inline char *
4474strrdirsep(const char *path, const char *end, bool mb_enc, rb_encoding *enc)
4475{
4476 if (RB_UNLIKELY(mb_enc)) {
4477 return enc_path_last_separator(path, end, mb_enc, enc);
4478 }
4479
4480 const char *cursor = end - 1;
4481
4482 while (cursor >= path && isdirsep(cursor[0])) {
4483 cursor--;
4484 }
4485
4486 while (cursor >= path) {
4487 if (isdirsep(cursor[0])) {
4488 while (cursor > path && isdirsep(cursor[-1])) {
4489 cursor--;
4490 }
4491 return (char *)cursor;
4492 }
4493 cursor--;
4494 }
4495 return NULL;
4496}
4497
4498static char *
4499chompdirsep(const char *path, const char *end, bool mb_enc, rb_encoding *enc)
4500{
4501 while (path < end) {
4502 if (isdirsep(*path)) {
4503 const char *last = path++;
4504 while (path < end && isdirsep(*path)) path++;
4505 if (path >= end) return (char *)last;
4506 }
4507 else {
4508 Inc(path, end, mb_enc, enc);
4509 }
4510 }
4511 return (char *)path;
4512}
4513
4514char *
4515rb_enc_path_end(const char *path, const char *end, rb_encoding *enc)
4516{
4517 if (path < end && isdirsep(*path)) path++;
4518 return chompdirsep(path, end, enc_mbclen_needed(enc), enc);
4519}
4520
4521static rb_encoding *
4522fs_enc_check(VALUE path1, VALUE path2)
4523{
4524 rb_encoding *enc = rb_enc_check_str(path1, path2);
4525 int encidx = rb_enc_to_index(enc);
4526 if (encidx == ENCINDEX_US_ASCII) {
4527 encidx = rb_enc_get_index(path1);
4528 if (encidx == ENCINDEX_US_ASCII)
4529 encidx = rb_enc_get_index(path2);
4530 enc = rb_enc_from_index(encidx);
4531 }
4532 return enc;
4533}
4534
4535#if USE_NTFS
4536static char *
4537ntfs_tail(const char *path, const char *end, bool mb_enc, rb_encoding *enc)
4538{
4539 while (path < end && *path == '.') path++;
4540 while (path < end && !isADS(*path)) {
4541 if (istrailinggarbage(*path)) {
4542 const char *last = path++;
4543 while (path < end && istrailinggarbage(*path)) path++;
4544 if (path >= end || isADS(*path)) return (char *)last;
4545 }
4546 else if (isdirsep(*path)) {
4547 const char *last = path++;
4548 while (path < end && isdirsep(*path)) path++;
4549 if (path >= end) return (char *)last;
4550 if (isADS(*path)) path++;
4551 }
4552 else {
4553 Inc(path, end, mb_enc, enc);
4554 }
4555 }
4556 return (char *)path;
4557}
4558#endif /* USE_NTFS */
4559
4560#define BUFCHECK(cond) do {\
4561 bdiff = p - buf;\
4562 if (cond) {\
4563 do {buflen *= 2;} while (cond);\
4564 rb_str_resize(result, buflen);\
4565 buf = RSTRING_PTR(result);\
4566 p = buf + bdiff;\
4567 pend = buf + buflen;\
4568 }\
4569} while (0)
4570
4571#define BUFINIT(result, buf, p, pend) do {\
4572 if (!result) { result = rb_usascii_str_new(0, 1); } \
4573 p = buf = RSTRING_PTR(result); \
4574 buflen = RSTRING_LEN(result); \
4575 pend = p + buflen; \
4576} while (0)
4577
4578#ifdef __APPLE__
4579# define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
4580#else
4581# define SKIPPATHSEP(p) 1
4582#endif
4583
4584#define BUFCOPY(srcptr, srclen) do { \
4585 const int skip = SKIPPATHSEP(p); \
4586 rb_str_set_len(result, p-buf+skip); \
4587 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
4588 p += skip; \
4589 memcpy(p, (srcptr), (srclen)); \
4590 p += (srclen); \
4591} while (0)
4592
4593#define WITH_ROOTDIFF(stmt) do { \
4594 long rootdiff = root - buf; \
4595 stmt; \
4596 root = buf + rootdiff; \
4597} while (0)
4598
4599static VALUE
4600copy_home_path(VALUE result, const char *dir)
4601{
4602 char *buf;
4603 long dirlen;
4604 int encidx;
4605
4606 dirlen = strlen(dir);
4607 rb_str_resize(result, dirlen);
4608 memcpy(buf = RSTRING_PTR(result), dir, dirlen);
4609 encidx = rb_filesystem_encindex();
4610 rb_enc_associate_index(result, encidx);
4611#if defined FILE_ALT_SEPARATOR
4612 rb_encoding *enc = rb_enc_from_index(encidx);
4613 bool mb_enc = enc_mbclen_needed(enc);
4614 for (char *p = buf, *bend = p + dirlen; p < bend; Inc(p, bend, mb_enc, enc)) {
4615 if (*p == FILE_ALT_SEPARATOR) {
4616 *p = '/';
4617 }
4618 }
4619#endif
4620 return result;
4621}
4622
4623VALUE
4624rb_home_dir_of(VALUE user, VALUE result)
4625{
4626#ifdef HAVE_PWD_H
4627 VALUE dirname = rb_getpwdirnam_for_login(user);
4628 if (dirname == Qnil) {
4629 rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user);
4630 }
4631 const char *dir = RSTRING_PTR(dirname);
4632#else
4633 extern char *getlogin(void);
4634 const char *pwPtr = 0;
4635 const char *login;
4636 # define endpwent() ((void)0)
4637 const char *dir, *username = RSTRING_PTR(user);
4638 rb_encoding *enc = rb_enc_get(user);
4639#if defined _WIN32
4640 rb_encoding *fsenc = rb_utf8_encoding();
4641#else
4642 rb_encoding *fsenc = rb_filesystem_encoding();
4643#endif
4644 if (enc != fsenc) {
4645 dir = username = RSTRING_PTR(rb_str_conv_enc(user, enc, fsenc));
4646 }
4647
4648 if ((login = getlogin()) && strcasecmp(username, login) == 0)
4649 dir = pwPtr = getenv("HOME");
4650 if (!pwPtr) {
4651 rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user);
4652 }
4653#endif
4654 copy_home_path(result, dir);
4655 return result;
4656}
4657
4658#ifndef _WIN32 /* this encompasses rb_file_expand_path_internal */
4659VALUE
4660rb_default_home_dir(VALUE result)
4661{
4662 const char *dir = getenv("HOME");
4663
4664#if defined HAVE_PWD_H
4665 if (!dir) {
4666 /* We'll look up the user's default home dir in the password db by
4667 * login name, if possible, and failing that will fall back to looking
4668 * the information up by uid (as would be needed for processes that
4669 * are not a descendant of login(1) or a work-alike).
4670 *
4671 * While the lookup by uid is more likely to succeed (since we always
4672 * have a uid, but may or may not have a login name), we prefer first
4673 * looking up by name to accommodate the possibility of multiple login
4674 * names (each with its own record in the password database, so each
4675 * with a potentially different home directory) being mapped to the
4676 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
4677 */
4678 VALUE login_name = rb_getlogin();
4679
4680# if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
4681 /* This is a corner case, but for backward compatibility reasons we
4682 * want to emit this error if neither the lookup by login name nor
4683 * lookup by getuid() has a chance of succeeding.
4684 */
4685 if (NIL_P(login_name)) {
4686 rb_raise(rb_eArgError, "couldn't find login name -- expanding '~'");
4687 }
4688# endif /* !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID) */
4689
4690 VALUE pw_dir = rb_getpwdirnam_for_login(login_name);
4691 if (NIL_P(pw_dir)) {
4692 pw_dir = rb_getpwdiruid();
4693 if (NIL_P(pw_dir)) {
4694 rb_raise(rb_eArgError, "couldn't find home for uid '%ld'", (long)getuid());
4695 }
4696 }
4697
4698 /* found it */
4699 copy_home_path(result, RSTRING_PTR(pw_dir));
4700 rb_str_resize(pw_dir, 0);
4701 return result;
4702 }
4703#endif /* defined HAVE_PWD_H */
4704 if (!dir) {
4705 rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding '~'");
4706 }
4707 return copy_home_path(result, dir);
4708}
4709
4710static VALUE
4711ospath_new(const char *ptr, long len, rb_encoding *fsenc)
4712{
4713#if NORMALIZE_UTF8PATH
4714 VALUE path = rb_str_normalize_ospath(ptr, len);
4715 rb_enc_associate(path, fsenc);
4716 return path;
4717#else
4718 return rb_enc_str_new(ptr, len, fsenc);
4719#endif
4720}
4721
4722static char *
4723append_fspath(VALUE result, VALUE fname, VALUE dirname, rb_encoding **enc, rb_encoding *fsenc)
4724{
4725 if (RB_UNLIKELY(!rb_enc_asciicompat(fsenc) || rb_enc_str_coderange(dirname) != ENC_CODERANGE_7BIT)) {
4726 dirname = rb_str_new_shared(dirname);
4727 rb_enc_associate(dirname, fsenc);
4728 }
4729
4730 char *buf, *cwdp;
4731 size_t dirlen = RSTRING_LEN(dirname);
4732 size_t buflen = rb_str_capacity(result);
4733
4734 if (NORMALIZE_UTF8PATH || *enc != fsenc) {
4735 if (!rb_enc_compatible(fname, dirname)) {
4736 /* rb_enc_check must raise because the two encodings are not
4737 * compatible. */
4738 rb_enc_check(fname, dirname);
4739 rb_bug("unreachable");
4740 }
4741 rb_encoding *direnc = fs_enc_check(fname, dirname);
4742 if (direnc != fsenc) {
4743 dirname = rb_str_conv_enc(dirname, fsenc, direnc);
4744 }
4745 *enc = direnc;
4746 }
4747
4748 RSTRING_GETMEM(dirname, cwdp, dirlen);
4749 do {buflen *= 2;} while (dirlen > buflen);
4750 rb_str_resize(result, buflen);
4751 buf = RSTRING_PTR(result);
4752 memcpy(buf, cwdp, dirlen);
4753 rb_enc_associate(result, *enc);
4754 return buf + dirlen;
4755}
4756
4757VALUE
4758rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_name, VALUE result)
4759{
4760 const char *s, *b, *fend;
4761 char *buf, *p, *pend, *root;
4762 size_t buflen, bdiff;
4763 rb_encoding *enc, *fsenc = rb_filesystem_encoding();
4764
4765 s = StringValuePtr(fname);
4766 fend = s + RSTRING_LEN(fname);
4767 enc = rb_str_enc_get(fname);
4768 bool mb_enc = enc_mbclen_needed(enc);
4769 if (!mb_enc && RTEST(dname)) {
4770 mb_enc = enc_mbclen_needed(rb_str_enc_get(dname));
4771 }
4772
4773 if (s < fend && s[0] == '~' && abs_mode == 0) { /* execute only if NOT absolute_path() */
4774 BUFINIT(result, buf, p, pend); // TOOD: right size the buffer
4775
4776 long userlen = 0;
4777 if (s + 1 == fend || isdirsep(s[1])) {
4778 buf = 0;
4779 b = 0;
4780 rb_str_set_len(result, 0);
4781 if (++s < fend) ++s;
4782 rb_default_home_dir(result);
4783 }
4784 else {
4785 s = nextdirsep(b = s, fend, enc);
4786 b++; /* b[0] is '~' */
4787 userlen = s - b;
4788 BUFCHECK(bdiff + userlen >= buflen);
4789 memcpy(p, b, userlen);
4790 ENC_CODERANGE_CLEAR(result);
4791 rb_str_set_len(result, userlen);
4792 rb_enc_associate(result, enc);
4793 rb_home_dir_of(result, result);
4794 buf = p + 1;
4795 p += userlen;
4796 }
4797 if (!rb_is_absolute_path(RSTRING_PTR(result))) {
4798 if (userlen) {
4799 rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE,
4800 (int)userlen, b, fname);
4801 }
4802 else {
4803 rb_raise(rb_eArgError, "non-absolute home");
4804 }
4805 }
4806 BUFINIT(result, buf, p, pend);
4807 p = pend;
4808 }
4809#ifdef DOSISH_DRIVE_LETTER
4810 /* skip drive letter */
4811 else if (s + 1 < fend && has_drive_letter(s)) {
4812 BUFINIT(result, buf, p, pend); // TOOD: right size the buffer
4813
4814 if (s + 2 < fend && isdirsep(s[2])) {
4815 /* specified drive letter, and full path */
4816 /* skip drive letter */
4817 BUFCHECK(bdiff + 2 >= buflen);
4818 memcpy(p, s, 2);
4819 p += 2;
4820 s += 2;
4821 rb_enc_copy(result, fname);
4822 }
4823 else {
4824 /* specified drive, but not full path */
4825 int same = 0;
4826 if (!NIL_P(dname) && !not_same_drive(dname, s[0])) {
4827 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
4828 BUFINIT(result, buf, p, pend);
4829 if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) {
4830 /* ok, same drive */
4831 same = 1;
4832 }
4833 }
4834 if (!same) {
4835 char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc);
4836 BUFINIT(result, buf, p, pend);
4837 p = e;
4838 }
4839 else {
4840 rb_enc_associate(result, enc = fs_enc_check(result, fname));
4841 p = pend;
4842 }
4843 p = chompdirsep(skiproot(buf, p), p, mb_enc, enc);
4844 s += 2;
4845 }
4846 }
4847#endif /* DOSISH_DRIVE_LETTER */
4848 else if (s == fend || !rb_is_absolute_path(s)) {
4849
4850 if (!NIL_P(dname)) {
4851 if (result) {
4852 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
4853 }
4854 else {
4855 result = rb_usascii_str_new(0, RSTRING_LEN(dname) + RSTRING_LEN(fname) + 1);
4856 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
4857
4858 if (RB_UNLIKELY(RSTRING_LEN(result) > RSTRING_LEN(dname))) {
4859 VALUE resized_result = rb_usascii_str_new(0, RSTRING_LEN(result) + RSTRING_LEN(fname) + 1);
4860 rb_str_set_len(resized_result, 0);
4861 rb_str_buf_append(resized_result, result);
4862 rb_str_set_len(result, 0);
4863 result = resized_result;
4864 }
4865 }
4866
4867 rb_enc_associate(result, fs_enc_check(result, fname));
4868 BUFINIT(result, buf, p, pend);
4869 p = pend;
4870 }
4871 else {
4872 VALUE cwd = rb_dir_getwd_ospath();
4873 if (!result) {
4874 result = rb_usascii_str_new(0, RSTRING_LEN(cwd) + RSTRING_LEN(fname) + 1);
4875 }
4876 char *e = append_fspath(result, fname, rb_dir_getwd_ospath(), &enc, fsenc);
4877 BUFINIT(result, buf, p, pend);
4878 p = e;
4879 }
4880#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4881 if (s < fend && isdirsep(*s)) {
4882 /* specified full path, but not drive letter nor UNC */
4883 /* we need to get the drive letter or UNC share name */
4884 p = skipprefix(buf, p, mb_enc, enc);
4885 }
4886 else
4887#endif /* defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC */
4888 p = chompdirsep(skiproot(buf, p), p, mb_enc, enc);
4889 }
4890 else {
4891 BUFINIT(result, buf, p, pend);
4892
4893 size_t len;
4894 b = s;
4895 do s++; while (s < fend && isdirsep(*s));
4896 len = s - b;
4897 p = buf + len;
4898 BUFCHECK(bdiff >= buflen);
4899 memset(buf, '/', len);
4900 rb_str_set_len(result, len);
4901 rb_enc_associate(result, fs_enc_check(result, fname));
4902 }
4903 if (p > buf && p[-1] == '/')
4904 --p;
4905 else {
4906 rb_str_set_len(result, p-buf);
4907 BUFCHECK(bdiff + 1 >= buflen);
4908 *p = '/';
4909 }
4910
4911 rb_str_set_len(result, p-buf+1);
4912 BUFCHECK(bdiff + 1 >= buflen);
4913 p[1] = 0;
4914 root = skipprefix(buf, p+1, mb_enc, enc);
4915
4916 b = s;
4917 while (s < fend) {
4918 switch (*s) {
4919 case '.':
4920 if (b == s++) { /* beginning of path element */
4921 if (s == fend) {
4922 b = s;
4923 break;
4924 }
4925 switch (*s) {
4926 case '.':
4927 if (s+1 == fend || isdirsep(*(s+1))) {
4928 /* We must go back to the parent */
4929 char *n;
4930 *p = '\0';
4931 if (!(n = strrdirsep(root, p, mb_enc, enc))) {
4932 *p = '/';
4933 }
4934 else {
4935 p = n;
4936 }
4937 b = ++s;
4938 }
4939 break;
4940 case '/':
4941#if defined FILE_ALT_SEPARATOR
4942 case FILE_ALT_SEPARATOR:
4943#endif
4944 b = ++s;
4945 break;
4946 default:
4947 /* ordinary path element, beginning don't move */
4948 break;
4949 }
4950 }
4951 break;
4952 case '/':
4953#if defined FILE_ALT_SEPARATOR
4954 case FILE_ALT_SEPARATOR:
4955#endif
4956 if (s > b) {
4957 WITH_ROOTDIFF(BUFCOPY(b, s-b));
4958 *p = '/';
4959 }
4960 b = ++s;
4961 break;
4962 default:
4963#ifdef __APPLE__
4964 {
4965 int n = ignored_char_p(s, fend, enc);
4966 if (n) {
4967 if (s > b) {
4968 WITH_ROOTDIFF(BUFCOPY(b, s-b));
4969 *p = '\0';
4970 }
4971 b = s += n;
4972 break;
4973 }
4974 }
4975#endif /* __APPLE__ */
4976 Inc(s, fend, mb_enc, enc);
4977 break;
4978 }
4979 }
4980
4981 if (s > b) {
4982 BUFCOPY(b, s-b);
4983 rb_str_set_len(result, p-buf);
4984 }
4985 if (p == skiproot(buf, p + !!*p) - 1) p++;
4986
4987 rb_str_set_len(result, p - buf);
4988 rb_enc_check(fname, result);
4989 ENC_CODERANGE_CLEAR(result);
4990 return result;
4991}
4992#endif /* !_WIN32 (this ifdef started above rb_default_home_dir) */
4993
4994static VALUE
4995str_shrink(VALUE str)
4996{
4997 rb_str_resize(str, RSTRING_LEN(str));
4998 return str;
4999}
5000
5001#define expand_path(fname, dname, abs_mode, long_name, result) \
5002 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
5003
5004#define check_expand_path_args(fname, dname) \
5005 (((fname) = rb_get_path(fname)), \
5006 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
5007
5008static VALUE
5009file_expand_path_1(VALUE fname, long extra_capa)
5010{
5011 VALUE buffer = rb_usascii_str_new(0, RSTRING_LEN(fname) + extra_capa);
5012 return rb_file_expand_path_internal(fname, Qnil, 0, 0, buffer);
5013}
5014
5015VALUE
5016rb_file_expand_path(VALUE fname, VALUE dname)
5017{
5018 check_expand_path_args(fname, dname);
5019 return expand_path(fname, dname, 0, 1, Qfalse);
5020}
5021
5022VALUE
5023rb_file_expand_path_fast(VALUE fname, VALUE dname)
5024{
5025 return expand_path(fname, dname, 0, 0, Qfalse);
5026}
5027
5028VALUE
5029rb_file_s_expand_path(int argc, const VALUE *argv)
5030{
5031 rb_check_arity(argc, 1, 2);
5032 return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil);
5033}
5034
5035/*
5036 * :markup: markdown
5037 *
5038 * call-seq:
5039 * File.expand_path(path, dirpath = '.') -> absolute_path
5040 *
5041 * Returns the string absolute path for the given `path`.
5042 *
5043 * Evaluates a relative path with respect to the directory given by `dirpath`:
5044 *
5045 * ```ruby
5046 * Dir.chdir('/snap')
5047 * # Default dirpath.
5048 * File.expand_path('README') # => "/snap/README"
5049 * File.expand_path('bin') # => "/snap/bin"
5050 * File.expand_path('bin/../var') # => "/snap/var" # Cleaned.
5051 * # Other dirpath.
5052 * File.expand_path('../zip', '/usr/bin/ruby') # => "/usr/bin/zip"
5053 * Dir.chdir('/usr/bin')
5054 * File.expand_path('../../snap', __FILE__) # => "/usr/snap"
5055 * ```
5056 *
5057 * Evaluates an absolute path without respect to `dirpath`:
5058 *
5059 * ```ruby
5060 * File.expand_path('/snap') # => "/snap"
5061 * File.expand_path('/snap', 'nosuch') # => "/snap"
5062 * File.expand_path('/snap/../snap') # => "/snap" # Cleaned.
5063 * ```
5064 *
5065 * More examples:
5066 *
5067 * ```
5068 * Dir.chdir('/usr/bin')
5069 * File.expand_path('../../snap', __FILE__) # => "/usr/snap"
5070 * File.expand_path('../../snap') # => "/snap"
5071 * ```
5072 *
5073 */
5074
5075static VALUE
5076s_expand_path(int c, const VALUE * v, VALUE _)
5077{
5078 return rb_file_s_expand_path(c, v);
5079}
5080
5081VALUE
5082rb_file_absolute_path(VALUE fname, VALUE dname)
5083{
5084 check_expand_path_args(fname, dname);
5085 return expand_path(fname, dname, 1, 1, Qfalse);
5086}
5087
5088VALUE
5089rb_file_s_absolute_path(int argc, const VALUE *argv)
5090{
5091 rb_check_arity(argc, 1, 2);
5092 return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil);
5093}
5094
5095/*
5096 * :markup: markdown
5097 *
5098 * call-seq:
5099 * File.absolute_path(path, dirpath = '.') -> absolute_path
5100 *
5101 * Returns the string absolute path for the given `path`.
5102 *
5103 * Evaluates a relative path with respect to the directory given by `dirpath`:
5104 *
5105 * ```ruby
5106 * Dir.chdir('/snap')
5107 * # Default dirpath.
5108 * File.absolute_path('README') # => "/snap/README"
5109 * File.absolute_path('bin') # => "/snap/bin"
5110 * File.absolute_path('bin/../var') # => "/snap/var"
5111 * # Other dirpath.
5112 * File.absolute_path('../zip', '/usr/bin/ruby') # => "/usr/bin/zip"
5113 * ```
5114 *
5115 * For an absolute path, argument `dirpath` is ignored:
5116 *
5117 * ```ruby
5118 * File.absolute_path('/snap', '/usr/bin') # => "/snap"
5119 * File.absolute_path('/snap', 'nosuch') # => "/snap"
5120 * ```
5121 *
5122 * A leading tilde character (`'~'`), is not expanded:
5123 *
5124 * ```ruby
5125 * Dir.chdir('/usr/bin')
5126 * File.absolute_path("~") # => "/usr/bin/~"
5127 * File.absolute_path("~/Documents") # => "/usr/bin/~/Documents"
5128 * ```
5129 *
5130 */
5131
5132static VALUE
5133s_absolute_path(int c, const VALUE * v, VALUE _)
5134{
5135 return rb_file_s_absolute_path(c, v);
5136}
5137
5138/*
5139 * :markup: markdown
5140 *
5141 * call-seq:
5142 * File.absolute_path?(path) -> true or false
5143 *
5144 * Returns whether the given `path` is an absolute path:
5145 *
5146 * ```ruby
5147 * File.absolute_path?('/home') # => true
5148 * File.absolute_path?('lib') # => false
5149 * ```
5150 *
5151 * The result is OS-dependent for some paths:
5152 *
5153 * ```ruby
5154 * File.absolute_path?('C:/') # => true # On Windows.
5155 * File.absolute_path?('C:/') # => false # Elsewhere.
5156 * ```
5157 *
5158 */
5159
5160static VALUE
5161s_absolute_path_p(VALUE klass, VALUE fname)
5162{
5163 VALUE path = rb_get_path(fname);
5164
5165 if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse;
5166 return Qtrue;
5167}
5168
5169enum rb_realpath_mode {
5170 RB_REALPATH_CHECK,
5171 RB_REALPATH_DIR,
5172 RB_REALPATH_STRICT,
5173 RB_REALPATH_MODE_MAX
5174};
5175
5176static int
5177realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE fallback,
5178 VALUE loopcheck, enum rb_realpath_mode mode, int last)
5179{
5180 const char *pend = unresolved + strlen(unresolved);
5181 rb_encoding *enc = rb_enc_get(*resolvedp);
5182 ID resolving;
5183 CONST_ID(resolving, "resolving");
5184 while (unresolved < pend) {
5185 const char *testname = unresolved;
5186 const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc);
5187 long testnamelen = unresolved_firstsep - unresolved;
5188 const char *unresolved_nextname = unresolved_firstsep;
5189 while (unresolved_nextname < pend && isdirsep(*unresolved_nextname))
5190 unresolved_nextname++;
5191 unresolved = unresolved_nextname;
5192 if (testnamelen == 1 && testname[0] == '.') {
5193 }
5194 else if (testnamelen == 2 && testname[0] == '.' && testname[1] == '.') {
5195 if (*prefixlenp < RSTRING_LEN(*resolvedp)) {
5196 bool mb_enc = enc_mbclen_needed(enc);
5197 const char *resolved_str = RSTRING_PTR(*resolvedp);
5198 const char *resolved_names = resolved_str + *prefixlenp;
5199 const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), mb_enc, enc);
5200 long len = lastsep ? lastsep - resolved_names : 0;
5201 rb_str_resize(*resolvedp, *prefixlenp + len);
5202 }
5203 }
5204 else {
5205 VALUE checkval;
5206 VALUE testpath = rb_str_dup(*resolvedp);
5207 if (*prefixlenp < RSTRING_LEN(testpath))
5208 rb_str_cat2(testpath, "/");
5209#if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
5210 if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) {
5211 const char *prefix = RSTRING_PTR(testpath);
5212 const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc);
5213 if (!isdirsep(*last)) rb_str_cat2(testpath, "/");
5214 }
5215#endif
5216 rb_str_cat(testpath, testname, testnamelen);
5217 checkval = rb_hash_aref(loopcheck, testpath);
5218 if (!NIL_P(checkval)) {
5219 if (checkval == ID2SYM(resolving)) {
5220 if (mode == RB_REALPATH_CHECK) {
5221 errno = ELOOP;
5222 return -1;
5223 }
5224 rb_syserr_fail_path(ELOOP, testpath);
5225 }
5226 else {
5227 *resolvedp = rb_str_dup(checkval);
5228 }
5229 }
5230 else {
5231 struct stat sbuf;
5232 int ret;
5233 ret = lstat_without_gvl(RSTRING_PTR(testpath), &sbuf);
5234 if (ret == -1) {
5235 int e = errno;
5236 if (e == ENOENT && !NIL_P(fallback)) {
5237 if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) {
5238 rb_str_replace(*resolvedp, fallback);
5239 return 0;
5240 }
5241 }
5242 if (mode == RB_REALPATH_CHECK) return -1;
5243 if (e == ENOENT) {
5244 if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep)
5245 rb_syserr_fail_path(e, testpath);
5246 *resolvedp = testpath;
5247 break;
5248 }
5249 else {
5250 rb_syserr_fail_path(e, testpath);
5251 }
5252 }
5253#ifdef HAVE_READLINK
5254 if (S_ISLNK(sbuf.st_mode)) {
5255 VALUE link;
5256 VALUE link_orig = Qnil;
5257 const char *link_prefix, *link_names;
5258 long link_prefixlen;
5259 rb_hash_aset(loopcheck, testpath, ID2SYM(resolving));
5260 link = rb_readlink(testpath, enc);
5261 link_prefix = RSTRING_PTR(link);
5262 link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link));
5263 link_prefixlen = link_names - link_prefix;
5264 if (link_prefixlen > 0) {
5265 rb_encoding *tmpenc, *linkenc = rb_enc_get(link);
5266 link_orig = link;
5267 link = rb_str_subseq(link, 0, link_prefixlen);
5268 tmpenc = fs_enc_check(*resolvedp, link);
5269 if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc);
5270 *resolvedp = link;
5271 *prefixlenp = link_prefixlen;
5272 }
5273 if (realpath_rec(prefixlenp, resolvedp, link_names, testpath,
5274 loopcheck, mode, !*unresolved_firstsep))
5275 return -1;
5276 RB_GC_GUARD(link_orig);
5277 rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp));
5278 }
5279 else
5280#endif /* HAVE_READLINK */
5281 {
5282 VALUE s = rb_str_dup_frozen(testpath);
5283 rb_hash_aset(loopcheck, s, s);
5284 *resolvedp = testpath;
5285 }
5286 }
5287 }
5288 }
5289 return 0;
5290}
5291
5292static VALUE
5293rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
5294{
5295 long prefixlen;
5296 VALUE resolved;
5297 VALUE unresolved_path;
5298 VALUE loopcheck;
5299 VALUE curdir = Qnil;
5300
5301 rb_encoding *enc;
5302 char *path_names = NULL, *basedir_names = NULL, *curdir_names = NULL;
5303 char *ptr, *prefixptr = NULL, *pend;
5304 long len;
5305
5306 unresolved_path = rb_str_dup_frozen(path);
5307
5308 if (!NIL_P(basedir)) {
5309 FilePathValue(basedir);
5310 basedir = TO_OSPATH(rb_str_dup_frozen(basedir));
5311 }
5312
5313 enc = rb_enc_get(unresolved_path);
5314 unresolved_path = TO_OSPATH(unresolved_path);
5315 RSTRING_GETMEM(unresolved_path, ptr, len);
5316 path_names = skipprefixroot(ptr, ptr + len, rb_enc_get(unresolved_path));
5317 if (ptr != path_names) {
5318 resolved = rb_str_subseq(unresolved_path, 0, path_names - ptr);
5319 goto root_found;
5320 }
5321
5322 if (!NIL_P(basedir)) {
5323 RSTRING_GETMEM(basedir, ptr, len);
5324 basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir));
5325 if (ptr != basedir_names) {
5326 resolved = rb_str_subseq(basedir, 0, basedir_names - ptr);
5327 goto root_found;
5328 }
5329 }
5330
5331 curdir = rb_dir_getwd_ospath();
5332 RSTRING_GETMEM(curdir, ptr, len);
5333 curdir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(curdir));
5334 resolved = rb_str_subseq(curdir, 0, curdir_names - ptr);
5335
5336 root_found:
5337 RSTRING_GETMEM(resolved, prefixptr, prefixlen);
5338 pend = prefixptr + prefixlen;
5339 bool mb_enc = enc_mbclen_needed(enc);
5340 ptr = chompdirsep(prefixptr, pend, mb_enc, enc);
5341 if (ptr < pend) {
5342 prefixlen = ++ptr - prefixptr;
5343 rb_str_set_len(resolved, prefixlen);
5344 }
5345#ifdef FILE_ALT_SEPARATOR
5346 while (prefixptr < ptr) {
5347 if (*prefixptr == FILE_ALT_SEPARATOR) {
5348 *prefixptr = '/';
5349 }
5350 Inc(prefixptr, pend, mb_enc, enc);
5351 }
5352#endif
5353
5354 switch (rb_enc_to_index(enc)) {
5355 case ENCINDEX_ASCII_8BIT:
5356 case ENCINDEX_US_ASCII:
5357 rb_enc_associate_index(resolved, rb_filesystem_encindex());
5358 }
5359
5360 loopcheck = rb_hash_new();
5361 if (curdir_names) {
5362 if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0))
5363 return Qnil;
5364 }
5365 if (basedir_names) {
5366 if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0))
5367 return Qnil;
5368 }
5369 if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1))
5370 return Qnil;
5371
5372 if (origenc && origenc != rb_enc_get(resolved)) {
5373 if (rb_enc_str_asciionly_p(resolved)) {
5374 rb_enc_associate(resolved, origenc);
5375 }
5376 else {
5377 resolved = rb_str_conv_enc(resolved, NULL, origenc);
5378 }
5379 }
5380
5381 RB_GC_GUARD(unresolved_path);
5382 RB_GC_GUARD(curdir);
5383 return resolved;
5384}
5385
5386static VALUE rb_file_join(long argc, VALUE *args);
5387
5388#ifndef HAVE_REALPATH
5389static VALUE
5390rb_check_realpath_emulate_try(VALUE arg)
5391{
5392 VALUE *args = (VALUE *)arg;
5393 return rb_check_realpath_emulate(args[0], args[1], (rb_encoding *)args[2], RB_REALPATH_CHECK);
5394}
5395
5396static VALUE
5397rb_check_realpath_emulate_rescue(VALUE arg, VALUE exc)
5398{
5399 return Qnil;
5400}
5401#elif !defined(NEEDS_REALPATH_BUFFER) && defined(__APPLE__) && \
5402 (!defined(MAC_OS_X_VERSION_10_6) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6))
5403/* realpath() on OSX < 10.6 doesn't implement automatic allocation */
5404# include <sys/syslimits.h>
5405# define NEEDS_REALPATH_BUFFER 1
5406#endif /* HAVE_REALPATH */
5407
5408static VALUE
5409rb_check_realpath_internal(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
5410{
5411#ifdef HAVE_REALPATH
5412 VALUE unresolved_path;
5413 char *resolved_ptr = NULL;
5414 VALUE resolved;
5415# if defined(NEEDS_REALPATH_BUFFER) && NEEDS_REALPATH_BUFFER
5416 char resolved_buffer[PATH_MAX];
5417# else
5418 char *const resolved_buffer = NULL;
5419# endif
5420
5421 if (mode == RB_REALPATH_DIR) {
5422 return rb_check_realpath_emulate(basedir, path, origenc, mode);
5423 }
5424
5425 unresolved_path = rb_str_dup_frozen(path);
5426 if (*RSTRING_PTR(unresolved_path) != '/' && !NIL_P(basedir)) {
5427 VALUE paths[2] = {basedir, unresolved_path};
5428 unresolved_path = rb_file_join(2, paths);
5429 }
5430 if (origenc) unresolved_path = TO_OSPATH(unresolved_path);
5431
5432 if ((resolved_ptr = realpath(RSTRING_PTR(unresolved_path), resolved_buffer)) == NULL) {
5433 /*
5434 wasi-libc 22 and later support realpath(3) but return ENOTSUP
5435 when the underlying host syscall returns it.
5436 glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
5437 returning ENOTDIR in that case.
5438 glibc realpath(3) can also return ENOENT for paths that exist,
5439 such as /dev/fd/5.
5440 Fallback to the emulated approach in either of those cases. */
5441 if (errno == ENOTSUP ||
5442 errno == ENOTDIR ||
5443 (errno == ENOENT && rb_file_exist_p(0, unresolved_path))) {
5444 return rb_check_realpath_emulate(basedir, path, origenc, mode);
5445
5446 }
5447 if (mode == RB_REALPATH_CHECK) {
5448 return Qnil;
5449 }
5450 rb_sys_fail_path(unresolved_path);
5451 }
5452 resolved = ospath_new(resolved_ptr, strlen(resolved_ptr), rb_filesystem_encoding());
5453# if !(defined(NEEDS_REALPATH_BUFFER) && NEEDS_REALPATH_BUFFER)
5454 free(resolved_ptr);
5455# endif
5456
5457# if !defined(__linux__) && !defined(__APPLE__)
5458 /* As `resolved` is a String in the filesystem encoding, no
5459 * conversion is needed */
5460 struct stat st;
5461 if (stat_without_gvl(RSTRING_PTR(resolved), &st) < 0) {
5462 if (mode == RB_REALPATH_CHECK) {
5463 return Qnil;
5464 }
5465 rb_sys_fail_path(unresolved_path);
5466 }
5467# endif /* !defined(__linux__) && !defined(__APPLE__) */
5468
5469 if (origenc && origenc != rb_enc_get(resolved)) {
5470 if (!rb_enc_str_asciionly_p(resolved)) {
5471 resolved = rb_str_conv_enc(resolved, NULL, origenc);
5472 }
5473 rb_enc_associate(resolved, origenc);
5474 }
5475
5476 if (is_broken_string(resolved)) {
5477 rb_enc_associate(resolved, rb_filesystem_encoding());
5478 if (is_broken_string(resolved)) {
5479 rb_enc_associate(resolved, rb_ascii8bit_encoding());
5480 }
5481 }
5482
5483 RB_GC_GUARD(unresolved_path);
5484 return resolved;
5485#else /* !HAVE_REALPATH */
5486 if (mode == RB_REALPATH_CHECK) {
5487 VALUE arg[3];
5488 arg[0] = basedir;
5489 arg[1] = path;
5490 arg[2] = (VALUE)origenc;
5491
5492 return rb_rescue(rb_check_realpath_emulate_try, (VALUE)arg,
5493 rb_check_realpath_emulate_rescue, Qnil);
5494 }
5495 else {
5496 return rb_check_realpath_emulate(basedir, path, origenc, mode);
5497 }
5498#endif /* HAVE_REALPATH */
5499}
5500
5501VALUE
5502rb_realpath_internal(VALUE basedir, VALUE path, int strict)
5503{
5504 const enum rb_realpath_mode mode =
5505 strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR;
5506 return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode);
5507}
5508
5509VALUE
5510rb_check_realpath(VALUE basedir, VALUE path, rb_encoding *enc)
5511{
5512 return rb_check_realpath_internal(basedir, path, enc, RB_REALPATH_CHECK);
5513}
5514
5515/*
5516 * call-seq:
5517 * File.realpath(pathname [, dir_string]) -> real_pathname
5518 *
5519 * Returns the real (absolute) pathname of _pathname_ in the actual
5520 * filesystem not containing symlinks or useless dots.
5521 *
5522 * If _dir_string_ is given, it is used as a base directory
5523 * for interpreting relative pathname instead of the current directory.
5524 *
5525 * All components of the pathname must exist when this method is
5526 * called.
5527 */
5528static VALUE
5529rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
5530{
5531 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
5532 VALUE path = argv[0];
5533 FilePathValue(path);
5534 return rb_realpath_internal(basedir, path, 1);
5535}
5536
5537/*
5538 * call-seq:
5539 * File.realdirpath(pathname [, dir_string]) -> real_pathname
5540 *
5541 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
5542 * The real pathname doesn't contain symlinks or useless dots.
5543 *
5544 * If _dir_string_ is given, it is used as a base directory
5545 * for interpreting relative pathname instead of the current directory.
5546 *
5547 * The last component of the real pathname can be nonexistent.
5548 */
5549static VALUE
5550rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
5551{
5552 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
5553 VALUE path = argv[0];
5554 FilePathValue(path);
5555 return rb_realpath_internal(basedir, path, 0);
5556}
5557
5558static size_t
5559rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc)
5560{
5561 int len1, len2;
5562 unsigned int c;
5563 const char *s, *last;
5564
5565 if (!e || !l2) return 0;
5566
5567 c = rb_enc_codepoint_len(e, e + l2, &len1, enc);
5568 if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) {
5569 if (c == '.') return l0;
5570 s = p;
5571 e = p + l1;
5572 last = e;
5573 while (s < e) {
5574 if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s;
5575 s += len1;
5576 }
5577 return last - p;
5578 }
5579 if (l1 < l2) return l1;
5580
5581 s = p+l1-l2;
5582 if (!at_char_boundary(p, s, p+l1, enc)) return 0;
5583#if CASEFOLD_FILESYSTEM
5584#define fncomp strncasecmp
5585#else
5586#define fncomp strncmp
5587#endif
5588 if (fncomp(s, e, l2) == 0) {
5589 return l1-l2;
5590 }
5591 return 0;
5592}
5593
5594static inline const char *
5595enc_find_basename(const char *name, long *baselen, long *alllen, bool mb_enc, rb_encoding *enc)
5596{
5597 const char *p, *q, *e, *end;
5598 long f = 0, n = -1;
5599
5600 long len = (alllen ? (size_t)*alllen : strlen(name));
5601
5602 if (len <= 0) {
5603 return name;
5604 }
5605
5606 end = name + len;
5607 name = skipprefix(name, end, mb_enc, enc);
5608#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
5609 const char *root = name;
5610#endif
5611
5612 while (name < end && isdirsep(*name)) {
5613 name++;
5614 }
5615
5616 if (name == end) {
5617 p = name - 1;
5618 f = 1;
5619#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
5620 if (name != root) {
5621 /* has slashes */
5622 }
5623#ifdef DOSISH_DRIVE_LETTER
5624 else if (*p == ':') {
5625 p++;
5626 f = 0;
5627 }
5628#endif /* DOSISH_DRIVE_LETTER */
5629#ifdef DOSISH_UNC
5630 else {
5631 p = "/";
5632 }
5633#endif /* DOSISH_UNC */
5634#endif /* defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC */
5635 }
5636 else {
5637 p = strrdirsep(name, end, mb_enc, enc);
5638 if (!p) {
5639 p = name;
5640 }
5641 else {
5642 while (isdirsep(*p)) {
5643 p++; /* skip last / */
5644 }
5645 }
5646#if USE_NTFS
5647 n = ntfs_tail(p, end, mb_enc, enc) - p;
5648#else
5649 n = chompdirsep(p, end, mb_enc, enc) - p;
5650#endif
5651 for (q = p; q - p < n && *q == '.'; q++);
5652 for (e = 0; q - p < n; Inc(q, end, mb_enc, enc)) {
5653 if (*q == '.') e = q;
5654 }
5655 if (e) {
5656 f = e - p;
5657 }
5658 else {
5659 f = n;
5660 }
5661 }
5662
5663 if (baselen) {
5664 *baselen = f;
5665 }
5666 if (alllen) {
5667 *alllen = n;
5668 }
5669 return p;
5670}
5671
5672const char *
5673ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encoding *enc)
5674{
5675 return enc_find_basename(name, baselen, alllen, enc_mbclen_needed(enc), enc);
5676}
5677
5678/*
5679 * call-seq:
5680 * File.basename(path, suffix = '') -> string
5681 *
5682 * Returns a new string containing all or part of the last component of the given +path+.
5683 * Components are delimited by the value of constant File::SEPARATOR
5684 * and, if non-+nil+, the value of constant File::ALT_SEPARATOR.
5685 *
5686 * When +suffix+ is the empty string <tt>''</tt>,
5687 * returns all of the last entry:
5688 *
5689 * File.basename('foo/bar/baz/bat.txt') # => "bat.txt"
5690 * File.basename('foo/bar/baz') # => "baz"
5691 *
5692 * File::SEPARATOR # => "/"
5693 * File.basename('foo/bar.txt////') # => "bar.txt"
5694 * File::ALT_SEPARATOR # => "\\" # On Windows.
5695 * File.basename('foo/bar.txt//\\\\//') # => "bar.txt"
5696 *
5697 * When +suffix+ is <tt>'.*'</tt>,
5698 * the last {filename extension}[https://en.wikipedia.org/wiki/Filename_extension],
5699 * if any, is removed:
5700 *
5701 * File.basename('foo/bar.txt', '.*') # => "bar"
5702 * File.basename('foo/bar.txt.old', '.*') # => "bar.txt"
5703 * File.basename('foo/bar', '.*') # => "bar"
5704 *
5705 * When +suffix+ is any string other than <tt>''</tt> or <tt>'.*'</tt>,
5706 * the matching trailing substring, if any, is removed:
5707 *
5708 * File.basename('foo/bar.txt', '.txt') # => "bar"
5709 * File.basename('foo/bar.txt', 'txt') # => "bar."
5710 * File.basename('foo/bar.txt', '*') # => "bar.txt"
5711 * File.basename('foo/bar.txt', '.') # => "bar.txt"
5712 *
5713 */
5714
5715static VALUE
5716rb_file_s_basename(int argc, VALUE *argv, VALUE _)
5717{
5718 VALUE fname, fext = Qnil;
5719 const char *name, *p, *fp = 0;
5720 long f = 0, n;
5721 rb_encoding *enc;
5722
5723 argc = rb_check_arity(argc, 1, 2);
5724 fname = argv[0];
5725 CheckPath(fname, name);
5726 if (argc == 2) {
5727 fext = argv[1];
5728 fp = StringValueCStr(fext);
5729 check_path_encoding(fext);
5730 }
5731 if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
5732 enc = rb_str_enc_get(fname);
5733 }
5734
5735 n = RSTRING_LEN(fname);
5736 if (n <= 0 || !*name) {
5737 return rb_enc_str_new(0, 0, enc);
5738 }
5739
5740 bool mb_enc = enc_mbclen_needed(enc);
5741 p = enc_find_basename(name, &f, &n, mb_enc, enc);
5742 if (n >= 0) {
5743 if (!fp) {
5744 f = n;
5745 }
5746 else {
5747 if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
5748 f = n;
5749 }
5750 RB_GC_GUARD(fext);
5751 }
5752 if (f == RSTRING_LEN(fname)) {
5753 return rb_str_new_shared(fname);
5754 }
5755 }
5756
5757 return rb_enc_str_new(p, f, enc);
5758}
5759
5760static VALUE rb_file_dirname_n(VALUE fname, int n);
5761
5762/*
5763 * call-seq:
5764 * File.dirname(path, count = 1) -> string
5765 *
5766 * Returns a string path containing all but the last +count+ components
5767 * of the given +path+:
5768 *
5769 * File.dirname('/usr/lib/linux') # => "/usr/lib"
5770 * File.dirname('/usr') # => "/"
5771 * File.dirname('/') # => "/"
5772 * File.dirname('lib/') # => "."
5773 * File.dirname('nosuch') # => "."
5774 * File.dirname('/usr/lib/linux', 2) # => "/usr"
5775 * File.dirname('/usr/lib/linux', 20) # => "/"
5776 * File.dirname('/usr/lib/linux', 0) # => "/usr/lib/linux"
5777 *
5778 * Components are delimited by File::SEPARATOR and, if non-+nil+, File::ALT_SEPARATOR.
5779 *
5780 */
5781
5782static VALUE
5783rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
5784{
5785 int n = 1;
5786 if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
5787 n = NUM2INT(argv[1]);
5788 }
5789 return rb_file_dirname_n(argv[0], n);
5790}
5791
5792VALUE
5793rb_file_dirname(VALUE fname)
5794{
5795 return rb_file_dirname_n(fname, 1);
5796}
5797
5798static VALUE
5799rb_file_dirname_n(VALUE fname, int n)
5800{
5801 const char *name, *root, *p, *end;
5802 VALUE dirname;
5803
5804 if (n < 0) rb_raise(rb_eArgError, "negative level: %d", n);
5805 CheckPath(fname, name);
5806 end = name + RSTRING_LEN(fname);
5807
5808 bool mb_enc = !rb_str_enc_fastpath(fname);
5809 rb_encoding *enc = rb_str_enc_get(fname);
5810
5811 root = skiproot(name, end);
5812#ifdef DOSISH_UNC
5813 if (root > name + 1 && isdirsep(*name))
5814 root = skipprefix(name = root - 2, end, mb_enc, enc);
5815#else
5816 if (root > name + 1)
5817 name = root - 1;
5818#endif
5819 if (n > (end - root + 1) / 2) {
5820 p = root;
5821 }
5822 else {
5823 p = end;
5824 while (n) {
5825 if (!(p = strrdirsep(root, p, mb_enc, enc))) {
5826 p = root;
5827 break;
5828 }
5829 n--;
5830 }
5831 }
5832
5833 if (p == name) {
5834 return rb_enc_str_new(".", 1, enc);
5835 }
5836#ifdef DOSISH_DRIVE_LETTER
5837 if (name + 3 < end && has_drive_letter(name) && isdirsep(*(name + 2))) {
5838 const char *top = skiproot(name + 2, end);
5839 dirname = rb_enc_str_new(name, 3, enc);
5840 rb_str_cat(dirname, top, p - top);
5841 }
5842 else
5843#endif
5844 dirname = rb_enc_str_new(name, p - name, enc);
5845#ifdef DOSISH_DRIVE_LETTER
5846 if (root == name + 2 && p == root && name[1] == ':')
5847 rb_str_cat(dirname, ".", 1);
5848#endif
5849 return dirname;
5850}
5851
5852static inline const char *
5853enc_find_extname(const char *name, long *len, bool mb_enc, rb_encoding *enc)
5854{
5855 const char *p, *e, *end = name + (len ? *len : (long)strlen(name));
5856
5857 p = strrdirsep(name, end, mb_enc, enc); /* get the last path component */
5858 if (!p)
5859 p = name;
5860 else
5861 do name = ++p; while (isdirsep(*p));
5862
5863 e = 0;
5864 while (*p && *p == '.') p++;
5865 while (*p) {
5866 if (*p == '.' || istrailinggarbage(*p)) {
5867#if USE_NTFS
5868 const char *last = p++, *dot = last;
5869 while (istrailinggarbage(*p)) {
5870 if (*p == '.') dot = p;
5871 p++;
5872 }
5873 if (!*p || isADS(*p)) {
5874 p = last;
5875 break;
5876 }
5877 if (*last == '.' || dot > last) e = dot;
5878 continue;
5879#else
5880 e = p; /* get the last dot of the last component */
5881#endif /* USE_NTFS */
5882 }
5883#if USE_NTFS
5884 else if (isADS(*p)) {
5885 break;
5886 }
5887#endif
5888 else if (isdirsep(*p))
5889 break;
5890 Inc(p, end, mb_enc, enc);
5891 }
5892
5893 if (len) {
5894 /* no dot, or the only dot is first or end? */
5895 if (!e || e == name)
5896 *len = 0;
5897 else if (e+1 == p)
5898 *len = 1;
5899 else
5900 *len = p - e;
5901 }
5902 return e;
5903}
5904
5905/*
5906 * accept a String, and return the pointer of the extension.
5907 * if len is passed, set the length of extension to it.
5908 * returned pointer is in ``name'' or NULL.
5909 * returns *len
5910 * no dot NULL 0
5911 * dotfile top 0
5912 * end with dot dot 1
5913 * .ext dot len of .ext
5914 * .ext:stream dot len of .ext without :stream (NTFS only)
5915 *
5916 */
5917const char *
5918ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc)
5919{
5920 return enc_find_extname(name, len, enc_mbclen_needed(enc), enc);
5921}
5922
5923/*
5924 * :markup: markdown
5925 *
5926 * call-seq:
5927 * File.extname(path) -> extension
5928 *
5929 * Returns the filename extension --
5930 * usually the portion of the string `path`
5931 * beginning from the last period:
5932 *
5933 * ```ruby
5934 * File.extname('t.rb') # => ".rb"
5935 * File.extname('foo.bar.t.rb') # => ".rb"
5936 * File.extname('foo/bar/t.rb') # => ".rb"
5937 * File.extname('nosuch.txt') # => ".txt" # Path need not exist.
5938 * ```
5939 *
5940 * Returns the entire string when there is no period:
5941 *
5942 * ```ruby
5943 * Pathname('foo').extname # => ""
5944 * ```
5945 *
5946 * Returns an empty string when the only period is the first character:
5947 *
5948 * ```ruby
5949 * File.extname('.irbrc') # => ""
5950 * ```
5951 *
5952 * Returns an empty string or `'.'` when `path` ends with a period:
5953 *
5954 * ```
5955 * File.extname('foo.') # => "" # On Windows.
5956 * File.extname('foo.') # => "." # Elsewhere.
5957 * File.extname('foo....') # => "" # On Windows.
5958 * File.extname('foo....') # => "." # Elsewhere.
5959 * ```
5960 *
5961 */
5962
5963static VALUE
5964rb_file_s_extname(VALUE klass, VALUE fname)
5965{
5966 const char *name;
5967 CheckPath(fname, name);
5968 long len = RSTRING_LEN(fname);
5969
5970 if (len < 1) {
5971 return rb_enc_str_new(0, 0, rb_str_enc_get(fname));
5972 }
5973
5974 bool mb_enc = !rb_str_enc_fastpath(fname);
5975 rb_encoding *enc = rb_str_enc_get(fname);
5976
5977 const char *ext = enc_find_extname(name, &len, mb_enc, enc);
5978 return rb_enc_str_new(ext, len, enc);
5979}
5980
5981/*
5982 * :markup: markdown
5983 *
5984 * call-seq:
5985 * File.path(path) -> string
5986 *
5987 * Returns a string representation of the given `path`:
5988 *
5989 * ```ruby
5990 * File.path(File::NULL) # => "/dev/null"
5991 * File.path('/tmp') # => "/tmp"
5992 * File.path('../ruby') # => "../ruby"
5993 * File.path($stdin) # => "<STDIN>"
5994 * File.path('nosuch') # => "nosuch"
5995 * ```
5996 *
5997 */
5998
5999static VALUE
6000rb_file_s_path(VALUE klass, VALUE fname)
6001{
6002 return rb_get_path(fname);
6003}
6004
6005/*
6006 * :markup: markdown
6007 *
6008 * call-seq:
6009 * File.split(string) -> array_of_strings
6010 *
6011 * Returns a 2-element array of strings containing the ::dirname and ::basename
6012 * of the the given `string`:
6013 *
6014 * ```ruby
6015 * File.split('doc/maintainers.md') # => ["doc", "maintainers.md"]
6016 * File.split('doc/') # => [".", "doc"]
6017 * File.split('README.md') # => [".", "README.md"]
6018 * File.split('/tmp/nosuch') # => ["/tmp", "nosuch"]
6019 * File.split('@@##$$/%%^^&&') # => ["@@#\#$$", "%%^^&&"]
6020 * ```
6021 *
6022 */
6023
6024static VALUE
6025rb_file_s_split(VALUE klass, VALUE path)
6026{
6027 FilePathStringValue(path); /* get rid of converting twice */
6028 return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));
6029}
6030
6031static VALUE rb_file_join_ary(VALUE ary);
6032
6033static VALUE
6034file_inspect_join(VALUE ary, VALUE arg, int recur)
6035{
6036 if (recur || ary == arg) rb_raise(rb_eArgError, "recursive array");
6037 return rb_file_join_ary(arg);
6038}
6039
6040static VALUE
6041rb_file_join_ary(VALUE ary)
6042{
6043 long len, i;
6044 VALUE result, tmp;
6045 const char *name, *tail;
6046 int checked = TRUE;
6047 rb_encoding *enc;
6048
6049 if (RARRAY_LEN(ary) == 0) return rb_str_new(0, 0);
6050
6051 len = 1;
6052 for (i=0; i<RARRAY_LEN(ary); i++) {
6053 tmp = RARRAY_AREF(ary, i);
6054 if (RB_TYPE_P(tmp, T_STRING)) {
6055 check_path_encoding(tmp);
6056 len += RSTRING_LEN(tmp);
6057 }
6058 else {
6059 len += 10;
6060 }
6061 }
6062 len += RARRAY_LEN(ary) - 1;
6063 result = rb_str_buf_new(len);
6064 RBASIC_CLEAR_CLASS(result);
6065 for (i=0; i<RARRAY_LEN(ary); i++) {
6066 tmp = RARRAY_AREF(ary, i);
6067 switch (OBJ_BUILTIN_TYPE(tmp)) {
6068 case T_STRING:
6069 if (!checked) check_path_encoding(tmp);
6070 StringValueCStr(tmp);
6071 break;
6072 case T_ARRAY:
6073 if (ary == tmp) {
6074 rb_raise(rb_eArgError, "recursive array");
6075 }
6076 else {
6077 tmp = rb_exec_recursive(file_inspect_join, ary, tmp);
6078 }
6079 break;
6080 default:
6082 checked = FALSE;
6083 }
6084 RSTRING_GETMEM(result, name, len);
6085 if (i == 0) {
6086 rb_enc_copy(result, tmp);
6087 }
6088 else {
6089 tail = chompdirsep(name, name + len, true, rb_enc_get(result));
6090 if (RSTRING_LEN(tmp) > 0 && isdirsep(RSTRING_PTR(tmp)[0])) {
6091 rb_str_set_len(result, tail - name);
6092 }
6093 else if (tail == name + len) {
6094 rb_str_cat(result, "/", 1);
6095 }
6096 }
6097 enc = fs_enc_check(result, tmp);
6098 rb_str_buf_append(result, tmp);
6099 rb_enc_associate(result, enc);
6100 }
6101 RBASIC_SET_CLASS_RAW(result, rb_cString);
6102
6103 return result;
6104}
6105
6106static inline VALUE
6107rb_file_join_fastpath(long argc, VALUE *args)
6108{
6109 long size = argc;
6110
6111 long i;
6112 for (i = 0; i < argc; i++) {
6113 VALUE tmp = args[i];
6114 if (RB_LIKELY(RB_TYPE_P(tmp, T_STRING) && rb_str_enc_fastpath(tmp))) {
6115 size += RSTRING_LEN(tmp);
6116 }
6117 else {
6118 return 0;
6119 }
6120 }
6121
6122 VALUE result = rb_str_buf_new(size);
6123
6124 int encidx = ENCODING_GET_INLINED(args[0]);
6125 ENCODING_SET_INLINED(result, encidx);
6126 rb_str_buf_append(result, args[0]);
6127
6128 const char *name = RSTRING_PTR(result);
6129 for (i = 1; i < argc; i++) {
6130 VALUE tmp = args[i];
6131 long len = RSTRING_LEN(result);
6132
6133 const char *tmp_s;
6134 long tmp_len;
6135 RSTRING_GETMEM(tmp, tmp_s, tmp_len);
6136
6137 if (tmp_len > 0 && isdirsep(tmp_s[0])) {
6138 // right side has a leading separator, remove left side separators.
6139 long chomp = len;
6140 while (chomp > 0 && isdirsep(name[chomp - 1])) {
6141 --chomp;
6142 }
6143 rb_str_set_len(result, chomp);
6144 }
6145 else if (len < 1 || !isdirsep(name[len - 1])) {
6146 // neither side have a separator, append one;
6147 rb_str_cat(result, "/", 1);
6148 }
6149
6150 if (RB_UNLIKELY(ENCODING_GET_INLINED(tmp) != encidx)) {
6151 rb_encoding *new_enc = fs_enc_check(result, tmp);
6152 rb_enc_associate(result, new_enc);
6153 encidx = rb_enc_to_index(new_enc);
6154 }
6155
6156 rb_str_buf_cat(result, tmp_s, tmp_len);
6157 }
6158
6159 rb_str_null_check(result);
6160 return result;
6161}
6162
6163static inline VALUE
6164rb_file_join(long argc, VALUE *args)
6165{
6166 if (RB_UNLIKELY(argc == 0)) {
6167 return rb_str_new(0, 0);
6168 }
6169
6170 VALUE result = rb_file_join_fastpath(argc, args);
6171 if (RB_LIKELY(result)) {
6172 return result;
6173 }
6174
6175 return rb_file_join_ary(rb_ary_new_from_values(argc, args));
6176}
6177/*
6178 * call-seq:
6179 * File.join(*components) -> string
6180 *
6181 * Returns a new string formed by joining the given string +components+
6182 * with character <tt>'/'</tt>:
6183 *
6184 * File.join # => ""
6185 * File.join('foo') # => "foo"
6186 * File.join(*%w[bar baz bat]) # => "bar/baz/bat"
6187 *
6188 */
6189
6190static VALUE
6191rb_file_s_join(int argc, VALUE *argv, VALUE klass)
6192{
6193 return rb_file_join(argc, argv);
6194}
6195
6196#if defined(HAVE_TRUNCATE)
6197struct truncate_arg {
6198 const char *path;
6199 rb_off_t pos;
6200};
6201
6202static void *
6203nogvl_truncate(void *ptr)
6204{
6205 struct truncate_arg *ta = ptr;
6206 return (void *)(VALUE)truncate(ta->path, ta->pos);
6207}
6208
6209/*
6210 * :markup: markdown
6211 *
6212 * call-seq:
6213 * File.truncate(filepath, size) -> 0
6214 *
6215 * Adjusts the size of file `filepath` to the given `size`:
6216 *
6217 * ```ruby
6218 * filepath = '/tmp/t.tmp'
6219 * File.write(filepath, '0123456789')
6220 * File.read(filepath) # => "0123456789"
6221 * File.truncate(filepath, 5)
6222 * File.read(filepath) # => "01234"
6223 * ```
6224 *
6225 * Pads with null characters if necessary:
6226 *
6227 * ```ruby
6228 * File.truncate(filepath, 10)
6229 * File.read(filepath) # => "01234\u0000\u0000\u0000\u0000\u0000"
6230 * File.delete(filepath) # Clean up.
6231 * ```
6232 *
6233 */
6234
6235static VALUE
6236rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
6237{
6238 struct truncate_arg ta;
6239 int r;
6240
6241 ta.pos = NUM2OFFT(len);
6242 FilePathValue(path);
6243 path = rb_str_encode_ospath(path);
6244 ta.path = StringValueCStr(path);
6245
6246 r = IO_WITHOUT_GVL_INT(nogvl_truncate, &ta);
6247 if (r < 0)
6248 rb_sys_fail_path(path);
6249 return INT2FIX(0);
6250}
6251#else
6252#define rb_file_s_truncate rb_f_notimplement
6253#endif
6254
6255#if defined(HAVE_FTRUNCATE)
6256struct ftruncate_arg {
6257 int fd;
6258 rb_off_t pos;
6259};
6260
6261static VALUE
6262nogvl_ftruncate(void *ptr)
6263{
6264 struct ftruncate_arg *fa = ptr;
6265
6266 return (VALUE)ftruncate(fa->fd, fa->pos);
6267}
6268
6269/*
6270 * :markup: markdown
6271 *
6272 * call-seq:
6273 * truncate(size) -> 0
6274 *
6275 * Adjusts the size of `self` to the given `size`,
6276 * regardless of the current [position](rdoc-ref:IO@Position);
6277 * does not adjust the position:
6278 *
6279 * ```ruby
6280 * filepath = '/tmp/t.tmp'
6281 * file = File.new(filepath, 'w+')
6282 * file.write('0123456789')
6283 * file.truncate(5)
6284 * file.pos # => 10
6285 * file.rewind
6286 * file.read # => "01234"
6287 * ```
6288 *
6289 * Pads with null characters if necessary:
6290 *
6291 * ```ruby
6292 * file.truncate(10)
6293 * file.pos # => 5
6294 * file.rewind
6295 * file.read # => "01234\u0000\u0000\u0000\u0000\u0000"
6296 * # Clean up.
6297 * file.close
6298 * File.delete(filepath)
6299 * ```
6300 *
6301 */
6302
6303static VALUE
6304rb_file_truncate(VALUE obj, VALUE len)
6305{
6306 rb_io_t *fptr;
6307 struct ftruncate_arg fa;
6308
6309 fa.pos = NUM2OFFT(len);
6310 GetOpenFile(obj, fptr);
6311 if (!(fptr->mode & FMODE_WRITABLE)) {
6312 rb_raise(rb_eIOError, "not opened for writing");
6313 }
6314 rb_io_flush_raw(obj, 0);
6315 fa.fd = fptr->fd;
6316 if ((int)rb_io_blocking_region(fptr, nogvl_ftruncate, &fa) < 0) {
6317 rb_sys_fail_path(fptr->pathv);
6318 }
6319 return INT2FIX(0);
6320}
6321#else
6322#define rb_file_truncate rb_f_notimplement
6323#endif
6324
6325# ifndef LOCK_SH
6326# define LOCK_SH 1
6327# endif
6328# ifndef LOCK_EX
6329# define LOCK_EX 2
6330# endif
6331# ifndef LOCK_NB
6332# define LOCK_NB 4
6333# endif
6334# ifndef LOCK_UN
6335# define LOCK_UN 8
6336# endif
6337
6338#ifdef __CYGWIN__
6339#include <winerror.h>
6340#endif
6341
6342static VALUE
6343rb_thread_flock(void *data)
6344{
6345#ifdef __CYGWIN__
6346 int old_errno = errno;
6347#endif
6348 int *op = data, ret = flock(op[0], op[1]);
6349
6350#ifdef __CYGWIN__
6351 if (GetLastError() == ERROR_NOT_LOCKED) {
6352 ret = 0;
6353 errno = old_errno;
6354 }
6355#endif
6356 return (VALUE)ret;
6357}
6358
6359/* :markup: markdown
6360 *
6361 * call-seq:
6362 * flock(locking_constant) -> 0 or false
6363 *
6364 * Locks or unlocks file `self` according to the given `locking_constant`,
6365 * a bitwise OR of the values in the table below.
6366 *
6367 * Not available on all platforms.
6368 *
6369 * Returns `false` if `File::LOCK_NB` is specified and the operation would have blocked;
6370 * otherwise returns `0`.
6371 *
6372 * | Constant | Lock | Effect
6373 * |-----------------|--------------|-----------------------------------------------------------------------------------------------------------------|
6374 * | `File::LOCK_EX` | Exclusive | Only one process may hold an exclusive lock for `self` at a time. |
6375 * | `File::LOCK_NB` | Non-blocking | No blocking; may be combined with `File::LOCK_SH` or `File::LOCK_EX` using the bitwise OR operator <tt>\|</tt>. |
6376 * | `File::LOCK_SH` | Shared | Multiple processes may each hold a shared lock for `self` at the same time. |
6377 * | `File::LOCK_UN` | Unlock | Remove an existing lock held by this process. |
6378 *
6379 * Example:
6380 *
6381 * ```ruby
6382 * # Update a counter using an exclusive lock.
6383 * # Don't use File::WRONLY because it truncates the file.
6384 * File.open('counter', File::RDWR | File::CREAT, 0644) do |f|
6385 * f.flock(File::LOCK_EX)
6386 * value = f.read.to_i + 1
6387 * f.rewind
6388 * f.write("#{value}\n")
6389 * f.flush
6390 * f.truncate(f.pos)
6391 * end
6392 *
6393 * # Read the counter using a shared lock.
6394 * File.open('counter', 'r') do |f|
6395 * f.flock(File::LOCK_SH)
6396 * f.read
6397 * end
6398 * ```
6399 *
6400 */
6401
6402static VALUE
6403rb_file_flock(VALUE obj, VALUE operation)
6404{
6405 rb_io_t *fptr;
6406 int op[2], op1;
6407 struct timeval time;
6408
6409 op[1] = op1 = NUM2INT(operation);
6410 GetOpenFile(obj, fptr);
6411 op[0] = fptr->fd;
6412
6413 if (fptr->mode & FMODE_WRITABLE) {
6414 rb_io_flush_raw(obj, 0);
6415 }
6416 while ((int)rb_io_blocking_region(fptr, rb_thread_flock, op) < 0) {
6417 int e = errno;
6418 switch (e) {
6419 case EAGAIN:
6420 case EACCES:
6421#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
6422 case EWOULDBLOCK:
6423#endif
6424 if (op1 & LOCK_NB) return Qfalse;
6425
6426 time.tv_sec = 0;
6427 time.tv_usec = 100 * 1000; /* 0.1 sec */
6428 rb_thread_wait_for(time);
6429 rb_io_check_closed(fptr);
6430 continue;
6431
6432 case EINTR:
6433#if defined(ERESTART)
6434 case ERESTART:
6435#endif
6436 break;
6437
6438 default:
6439 rb_syserr_fail_path(e, fptr->pathv);
6440 }
6441 }
6442 return INT2FIX(0);
6443}
6444
6445static void
6446test_check(int n, int argc, VALUE *argv)
6447{
6448 int i;
6449
6450 n+=1;
6451 rb_check_arity(argc, n, n);
6452 for (i=1; i<n; i++) {
6453 if (!RB_TYPE_P(argv[i], T_FILE)) {
6454 FilePathValue(argv[i]);
6455 }
6456 }
6457}
6458
6459#define CHECK(n) test_check((n), argc, argv)
6460
6461/*
6462 * :markup: markdown
6463 *
6464 * call-seq:
6465 * test(char, path0, path1 = nil) -> object
6466 *
6467 * Performs a test on one or both of the <i>filesystem entities</i> at the given paths
6468 * `path0` and `path1`:
6469 *
6470 * - Each path `path0` or `path1` points to a file, directory, device, pipe, etc.
6471 * - Character `char` selects a specific test.
6472 *
6473 * The tests:
6474 *
6475 * - Each of these tests operates only on the entity at `path0`,
6476 * and returns `true` or `false`;
6477 * for a non-existent entity, returns `false` (does not raise exception):
6478 *
6479 * | Character | Test |
6480 * |:------------:|:--------------------------------------------------------------------------|
6481 * | <tt>'b'</tt> | Whether the entity is a block device. |
6482 * | <tt>'c'</tt> | Whether the entity is a character device. |
6483 * | <tt>'d'</tt> | Whether the entity is a directory. |
6484 * | <tt>'e'</tt> | Whether the entity is an existing entity. |
6485 * | <tt>'f'</tt> | Whether the entity is an existing regular file. |
6486 * | <tt>'g'</tt> | Whether the entity's setgid bit is set. |
6487 * | <tt>'G'</tt> | Whether the entity's group ownership is equal to the caller's. |
6488 * | <tt>'k'</tt> | Whether the entity's sticky bit is set. |
6489 * | <tt>'l'</tt> | Whether the entity is a symbolic link. |
6490 * | <tt>'o'</tt> | Whether the entity is owned by the caller's effective uid. |
6491 * | <tt>'O'</tt> | Like <tt>'o'</tt>, but uses the real uid (not the effective uid). |
6492 * | <tt>'p'</tt> | Whether the entity is a FIFO device (named pipe). |
6493 * | <tt>'r'</tt> | Whether the entity is readable by the caller's effective uid/gid. |
6494 * | <tt>'R'</tt> | Like <tt>'r'</tt>, but uses the real uid/gid (not the effective uid/gid). |
6495 * | <tt>'S'</tt> | Whether the entity is a socket. |
6496 * | <tt>'u'</tt> | Whether the entity's setuid bit is set. |
6497 * | <tt>'w'</tt> | Whether the entity is writable by the caller's effective uid/gid. |
6498 * | <tt>'W'</tt> | Like <tt>'w'</tt>, but uses the real uid/gid (not the effective uid/gid). |
6499 * | <tt>'x'</tt> | Whether the entity is executable by the caller's effective uid/gid. |
6500 * | <tt>'X'</tt> | Like <tt>'x'</tt>, but uses the real uid/gid (not the effective uid/git). |
6501 * | <tt>'z'</tt> | Whether the entity exists and is of length zero. |
6502 *
6503 * - This test operates only on the entity at `path0`,
6504 * and returns an integer size or `nil`:
6505 *
6506 * | Character | Test |
6507 * |:------------:|:---------------------------------------------------------------------------------------------|
6508 * | <tt>'s'</tt> | Returns positive integer size if the entity exists and has non-zero length, `nil` otherwise. |
6509 *
6510 * - Each of these tests operates only on the entity at `path0`,
6511 * and returns a Time object;
6512 * raises an exception if the entity does not exist:
6513 *
6514 * | Character | Test |
6515 * |:------------:|:---------------------------------------|
6516 * | <tt>'A'</tt> | Last access time for the entity. |
6517 * | <tt>'C'</tt> | Last change time for the entity. |
6518 * | <tt>'M'</tt> | Last modification time for the entity. |
6519 *
6520 * - Each of these tests operates on the modification time (`mtime`)
6521 * of each of the entities at `path0` and `path1`,
6522 * and returns a `true` or `false`;
6523 * returns `false` if either entity does not exist:
6524 *
6525 * | Character | Test |
6526 * |:------------:|:----------------------------------------------------------------|
6527 * | <tt>'<'</tt> | Whether the `mtime` at `path0` is less than that at `path1`. |
6528 * | <tt>'='</tt> | Whether the `mtime` at `path0` is equal to that at `path1`. |
6529 * | <tt>'>'</tt> | Whether the `mtime` at `path0` is greater than that at `path1`. |
6530 *
6531 * - This test operates on the content of each of the entities at `path0` and `path1`,
6532 * and returns a `true` or `false`;
6533 * returns `false` if either entity does not exist:
6534 *
6535 * | Character | Test |
6536 * |:------------:|:----------------------------------------------|
6537 * | <tt>'-'</tt> | Whether the entities exist and are identical. |
6538 *
6539 */
6540
6541static VALUE
6542rb_f_test(int argc, VALUE *argv, VALUE _)
6543{
6544 int cmd;
6545
6546 if (argc == 0) rb_check_arity(argc, 2, 3);
6547 cmd = NUM2CHR(argv[0]);
6548 if (cmd == 0) {
6549 goto unknown;
6550 }
6551 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
6552 CHECK(1);
6553 switch (cmd) {
6554 case 'b':
6555 return rb_file_blockdev_p(0, argv[1]);
6556
6557 case 'c':
6558 return rb_file_chardev_p(0, argv[1]);
6559
6560 case 'd':
6561 return rb_file_directory_p(0, argv[1]);
6562
6563 case 'e':
6564 return rb_file_exist_p(0, argv[1]);
6565
6566 case 'f':
6567 return rb_file_file_p(0, argv[1]);
6568
6569 case 'g':
6570 return rb_file_sgid_p(0, argv[1]);
6571
6572 case 'G':
6573 return rb_file_grpowned_p(0, argv[1]);
6574
6575 case 'k':
6576 return rb_file_sticky_p(0, argv[1]);
6577
6578 case 'l':
6579 return rb_file_symlink_p(0, argv[1]);
6580
6581 case 'o':
6582 return rb_file_owned_p(0, argv[1]);
6583
6584 case 'O':
6585 return rb_file_rowned_p(0, argv[1]);
6586
6587 case 'p':
6588 return rb_file_pipe_p(0, argv[1]);
6589
6590 case 'r':
6591 return rb_file_readable_p(0, argv[1]);
6592
6593 case 'R':
6594 return rb_file_readable_real_p(0, argv[1]);
6595
6596 case 's':
6597 return rb_file_size_p(0, argv[1]);
6598
6599 case 'S':
6600 return rb_file_socket_p(0, argv[1]);
6601
6602 case 'u':
6603 return rb_file_suid_p(0, argv[1]);
6604
6605 case 'w':
6606 return rb_file_writable_p(0, argv[1]);
6607
6608 case 'W':
6609 return rb_file_writable_real_p(0, argv[1]);
6610
6611 case 'x':
6612 return rb_file_executable_p(0, argv[1]);
6613
6614 case 'X':
6615 return rb_file_executable_real_p(0, argv[1]);
6616
6617 case 'z':
6618 return rb_file_zero_p(0, argv[1]);
6619 }
6620 }
6621
6622 if (strchr("MAC", cmd)) {
6623 struct stat st;
6624 VALUE fname = argv[1];
6625
6626 CHECK(1);
6627 if (rb_stat(fname, &st) == -1) {
6628 int e = errno;
6629 FilePathValue(fname);
6630 rb_syserr_fail_path(e, fname);
6631 }
6632
6633 switch (cmd) {
6634 case 'A':
6635 return stat_atime(&st);
6636 case 'M':
6637 return stat_mtime(&st);
6638 case 'C':
6639 return stat_ctime(&st);
6640 }
6641 }
6642
6643 if (cmd == '-') {
6644 CHECK(2);
6645 return rb_file_identical_p(0, argv[1], argv[2]);
6646 }
6647
6648 if (strchr("=<>", cmd)) {
6649 struct stat st1, st2;
6650 stat_timestamp t1, t2;
6651
6652 CHECK(2);
6653 if (rb_stat(argv[1], &st1) < 0) return Qfalse;
6654 if (rb_stat(argv[2], &st2) < 0) return Qfalse;
6655
6656 t1 = stat_mtimespec(&st1);
6657 t2 = stat_mtimespec(&st2);
6658
6659 switch (cmd) {
6660 case '=':
6661 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
6662 return Qfalse;
6663
6664 case '>':
6665 if (t1.tv_sec > t2.tv_sec) return Qtrue;
6666 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
6667 return Qfalse;
6668
6669 case '<':
6670 if (t1.tv_sec < t2.tv_sec) return Qtrue;
6671 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
6672 return Qfalse;
6673 }
6674 }
6675 unknown:
6676 /* unknown command */
6677 if (ISPRINT(cmd)) {
6678 rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
6679 }
6680 else {
6681 rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
6682 }
6684}
6685
6686
6687/*
6688 * Document-class: File::Stat
6689 *
6690 * A \File::Stat object contains information about an entry in the file system.
6691 *
6692 * Each of these methods returns a new \File::Stat object:
6693 *
6694 * - File#lstat.
6695 * - File::Stat.new.
6696 * - File::lstat.
6697 * - File::stat.
6698 * - IO#stat.
6699 *
6700 * === Snapshot
6701 *
6702 * A new \File::Stat object takes an immediate "snapshot" of the entry's information;
6703 * the captured information is never updated,
6704 * regardless of changes in the actual entry:
6705 *
6706 * The entry must exist when File::Stat.new is called:
6707 *
6708 * filepath = 't.tmp'
6709 * File.exist?(filepath) # => false
6710 * File::Stat.new(filepath) # Raises Errno::ENOENT: No such file or directory.
6711 * File.write(filepath, 'foo') # Create the file.
6712 * stat = File::Stat.new(filepath) # Okay.
6713 *
6714 * Later changes to the actual entry do not change the \File::Stat object:
6715 *
6716 * File.atime(filepath) # => 2026-04-01 11:51:38.0014518 -0500
6717 * stat.atime # => 2026-04-01 11:51:38.0014518 -0500
6718 * File.write(filepath, 'bar')
6719 * File.atime(filepath) # => 2026-04-01 11:58:11.922614 -0500
6720 * stat.atime # => 2026-04-01 11:51:38.0014518 -0500
6721 * File.delete(filepath)
6722 * stat.atime # => 2026-04-01 11:51:38.0014518 -0500
6723 *
6724 * === OS-Dependencies
6725 *
6726 * Methods in a \File::Stat object may return platform-dependents values,
6727 * and not all values are meaningful on all systems;
6728 * for example, File::Stat#blocks returns +nil+ on Windows,
6729 * but returns an integer on Linux.
6730 *
6731 * See also Kernel#test.
6732 */
6733
6734static VALUE
6735rb_stat_s_alloc(VALUE klass)
6736{
6737 VALUE obj;
6738 stat_alloc(rb_cStat, &obj);
6739 return obj;
6740}
6741
6742/*
6743 * call-seq:
6744 * File::Stat.new(file_name) -> stat
6745 *
6746 * Create a File::Stat object for the given file name (raising an
6747 * exception if the file doesn't exist).
6748 */
6749
6750static VALUE
6751rb_stat_init(VALUE obj, VALUE fname)
6752{
6753 rb_io_stat_data st;
6754
6755 FilePathValue(fname);
6756 fname = rb_str_encode_ospath(fname);
6757 if (STATX(StringValueCStr(fname), &st, STATX_ALL) == -1) {
6758 rb_sys_fail_path(fname);
6759 }
6760
6761 struct rb_stat *rb_st;
6762 TypedData_Get_Struct(obj, struct rb_stat, &stat_data_type, rb_st);
6763
6764 rb_st->stat = st;
6765 rb_st->initialized = true;
6766
6767 return Qnil;
6768}
6769
6770/* :nodoc: */
6771static VALUE
6772rb_stat_init_copy(VALUE copy, VALUE orig)
6773{
6774 if (!OBJ_INIT_COPY(copy, orig)) return copy;
6775
6776 struct rb_stat *orig_rb_st;
6777 TypedData_Get_Struct(orig, struct rb_stat, &stat_data_type, orig_rb_st);
6778
6779 struct rb_stat *copy_rb_st;
6780 TypedData_Get_Struct(copy, struct rb_stat, &stat_data_type, copy_rb_st);
6781
6782 *copy_rb_st = *orig_rb_st;
6783 return copy;
6784}
6785
6786/*
6787 * call-seq:
6788 * stat.ftype -> string
6789 *
6790 * Returns the string type of the object at +path+, one of:
6791 *
6792 * - <tt>'file'</tt>.
6793 * - <tt>'directory'</tt>.
6794 * - <tt>'characterSpecial'</tt>.
6795 * - <tt>'blockSpecial'</tt>.
6796 * - <tt>'fifo'</tt>.
6797 * - <tt>'link'</tt>.
6798 * - <tt>'socket'</tt>.
6799 *
6800 * Examples:
6801 *
6802 * File.stat('README.md').ftype # => "file"
6803 * File.stat('lib').ftype # => "directory"
6804 * File.stat('/dev/null').ftype # => "characterSpecial"
6805 * File.stat('/dev/loop0').ftype # => "blockSpecial"
6806 *
6807 * File.mkfifo('/tmp/pipe', 0666)
6808 * File.stat('/tmp/pipe').ftype # => "fifo"
6809 *
6810 * # Follows symbolic link.
6811 * File.symlink('lib', 'lib_link')
6812 * File.stat('lib_link').ftype # => "directory"
6813 * # Does not follow symbolic link.
6814 * File.lstat('lib_link').ftype # => "link"
6815 *
6816 * require 'socket'
6817 * UNIXServer.new('/tmp/socket')
6818 * File.stat('/tmp/socket').ftype # => "socket"
6819 *
6820 * Returns <tt>'unknown'</tt> if the type cannot be determined.
6821 */
6822
6823static VALUE
6824rb_stat_ftype(VALUE obj)
6825{
6826 return rb_file_ftype(get_stat(obj)->ST_(mode));
6827}
6828
6829/*
6830 * call-seq:
6831 * stat.directory? -> true or false
6832 *
6833 * Returns +true+ if <i>stat</i> is a directory, +false+ otherwise.
6834 *
6835 * File.stat("testfile").directory? #=> false
6836 * File.stat(".").directory? #=> true
6837 */
6838
6839static VALUE
6840rb_stat_d(VALUE obj)
6841{
6842 if (S_ISDIR(get_stat(obj)->ST_(mode))) return Qtrue;
6843 return Qfalse;
6844}
6845
6846/*
6847 * :markup: markdown
6848 *
6849 * call-seq:
6850 * stat.pipe? -> true or false
6851 *
6852 * Returns whether the entry at the path in `self` is a pipe:
6853 *
6854 * ```ruby
6855 * File.stat('doc/syntax/').pipe? # => false # Directory .
6856 * File.stat('doc/maintainers.md').pipe? # => false # Regular file.
6857 * path = '/tmp/foo'
6858 * File.mkfifo(path)
6859 * File.stat(path).pipe? # => true
6860 * File.delete(path) # Clean up.
6861 * ```
6862 *
6863 */
6864
6865static VALUE
6866rb_stat_p(VALUE obj)
6867{
6868#ifdef S_IFIFO
6869 if (S_ISFIFO(get_stat(obj)->ST_(mode))) return Qtrue;
6870
6871#endif
6872 return Qfalse;
6873}
6874
6875/*
6876 * :markup: markdown
6877 *
6878 * call-seq:
6879 * symlink? -> true or false
6880 *
6881 * Returns whether the entry in `self` (see [Snapshot](rdoc-ref:File::Stat@Snapshot))
6882 * is a [symbolic link](rdoc-ref:file/symbolic_links.md):
6883 *
6884 * ```ruby
6885 * filepath = '/etc/passwd'
6886 * linkpath = '/tmp/foo'
6887 * File.symlink(filepath, linkpath)
6888 * File.stat(filepath).symlink? # => false
6889 * File.lstat(filepath).symlink? # => false
6890 * stat = File.stat(linkpath) # Snapshot with stat follows link.
6891 * stat.symlink? # => false
6892 * lstat = File.lstat(linkpath) # Snapshot with lstat does not follow link.
6893 * lstat.symlink? # => true
6894 * File.delete(linkpath) # Clean up.
6895 * # Snapshots are unchanged, even when link deleted.
6896 * stat.symlink? # => false
6897 * lstat.symlink? # => true
6898 * ```
6899 *
6900 */
6901
6902static VALUE
6903rb_stat_l(VALUE obj)
6904{
6905#ifdef S_ISLNK
6906 if (S_ISLNK(get_stat(obj)->ST_(mode))) return Qtrue;
6907#endif
6908 return Qfalse;
6909}
6910
6911/*
6912 * :markup: markdown
6913 *
6914 * call-seq:
6915 * socket? -> true or false
6916 *
6917 * Returns whether entry in `self` is a socket:
6918 *
6919 * ```ruby
6920 * sock_path = '/tmp/socket'
6921 * server = UNIXServer.new(sock_path)
6922 * stat = File.stat(sock_path)
6923 * stat.socket? # => true
6924 * File.delete(sock_path) # Clean up.
6925 * stat.socket? # => true
6926 * file_path = '/etc/passwd'
6927 * File.exist?(file_path) # => true # Snapshot not updated.
6928 * stat = File.stat(file_path)
6929 * stat.socket? # => false
6930 * ```
6931 *
6932 */
6933
6934static VALUE
6935rb_stat_S(VALUE obj)
6936{
6937#ifdef S_ISSOCK
6938 if (S_ISSOCK(get_stat(obj)->ST_(mode))) return Qtrue;
6939
6940#endif
6941 return Qfalse;
6942}
6943
6944/*
6945 * call-seq:
6946 * stat.blockdev? -> true or false
6947 *
6948 * Returns +true+ if the file is a block device, +false+ if it isn't or if
6949 * the operating system doesn't support this feature.
6950 *
6951 * File.stat("testfile").blockdev? #=> false
6952 * File.stat("/dev/hda1").blockdev? #=> true
6953 *
6954 */
6955
6956static VALUE
6957rb_stat_b(VALUE obj)
6958{
6959#ifdef S_ISBLK
6960 if (S_ISBLK(get_stat(obj)->ST_(mode))) return Qtrue;
6961
6962#endif
6963 return Qfalse;
6964}
6965
6966/*
6967 * call-seq:
6968 * stat.chardev? -> true or false
6969 *
6970 * Returns +true+ if the file is a character device, +false+ if it isn't or
6971 * if the operating system doesn't support this feature.
6972 *
6973 * File.stat("/dev/tty").chardev? #=> true
6974 *
6975 */
6976
6977static VALUE
6978rb_stat_c(VALUE obj)
6979{
6980 if (S_ISCHR(get_stat(obj)->ST_(mode))) return Qtrue;
6981
6982 return Qfalse;
6983}
6984
6985/*
6986 * :markup: markdown
6987 *
6988 * call-seq:
6989 * owned? -> true or false
6990 *
6991 * Returns whether `self` represents a filesystem entry that,
6992 * at the time `self` was created,
6993 * existed and was owned by the user of the current process;
6994 * see [Snapshot](rdoc-ref:File::Stat@Snapshot):
6995 *
6996 * ```ruby
6997 * filepath = 'doc/t.tmp'
6998 * File.write(filepath, 'foo')
6999 * filestat = File.stat(filepath)
7000 * filestat.owned? # => true
7001 * File.delete(filepath)
7002 * filestat.owned? # => true # Snapshot unchanged.
7003 * dirpath = 'doc/tmp'
7004 * Dir.mkdir(dirpath)
7005 * dirstat = File.stat(dirpath)
7006 * dirstat.owned? # => true
7007 * Dir.rmdir(dirpath)
7008 * dirstat.owned? # => true # Snapshot unchanged.
7009 * File.stat('/etc').owned? # => false
7010 * ```
7011 *
7012 */
7013
7014static VALUE
7015rb_stat_owned(VALUE obj)
7016{
7017 if (get_stat(obj)->ST_(uid) == geteuid()) return Qtrue;
7018 return Qfalse;
7019}
7020
7021static VALUE
7022rb_stat_rowned(VALUE obj)
7023{
7024 if (get_stat(obj)->ST_(uid) == getuid()) return Qtrue;
7025 return Qfalse;
7026}
7027
7028/*
7029 * call-seq:
7030 * stat.grpowned?(path) -> true or false
7031 *
7032 * Returns whether the filesystem entry for the given string +path+ exists,
7033 * and the effective group id of the calling process is the owner of the entry:
7034 *
7035 * File.stat('README.md').grpowned? # => true
7036 * File.stat('lib').grpowned? # => true
7037 * File.stat('/etc/passwd').grpowned? # => false
7038 *
7039 * Raises an exception if there is no entry at the given +path+.
7040 *
7041 * Returns +false+ on Windows.
7042 */
7043
7044static VALUE
7045rb_stat_grpowned(VALUE obj)
7046{
7047#ifndef _WIN32
7048 if (rb_group_member(get_stat(obj)->ST_(gid))) return Qtrue;
7049#endif
7050 return Qfalse;
7051}
7052
7053/*
7054 * :markup: markdown
7055 *
7056 * call-seq:
7057 * readable? -> true or false
7058 *
7059 * Returns whether the entry represented by `self`
7060 * exists and is readable by the owner and group of the current process;
7061 * see [Permissions](rdoc-ref:file/filesystem_modes.md@Permissions):
7062 *
7063 * ```ruby
7064 * path = '/tmp/secret.txt'
7065 * File.write(path, 'foo')
7066 * File.stat(path).readable? # => true
7067 * File.chmod(0o000, path)
7068 * File.stat(path).readable? # => false
7069 * File.delete(path) # Clean up.
7070 * ```
7071 *
7072 */
7073
7074static VALUE
7075rb_stat_r(VALUE obj)
7076{
7077 rb_io_stat_data *st = get_stat(obj);
7078
7079#ifdef USE_GETEUID
7080 if (geteuid() == 0) return Qtrue;
7081#endif
7082#ifdef S_IRUSR
7083 if (rb_stat_owned(obj))
7084 return RBOOL(st->ST_(mode) & S_IRUSR);
7085#endif
7086#ifdef S_IRGRP
7087 if (rb_stat_grpowned(obj))
7088 return RBOOL(st->ST_(mode) & S_IRGRP);
7089#endif
7090#ifdef S_IROTH
7091 if (!(st->ST_(mode) & S_IROTH)) return Qfalse;
7092#endif
7093 return Qtrue;
7094}
7095
7096/*
7097 * :markup: markdown
7098 *
7099 * call-seq:
7100 * stat.readable_real? -> true or false
7101 *
7102 * Like #readable?, but checks against the real user and group ids
7103 * instead of the effective ids.
7104 */
7105
7106static VALUE
7107rb_stat_R(VALUE obj)
7108{
7109 rb_io_stat_data *st = get_stat(obj);
7110
7111#ifdef USE_GETEUID
7112 if (getuid() == 0) return Qtrue;
7113#endif
7114#ifdef S_IRUSR
7115 if (rb_stat_rowned(obj))
7116 return RBOOL(st->ST_(mode) & S_IRUSR);
7117#endif
7118#ifdef S_IRGRP
7119 if (rb_group_member(get_stat(obj)->ST_(gid)))
7120 return RBOOL(st->ST_(mode) & S_IRGRP);
7121#endif
7122#ifdef S_IROTH
7123 if (!(st->ST_(mode) & S_IROTH)) return Qfalse;
7124#endif
7125 return Qtrue;
7126}
7127
7128/*
7129 * call-seq:
7130 * stat.world_readable? -> integer or nil
7131 *
7132 * If <i>stat</i> is readable by others, returns an integer
7133 * representing the file permission bits of <i>stat</i>. Returns +nil+
7134 * otherwise. The meaning of the bits is platform dependent; on Unix
7135 * systems, see <code>stat(2)</code>.
7136 *
7137 * m = File.stat("/etc/passwd").world_readable? #=> 420
7138 * sprintf("%o", m) #=> "644"
7139 */
7140
7141static VALUE
7142rb_stat_wr(VALUE obj)
7143{
7144#ifdef S_IROTH
7145 rb_io_stat_data *st = get_stat(obj);
7146 if ((st->ST_(mode) & (S_IROTH)) == S_IROTH) {
7147 return UINT2NUM(st->ST_(mode) & (S_IRUGO|S_IWUGO|S_IXUGO));
7148 }
7149#endif
7150 return Qnil;
7151}
7152
7153/*
7154 * call-seq:
7155 * stat.writable? -> true or false
7156 *
7157 * Returns +true+ if <i>stat</i> is writable by the effective user id of this
7158 * process.
7159 *
7160 * File.stat("testfile").writable? #=> true
7161 *
7162 */
7163
7164static VALUE
7165rb_stat_w(VALUE obj)
7166{
7167 rb_io_stat_data *st = get_stat(obj);
7168
7169#ifdef USE_GETEUID
7170 if (geteuid() == 0) return Qtrue;
7171#endif
7172#ifdef S_IWUSR
7173 if (rb_stat_owned(obj))
7174 return RBOOL(st->ST_(mode) & S_IWUSR);
7175#endif
7176#ifdef S_IWGRP
7177 if (rb_stat_grpowned(obj))
7178 return RBOOL(st->ST_(mode) & S_IWGRP);
7179#endif
7180#ifdef S_IWOTH
7181 if (!(st->ST_(mode) & S_IWOTH)) return Qfalse;
7182#endif
7183 return Qtrue;
7184}
7185
7186/*
7187 * call-seq:
7188 * stat.writable_real? -> true or false
7189 *
7190 * Returns +true+ if <i>stat</i> is writable by the real user id of this
7191 * process.
7192 *
7193 * File.stat("testfile").writable_real? #=> true
7194 *
7195 */
7196
7197static VALUE
7198rb_stat_W(VALUE obj)
7199{
7200 rb_io_stat_data *st = get_stat(obj);
7201
7202#ifdef USE_GETEUID
7203 if (getuid() == 0) return Qtrue;
7204#endif
7205#ifdef S_IWUSR
7206 if (rb_stat_rowned(obj))
7207 return RBOOL(st->ST_(mode) & S_IWUSR);
7208#endif
7209#ifdef S_IWGRP
7210 if (rb_group_member(get_stat(obj)->ST_(gid)))
7211 return RBOOL(st->ST_(mode) & S_IWGRP);
7212#endif
7213#ifdef S_IWOTH
7214 if (!(st->ST_(mode) & S_IWOTH)) return Qfalse;
7215#endif
7216 return Qtrue;
7217}
7218
7219/*
7220 * call-seq:
7221 * stat.world_writable? -> integer or nil
7222 *
7223 * If <i>stat</i> is writable by others, returns an integer
7224 * representing the file permission bits of <i>stat</i>. Returns +nil+
7225 * otherwise. The meaning of the bits is platform dependent; on Unix
7226 * systems, see <code>stat(2)</code>.
7227 *
7228 * m = File.stat("/tmp").world_writable? #=> 511
7229 * sprintf("%o", m) #=> "777"
7230 */
7231
7232static VALUE
7233rb_stat_ww(VALUE obj)
7234{
7235#ifdef S_IWOTH
7236 rb_io_stat_data *st = get_stat(obj);
7237 if ((st->ST_(mode) & (S_IWOTH)) == S_IWOTH) {
7238 return UINT2NUM(st->ST_(mode) & (S_IRUGO|S_IWUGO|S_IXUGO));
7239 }
7240#endif
7241 return Qnil;
7242}
7243
7244/*
7245 * call-seq:
7246 * executable? -> true or false
7247 *
7248 * Returns whether the filesystem entry represented by +self+
7249 * exists and is executable;
7250 * raises Errno::ENOENT if the entry does not exist.
7251 *
7252 * On Windows, the entry is executable if its path has file extension
7253 * +.bat+, +.cmd+, +.com+, or +.exe+:
7254 *
7255 * File.stat('win32/rtname.cmd').executable? # => true
7256 * File.stat('win32/file.c').executable? # => false
7257 *
7258 * On other systems, the entry is executable if it has the execute/search
7259 * permission for the effective user and group id of the current process;
7260 * see {Permissions}[rdoc-ref:file/filesystem_modes.md@Permissions].
7261 *
7262 * These examples use
7263 * a {helper method}[rdoc-ref:file/filesystem_modes.md@Helper+Method], +mode+,
7264 * that displays a mode both in octal digits and in characters:
7265 *
7266 * File.stat('.').executable? # => true
7267 * mode('.') # => "040775 drwxrwxr-x"
7268 * File.stat('bin/gem').executable? # => true
7269 * mode('bin/gem') # => "100775 -rwxrwxr-x"
7270 * File.stat('/etc/passwd').executable? # => false
7271 * mode('/etc/passwd') # => "100644 -rw-r--r--"
7272 *
7273 * Note that some filesystem settings may cause this method to return +true+
7274 * even though the entry is not executable by the effective user/group.
7275 */
7276
7277static VALUE
7278rb_stat_x(VALUE obj)
7279{
7280 rb_io_stat_data *st = get_stat(obj);
7281
7282#ifdef USE_GETEUID
7283 if (geteuid() == 0) {
7284 return RBOOL(st->ST_(mode) & S_IXUGO);
7285 }
7286#endif
7287#ifdef S_IXUSR
7288 if (rb_stat_owned(obj))
7289 return RBOOL(st->ST_(mode) & S_IXUSR);
7290#endif
7291#ifdef S_IXGRP
7292 if (rb_stat_grpowned(obj))
7293 return RBOOL(st->ST_(mode) & S_IXGRP);
7294#endif
7295#ifdef S_IXOTH
7296 if (!(st->ST_(mode) & S_IXOTH)) return Qfalse;
7297#endif
7298 return Qtrue;
7299}
7300
7301/*
7302 * call-seq:
7303 * stat.executable_real? -> true or false
7304 *
7305 * Same as <code>executable?</code>, but tests using the real owner of
7306 * the process.
7307 */
7308
7309static VALUE
7310rb_stat_X(VALUE obj)
7311{
7312 rb_io_stat_data *st = get_stat(obj);
7313
7314#ifdef USE_GETEUID
7315 if (getuid() == 0) {
7316 return RBOOL(st->ST_(mode) & S_IXUGO);
7317 }
7318#endif
7319#ifdef S_IXUSR
7320 if (rb_stat_rowned(obj))
7321 return RBOOL(st->ST_(mode) & S_IXUSR);
7322#endif
7323#ifdef S_IXGRP
7324 if (rb_group_member(get_stat(obj)->ST_(gid)))
7325 return RBOOL(st->ST_(mode) & S_IXGRP);
7326#endif
7327#ifdef S_IXOTH
7328 if (!(st->ST_(mode) & S_IXOTH)) return Qfalse;
7329#endif
7330 return Qtrue;
7331}
7332
7333/*
7334 * call-seq:
7335 * file? -> true or false
7336 *
7337 * Returns whether +self+ represents a filesystem entry that exists and is a regular file;
7338 * see File::Stat.ftype:
7339 *
7340 * # Paths.
7341 * File.stat('README.md').file? # => true
7342 * File.stat('doc/').file? # => false
7343 * File.stat('nosuch').file? # Raises Errno::ENOENT: No such file or directory.
7344 *
7345 *
7346 */
7347
7348static VALUE
7349rb_stat_f(VALUE obj)
7350{
7351 if (S_ISREG(get_stat(obj)->ST_(mode))) return Qtrue;
7352 return Qfalse;
7353}
7354
7355/*
7356 * call-seq:
7357 * stat.zero? -> true or false
7358 *
7359 * Returns +true+ if <i>stat</i> is a zero-length file; +false+ otherwise.
7360 *
7361 * File.stat("testfile").zero? #=> false
7362 *
7363 */
7364
7365static VALUE
7366rb_stat_z(VALUE obj)
7367{
7368 if (get_stat(obj)->ST_(size) == 0) return Qtrue;
7369 return Qfalse;
7370}
7371
7372/*
7373 * :markup: markdown
7374 *
7375 * call-seq:
7376 * size? -> integer or nil
7377 *
7378 * Returns the size in bytes of the entry in `self`
7379 * if the entry exists and has non-zero size, `nil` otherwise:
7380 *
7381 * ```ruby
7382 * path = '/tmp/t.tmp'
7383 * File.write(path, 'foo')
7384 * File.size(path) # => 3
7385 * stat = File.stat(path) # Take snapshot.
7386 * stat.size? # => 3 # Non-zero size.
7387 * File.write(path, '')
7388 * File.size(path) # => 0
7389 * stat.size? # => 3 # Snapshot unchanged.
7390 * stat = File.stat(path) # Take new snapshot.
7391 * stat.size? # => nil # Zero size
7392 * File.delete(path) # Clean up.
7393 * ```
7394 *
7395 */
7396
7397static VALUE
7398rb_stat_s(VALUE obj)
7399{
7400 rb_off_t size = get_stat(obj)->ST_(size);
7401
7402 if (size == 0) return Qnil;
7403 return OFFT2NUM(size);
7404}
7405
7406/*
7407 * :markup: markdown
7408 *
7409 * call-seq:
7410 * setuid? -> true or false
7411 *
7412 * Returns whether the setuid bit is set
7413 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
7414 * for the entry represented in `self`:
7415 *
7416 * ```ruby
7417 * path = '/tmp/t.tmp'
7418 * File.write(path, 'foo')
7419 * stat = File.stat(path) # Take snapshot; bit not set.
7420 * stat.setuid? # => false
7421 * stat.mode.to_s(8) # => "100664"
7422 * File.chmod(0o4644, path) # Set the bit; snapshot not updated.
7423 * stat.setuid? # => false
7424 * stat.mode.to_s(8) # => "100664"
7425 * stat = File.stat(path) # Fresh snapshot.
7426 * stat.setuid? # => true
7427 * stat.mode.to_s(8) # => "104644"
7428 * File.delete(path) # Clean up.
7429 * ```
7430 *
7431 * On Windows, the bit is never set; the method always returns `false`.
7432 */
7433
7434static VALUE
7435rb_stat_suid(VALUE obj)
7436{
7437#ifdef S_ISUID
7438 if (get_stat(obj)->ST_(mode) & S_ISUID) return Qtrue;
7439#endif
7440 return Qfalse;
7441}
7442
7443/*
7444 * :markup: markdown
7445 *
7446 * call-seq:
7447 * setgid? -> true or false
7448 *
7449 * Returns whether the setgid bit is set
7450 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
7451 * for the entry represented in `self`:
7452 *
7453 * ```ruby
7454 * path = '/tmp/t.tmp'
7455 * File.write(path, 'foo')
7456 * stat = File.stat(path) # Take a snapshot.
7457 * stat.setgid? # => false
7458 * stat.mode.to_s(8) # => "100664"
7459 * File.chmod(0o2644, path) # Set the bit; stat snapshot unchanged.
7460 * stat.setgid? # => false
7461 * stat.mode.to_s(8) # => "100664"
7462 * stat = File.stat(path) # Fresh stat; snapshot changed.
7463 * stat.setgid? # => true
7464 * stat.mode.to_s(8) # => "102644"
7465 * File.delete(path) # Clean up.
7466 * ```
7467 *
7468 * On Windows, the bit is never set; the method always returns `false`.
7469 */
7470
7471static VALUE
7472rb_stat_sgid(VALUE obj)
7473{
7474#ifdef S_ISGID
7475 if (get_stat(obj)->ST_(mode) & S_ISGID) return Qtrue;
7476#endif
7477 return Qfalse;
7478}
7479
7480/*
7481 * :markup: markdown
7482
7483 * call-seq:
7484 * sticky? -> true or false
7485 *
7486 * Returns whether the sticky bit is set
7487 * in the [special bits](rdoc-ref:file/filesystem_modes.md@Special+Bits)
7488 * for `self`:
7489 *
7490 * ```ruby
7491 * filepath = '/tmp/t.tmp'
7492 * File.write(filepath, 'foo')
7493 * stat = File.stat(filepath)
7494 * stat.sticky? # => false
7495 * stat.mode.to_s(8) # => "100664"
7496 * File.chmod(01644, filepath) # => 1 # Stat unchanged.
7497 * stat.sticky? # => false
7498 * stat.mode.to_s(8) # => "100664"
7499 * stat = File.stat(filepath) # Fresh stat.
7500 * stat.sticky? # => true
7501 * stat.mode.to_s(8) # => "101644"
7502 * File.delete(filepath) # Clean up.
7503 * ```
7504 *
7505 * Returns `false` on Windows.
7506 */
7507
7508static VALUE
7509rb_stat_sticky(VALUE obj)
7510{
7511#ifdef S_ISVTX
7512 if (get_stat(obj)->ST_(mode) & S_ISVTX) return Qtrue;
7513#endif
7514 return Qfalse;
7515}
7516
7517#if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
7518#define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
7519#define HAVE_MKFIFO
7520#endif
7521
7522#ifdef HAVE_MKFIFO
7523struct mkfifo_arg {
7524 const char *path;
7525 mode_t mode;
7526};
7527
7528static void *
7529nogvl_mkfifo(void *ptr)
7530{
7531 struct mkfifo_arg *ma = ptr;
7532
7533 return (void *)(VALUE)mkfifo(ma->path, ma->mode);
7534}
7535
7536/*
7537 * :markup: markdown
7538 *
7539 * call-seq:
7540 * File.mkfifo(path, mode = 0666) -> 0
7541 *
7542 * Creates a FIFO special file at the given `path`,
7543 * with the permissions given by `mode`;
7544 * see [Filesystem Modes](rdoc-ref:file/filesystem_modes.md):
7545 *
7546 * ```ruby
7547 * path = '/tmp/pipe'
7548 * File.mkfifo(path)
7549 * File.pipe?(path) # => true
7550 * File.ftype(path) # => "fifo"
7551 * File.unlink(path)
7552 * ```
7553 *
7554 * Not implemented on Windows.
7555 */
7556
7557static VALUE
7558rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _)
7559{
7560 VALUE path;
7561 struct mkfifo_arg ma;
7562
7563 ma.mode = 0666;
7564 rb_check_arity(argc, 1, 2);
7565 if (argc > 1) {
7566 ma.mode = NUM2MODET(argv[1]);
7567 }
7568 path = argv[0];
7569 FilePathValue(path);
7570 path = rb_str_encode_ospath(path);
7571 ma.path = RSTRING_PTR(path);
7572 if (IO_WITHOUT_GVL(nogvl_mkfifo, &ma)) {
7573 rb_sys_fail_path(path);
7574 }
7575 return INT2FIX(0);
7576}
7577#else
7578#define rb_file_s_mkfifo rb_f_notimplement
7579#endif
7580
7581static VALUE rb_mFConst;
7582
7583void
7584rb_file_const(const char *name, VALUE value)
7585{
7586 rb_define_const(rb_mFConst, name, value);
7587}
7588
7589int
7590rb_is_absolute_path(const char *path)
7591{
7592#ifdef DOSISH_DRIVE_LETTER
7593 if (has_drive_letter(path) && isdirsep(path[2])) return 1;
7594#endif
7595#ifdef DOSISH_UNC
7596 if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
7597#endif
7598#ifndef DOSISH
7599 if (path[0] == '/') return 1;
7600#endif
7601 return 0;
7602}
7603
7604int
7605ruby_is_fd_loadable(int fd)
7606{
7607#ifdef _WIN32
7608 return 1;
7609#else
7610 struct stat st;
7611
7612 if (fstat(fd, &st) < 0)
7613 return 0;
7614
7615 if (S_ISREG(st.st_mode))
7616 return 1;
7617
7618 if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
7619 return -1;
7620
7621 if (S_ISDIR(st.st_mode))
7622 errno = EISDIR;
7623 else
7624 errno = ENXIO;
7625
7626 return 0;
7627#endif
7628}
7629
7630#ifndef _WIN32
7631int
7632rb_file_load_ok(const char *path)
7633{
7634 int ret = 1;
7635 /*
7636 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
7637 FIXME: Why O_NDELAY is checked?
7638 */
7639 int mode = (O_RDONLY |
7640#if defined O_NONBLOCK
7641 O_NONBLOCK |
7642#elif defined O_NDELAY
7643 O_NDELAY |
7644#endif
7645 0);
7646 int fd = rb_cloexec_open(path, mode, 0);
7647 if (fd < 0) {
7648 if (!rb_gc_for_fd(errno)) return 0;
7649 fd = rb_cloexec_open(path, mode, 0);
7650 if (fd < 0) return 0;
7651 }
7652 rb_update_max_fd(fd);
7653 ret = ruby_is_fd_loadable(fd);
7654 (void)close(fd);
7655 return ret;
7656}
7657#endif
7658
7659static int
7660is_explicit_relative(const char *path)
7661{
7662 if (*path++ != '.') return 0;
7663 if (*path == '.') path++;
7664 return isdirsep(*path);
7665}
7666
7667static VALUE
7668copy_path_class(VALUE path, VALUE orig)
7669{
7670 int encidx = rb_enc_get_index(orig);
7671 if (encidx == ENCINDEX_ASCII_8BIT || encidx == ENCINDEX_US_ASCII)
7672 encidx = rb_filesystem_encindex();
7673 rb_enc_associate_index(path, encidx);
7674 str_shrink(path);
7675 RBASIC_SET_CLASS(path, rb_obj_class(orig));
7676 OBJ_FREEZE(path);
7677 return path;
7678}
7679
7680static bool
7681nav_component_p(const char *s, const char *send)
7682{
7683 if ((send - s) >= 2 && s[0] == '.') {
7684 return s[1] == '.' || isdirsep(s[1]);
7685 }
7686 return false;
7687}
7688
7689static bool
7690fname_need_expansion_p(VALUE fname)
7691{
7692 const char *s = RSTRING_PTR(fname);
7693 const long len = RSTRING_LEN(fname);
7694 const char *send = s + len;
7695
7696 if (nav_component_p(s, send)) {
7697 return true;
7698 }
7699
7700 rb_encoding *enc = rb_str_enc_get(fname);
7701 bool mbenc = enc_mbclen_needed(enc);
7702
7703 s = enc_path_next(s, send, mbenc, enc);
7704 while (s < send) {
7705 if (nav_component_p(s, send)) {
7706 return true;
7707 }
7708 s++;
7709 s = enc_path_next(s, send, mbenc, enc);
7710 }
7711 return false;
7712}
7713
7714static bool
7715expand_feature(VALUE fname, VALUE dname, VALUE buffer, bool need_expansion)
7716{
7717 long dname_len = RSTRING_LEN(dname);
7718 const char *dname_ptr = RSTRING_PTR(dname);
7719
7720 RUBY_ASSERT(dname_len > 0);
7721
7722 if (need_expansion || dname_ptr[0] == '~') {
7723 rb_file_expand_path_internal(fname, dname, 0, 0, buffer);
7724 }
7725 else {
7726 rb_str_set_len(buffer, 0);
7727 rb_str_append(buffer, dname);
7728 if (!isdirsep(dname_ptr[dname_len - 1])) {
7729 rb_str_cat(buffer, "/", 1);
7730 }
7731 rb_str_append(buffer, fname);
7732 }
7733 return true;
7734}
7735
7736int
7737rb_find_file_ext(VALUE *filep, const char *const *ext)
7738{
7739 const char *f = StringValueCStr(*filep);
7740 VALUE fname = *filep;
7741 long i, j, fnlen;
7742 int expanded = 0;
7743
7744 if (!ext[0]) return 0;
7745
7746 if (f[0] == '~') {
7747 fname = file_expand_path_1(fname, DLEXT_MAXLEN);
7748 f = RSTRING_PTR(fname);
7749 *filep = fname;
7750 expanded = 1;
7751 }
7752
7753 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
7754 if (!expanded) fname = file_expand_path_1(fname, DLEXT_MAXLEN);
7755 fnlen = RSTRING_LEN(fname);
7756 for (i=0; ext[i]; i++) {
7757 rb_str_cat2(fname, ext[i]);
7758 if (rb_file_load_ok(RSTRING_PTR(fname))) {
7759 *filep = copy_path_class(fname, *filep);
7760 return (int)(i+1);
7761 }
7762 rb_str_set_len(fname, fnlen);
7763 }
7764 return 0;
7765 }
7766
7767 long expanded_load_path_maxlen;
7768 VALUE load_path = rb_get_expanded_load_path(&expanded_load_path_maxlen);
7769 if (!load_path) return 0;
7770
7771 fname = rb_str_dup(*filep);
7772 RBASIC_CLEAR_CLASS(fname);
7773 fnlen = RSTRING_LEN(fname);
7774 bool need_expansion = fname_need_expansion_p(fname);
7775
7776 VALUE tmp = rb_str_tmp_new(expanded_load_path_maxlen + fnlen + 2);
7777 rb_enc_associate_index(tmp, rb_usascii_encindex());
7778
7779 for (j=0; ext[j]; j++) {
7780 rb_str_cat2(fname, ext[j]);
7781 for (i = 0; i < RARRAY_LEN(load_path); i++) {
7782 VALUE dname = rb_get_path(RARRAY_AREF(load_path, i));
7783 if (!RSTRING_LEN(dname)) continue;
7784 expand_feature(fname, dname, tmp, need_expansion);
7785
7786 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
7787 *filep = copy_path_class(tmp, *filep);
7788 return (int)(j+1);
7789 }
7790 }
7791 rb_str_set_len(fname, fnlen);
7792 }
7793 rb_str_resize(tmp, 0);
7794 RB_GC_GUARD(load_path);
7795 RB_GC_GUARD(tmp);
7796 return 0;
7797}
7798
7799VALUE
7800rb_find_file(VALUE path)
7801{
7802 const char *f = StringValueCStr(path);
7803 int expanded = 0;
7804
7805 if (f[0] == '~') {
7806 path = copy_path_class(file_expand_path_1(path, 0), path);
7807 f = RSTRING_PTR(path);
7808 expanded = 1;
7809 }
7810
7811 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
7812 if (!rb_file_load_ok(f)) return 0;
7813 if (!expanded)
7814 path = copy_path_class(file_expand_path_1(path, 0), path);
7815 return path;
7816 }
7817
7818 long expanded_load_path_maxlen;
7819 VALUE load_path = rb_get_expanded_load_path(&expanded_load_path_maxlen);
7820
7821 if (load_path) {
7822 bool need_expansion = fname_need_expansion_p(path);
7823 VALUE tmp = rb_str_tmp_new(expanded_load_path_maxlen + RSTRING_LEN(path) + 2);
7824 rb_enc_associate_index(tmp, rb_usascii_encindex());
7825 for (long i = 0; i < RARRAY_LEN(load_path); i++) {
7826 VALUE dname = rb_get_path(RARRAY_AREF(load_path, i));
7827 if (!RSTRING_LEN(dname)) continue;
7828 expand_feature(path, dname, tmp, need_expansion);
7829
7830 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
7831 return copy_path_class(tmp, path);
7832 }
7833 }
7834 rb_str_resize(tmp, 0);
7835 }
7836
7837 RB_GC_GUARD(load_path);
7838
7839 return Qfalse; /* no path, no load */
7840}
7841
7842#define define_filetest_function(name, func, argc) do { \
7843 rb_define_module_function(rb_mFileTest, name, func, argc); \
7844 rb_define_singleton_method(rb_cFile, name, func, argc); \
7845} while(false)
7846
7847const char ruby_null_device[] =
7848#if defined DOSISH
7849 "NUL"
7850#elif defined AMIGA || defined __amigaos__
7851 "NIL"
7852#elif defined __VMS
7853 "NL:"
7854#else
7855 "/dev/null"
7856#endif
7857 ;
7858
7859/*
7860 * A \File object is a representation of a file in the underlying platform.
7861 *
7862 * Class \File extends module FileTest, supporting such singleton methods
7863 * as <tt>File.exist?</tt>.
7864 *
7865 * == About the Examples
7866 *
7867 * Many examples here use these variables:
7868 *
7869 * :include: doc/examples/files.rdoc
7870 *
7871 * == Access Modes
7872 *
7873 * Methods File.new and File.open each create a \File object for a given file path.
7874 *
7875 * === \String Access Modes
7876 *
7877 * Methods File.new and File.open each may take string argument +mode+, which:
7878 *
7879 * - Begins with a 1- or 2-character
7880 * {read/write mode}[rdoc-ref:File@ReadWrite+Mode].
7881 * - May also contain a 1-character {data mode}[rdoc-ref:File@Data+Mode].
7882 * - May also contain a 1-character
7883 * {file-create mode}[rdoc-ref:File@File-Create+Mode].
7884 *
7885 * ==== Read/Write Mode
7886 *
7887 * The read/write +mode+ determines:
7888 *
7889 * - Whether the file is to be initially truncated.
7890 *
7891 * - Whether reading is allowed, and if so:
7892 *
7893 * - The initial read position in the file.
7894 * - Where in the file reading can occur.
7895 *
7896 * - Whether writing is allowed, and if so:
7897 *
7898 * - The initial write position in the file.
7899 * - Where in the file writing can occur.
7900 *
7901 * These tables summarize:
7902 *
7903 * Read/Write Modes for Existing File
7904 *
7905 * |------|-----------|----------|----------|----------|-----------|
7906 * | R/W | Initial | | Initial | | Initial |
7907 * | Mode | Truncate? | Read | Read Pos | Write | Write Pos |
7908 * |------|-----------|----------|----------|----------|-----------|
7909 * | 'r' | No | Anywhere | 0 | Error | - |
7910 * | 'w' | Yes | Error | - | Anywhere | 0 |
7911 * | 'a' | No | Error | - | End only | End |
7912 * | 'r+' | No | Anywhere | 0 | Anywhere | 0 |
7913 * | 'w+' | Yes | Anywhere | 0 | Anywhere | 0 |
7914 * | 'a+' | No | Anywhere | End | End only | End |
7915 * |------|-----------|----------|----------|----------|-----------|
7916 *
7917 * Read/Write Modes for \File To Be Created
7918 *
7919 * |------|----------|----------|----------|-----------|
7920 * | R/W | | Initial | | Initial |
7921 * | Mode | Read | Read Pos | Write | Write Pos |
7922 * |------|----------|----------|----------|-----------|
7923 * | 'w' | Error | - | Anywhere | 0 |
7924 * | 'a' | Error | - | End only | 0 |
7925 * | 'w+' | Anywhere | 0 | Anywhere | 0 |
7926 * | 'a+' | Anywhere | 0 | End only | End |
7927 * |------|----------|----------|----------|-----------|
7928 *
7929 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
7930 * for a non-existent file (exception raised).
7931 *
7932 * In the tables:
7933 *
7934 * - +Anywhere+ means that methods IO#rewind, IO#pos=, and IO#seek
7935 * may be used to change the file's position,
7936 * so that allowed reading or writing may occur anywhere in the file.
7937 * - <tt>End only</tt> means that writing can occur only at end-of-file,
7938 * and that methods IO#rewind, IO#pos=, and IO#seek do not affect writing.
7939 * - +Error+ means that an exception is raised if disallowed reading or writing
7940 * is attempted.
7941 *
7942 * ===== Read/Write Modes for Existing \File
7943 *
7944 * - <tt>'r'</tt>:
7945 *
7946 * - \File is not initially truncated:
7947 *
7948 * f = File.new('t.txt') # => #<File:t.txt>
7949 * f.size == 0 # => false
7950 *
7951 * - File's initial read position is 0:
7952 *
7953 * f.pos # => 0
7954 *
7955 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
7956 *
7957 * f.readline # => "First line\n"
7958 * f.readline # => "Second line\n"
7959 *
7960 * f.rewind
7961 * f.readline # => "First line\n"
7962 *
7963 * f.pos = 1
7964 * f.readline # => "irst line\n"
7965 *
7966 * f.seek(1, :CUR)
7967 * f.readline # => "econd line\n"
7968 *
7969 * - Writing is not allowed:
7970 *
7971 * f.write('foo') # Raises IOError.
7972 *
7973 * - <tt>'w'</tt>:
7974 *
7975 * - \File is initially truncated:
7976 *
7977 * path = 't.tmp'
7978 * File.write(path, text)
7979 * f = File.new(path, 'w')
7980 * f.size == 0 # => true
7981 *
7982 * - File's initial write position is 0:
7983 *
7984 * f.pos # => 0
7985 *
7986 * - \File may be written anywhere (even past end-of-file);
7987 * see IO#rewind, IO#pos=, IO#seek:
7988 *
7989 * f.write('foo')
7990 * f.flush
7991 * File.read(path) # => "foo"
7992 * f.pos # => 3
7993 *
7994 * f.write('bar')
7995 * f.flush
7996 * File.read(path) # => "foobar"
7997 * f.pos # => 6
7998 *
7999 * f.rewind
8000 * f.write('baz')
8001 * f.flush
8002 * File.read(path) # => "bazbar"
8003 * f.pos # => 3
8004 *
8005 * f.pos = 3
8006 * f.write('foo')
8007 * f.flush
8008 * File.read(path) # => "bazfoo"
8009 * f.pos # => 6
8010 *
8011 * f.seek(-3, :END)
8012 * f.write('bam')
8013 * f.flush
8014 * File.read(path) # => "bazbam"
8015 * f.pos # => 6
8016 *
8017 * f.pos = 8
8018 * f.write('bah') # Zero padding as needed.
8019 * f.flush
8020 * File.read(path) # => "bazbam\u0000\u0000bah"
8021 * f.pos # => 11
8022 *
8023 * - Reading is not allowed:
8024 *
8025 * f.read # Raises IOError.
8026 *
8027 * - <tt>'a'</tt>:
8028 *
8029 * - \File is not initially truncated:
8030 *
8031 * path = 't.tmp'
8032 * File.write(path, 'foo')
8033 * f = File.new(path, 'a')
8034 * f.size == 0 # => false
8035 *
8036 * - File's initial position is 0 (but is ignored):
8037 *
8038 * f.pos # => 0
8039 *
8040 * - \File may be written only at end-of-file;
8041 * IO#rewind, IO#pos=, IO#seek do not affect writing:
8042 *
8043 * f.write('bar')
8044 * f.flush
8045 * File.read(path) # => "foobar"
8046 * f.write('baz')
8047 * f.flush
8048 * File.read(path) # => "foobarbaz"
8049 *
8050 * f.rewind
8051 * f.write('bat')
8052 * f.flush
8053 * File.read(path) # => "foobarbazbat"
8054 *
8055 * - Reading is not allowed:
8056 *
8057 * f.read # Raises IOError.
8058 *
8059 * - <tt>'r+'</tt>:
8060 *
8061 * - \File is not initially truncated:
8062 *
8063 * path = 't.tmp'
8064 * File.write(path, text)
8065 * f = File.new(path, 'r+')
8066 * f.size == 0 # => false
8067 *
8068 * - File's initial read position is 0:
8069 *
8070 * f.pos # => 0
8071 *
8072 * - \File may be read or written anywhere (even past end-of-file);
8073 * see IO#rewind, IO#pos=, IO#seek:
8074 *
8075 * f.readline # => "First line\n"
8076 * f.readline # => "Second line\n"
8077 *
8078 * f.rewind
8079 * f.readline # => "First line\n"
8080 *
8081 * f.pos = 1
8082 * f.readline # => "irst line\n"
8083 *
8084 * f.seek(1, :CUR)
8085 * f.readline # => "econd line\n"
8086 *
8087 * f.rewind
8088 * f.write('WWW')
8089 * f.flush
8090 * File.read(path)
8091 * # => "WWWst line\nSecond line\nFourth line\nFifth line\n"
8092 *
8093 * f.pos = 10
8094 * f.write('XXX')
8095 * f.flush
8096 * File.read(path)
8097 * # => "WWWst lineXXXecond line\nFourth line\nFifth line\n"
8098 *
8099 * f.seek(-6, :END)
8100 * # => 0
8101 * f.write('YYY')
8102 * # => 3
8103 * f.flush
8104 * # => #<File:t.tmp>
8105 * File.read(path)
8106 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n"
8107 *
8108 * f.seek(2, :END)
8109 * f.write('ZZZ') # Zero padding as needed.
8110 * f.flush
8111 * File.read(path)
8112 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
8113 *
8114 *
8115 * - <tt>'a+'</tt>:
8116 *
8117 * - \File is not initially truncated:
8118 *
8119 * path = 't.tmp'
8120 * File.write(path, 'foo')
8121 * f = File.new(path, 'a+')
8122 * f.size == 0 # => false
8123 *
8124 * - File's initial read position is 0:
8125 *
8126 * f.pos # => 0
8127 *
8128 * - \File may be written only at end-of-file;
8129 * IO#rewind, IO#pos=, IO#seek do not affect writing:
8130 *
8131 * f.write('bar')
8132 * f.flush
8133 * File.read(path) # => "foobar"
8134 * f.write('baz')
8135 * f.flush
8136 * File.read(path) # => "foobarbaz"
8137 *
8138 * f.rewind
8139 * f.write('bat')
8140 * f.flush
8141 * File.read(path) # => "foobarbazbat"
8142 *
8143 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
8144 *
8145 * f.rewind
8146 * f.read # => "foobarbazbat"
8147 *
8148 * f.pos = 3
8149 * f.read # => "barbazbat"
8150 *
8151 * f.seek(-3, :END)
8152 * f.read # => "bat"
8153 *
8154 * ===== Read/Write Modes for \File To Be Created
8155 *
8156 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
8157 * for a non-existent file (exception raised).
8158 *
8159 * - <tt>'w'</tt>:
8160 *
8161 * - File's initial write position is 0:
8162 *
8163 * path = 't.tmp'
8164 * FileUtils.rm_f(path)
8165 * f = File.new(path, 'w')
8166 * f.pos # => 0
8167 *
8168 * - \File may be written anywhere (even past end-of-file);
8169 * see IO#rewind, IO#pos=, IO#seek:
8170 *
8171 * f.write('foo')
8172 * f.flush
8173 * File.read(path) # => "foo"
8174 * f.pos # => 3
8175 *
8176 * f.write('bar')
8177 * f.flush
8178 * File.read(path) # => "foobar"
8179 * f.pos # => 6
8180 *
8181 * f.rewind
8182 * f.write('baz')
8183 * f.flush
8184 * File.read(path) # => "bazbar"
8185 * f.pos # => 3
8186 *
8187 * f.pos = 3
8188 * f.write('foo')
8189 * f.flush
8190 * File.read(path) # => "bazfoo"
8191 * f.pos # => 6
8192 *
8193 * f.seek(-3, :END)
8194 * f.write('bam')
8195 * f.flush
8196 * File.read(path) # => "bazbam"
8197 * f.pos # => 6
8198 *
8199 * f.pos = 8
8200 * f.write('bah') # Zero padding as needed.
8201 * f.flush
8202 * File.read(path) # => "bazbam\u0000\u0000bah"
8203 * f.pos # => 11
8204 *
8205 * - Reading is not allowed:
8206 *
8207 * f.read # Raises IOError.
8208 *
8209 * - <tt>'a'</tt>:
8210 *
8211 * - File's initial write position is 0:
8212 *
8213 * path = 't.tmp'
8214 * FileUtils.rm_f(path)
8215 * f = File.new(path, 'a')
8216 * f.pos # => 0
8217 *
8218 * - Writing occurs only at end-of-file:
8219 *
8220 * f.write('foo')
8221 * f.pos # => 3
8222 * f.write('bar')
8223 * f.pos # => 6
8224 * f.flush
8225 * File.read(path) # => "foobar"
8226 *
8227 * f.rewind
8228 * f.write('baz')
8229 * f.flush
8230 * File.read(path) # => "foobarbaz"
8231 *
8232 * - Reading is not allowed:
8233 *
8234 * f.read # Raises IOError.
8235 *
8236 * - <tt>'w+'</tt>:
8237 *
8238 * - File's initial position is 0:
8239 *
8240 * path = 't.tmp'
8241 * FileUtils.rm_f(path)
8242 * f = File.new(path, 'w+')
8243 * f.pos # => 0
8244 *
8245 * - \File may be written anywhere (even past end-of-file);
8246 * see IO#rewind, IO#pos=, IO#seek:
8247 *
8248 * f.write('foo')
8249 * f.flush
8250 * File.read(path) # => "foo"
8251 * f.pos # => 3
8252 *
8253 * f.write('bar')
8254 * f.flush
8255 * File.read(path) # => "foobar"
8256 * f.pos # => 6
8257 *
8258 * f.rewind
8259 * f.write('baz')
8260 * f.flush
8261 * File.read(path) # => "bazbar"
8262 * f.pos # => 3
8263 *
8264 * f.pos = 3
8265 * f.write('foo')
8266 * f.flush
8267 * File.read(path) # => "bazfoo"
8268 * f.pos # => 6
8269 *
8270 * f.seek(-3, :END)
8271 * f.write('bam')
8272 * f.flush
8273 * File.read(path) # => "bazbam"
8274 * f.pos # => 6
8275 *
8276 * f.pos = 8
8277 * f.write('bah') # Zero padding as needed.
8278 * f.flush
8279 * File.read(path) # => "bazbam\u0000\u0000bah"
8280 * f.pos # => 11
8281 *
8282 * - \File may be read anywhere (even past end-of-file);
8283 * see IO#rewind, IO#pos=, IO#seek:
8284 *
8285 * f.rewind
8286 * # => 0
8287 * f.read
8288 * # => "bazbam\u0000\u0000bah"
8289 *
8290 * f.pos = 3
8291 * # => 3
8292 * f.read
8293 * # => "bam\u0000\u0000bah"
8294 *
8295 * f.seek(-3, :END)
8296 * # => 0
8297 * f.read
8298 * # => "bah"
8299 *
8300 * - <tt>'a+'</tt>:
8301 *
8302 * - File's initial write position is 0:
8303 *
8304 * path = 't.tmp'
8305 * FileUtils.rm_f(path)
8306 * f = File.new(path, 'a+')
8307 * f.pos # => 0
8308 *
8309 * - Writing occurs only at end-of-file:
8310 *
8311 * f.write('foo')
8312 * f.pos # => 3
8313 * f.write('bar')
8314 * f.pos # => 6
8315 * f.flush
8316 * File.read(path) # => "foobar"
8317 *
8318 * f.rewind
8319 * f.write('baz')
8320 * f.flush
8321 * File.read(path) # => "foobarbaz"
8322 *
8323 * - \File may be read anywhere (even past end-of-file);
8324 * see IO#rewind, IO#pos=, IO#seek:
8325 *
8326 * f.rewind
8327 * f.read # => "foobarbaz"
8328 *
8329 * f.pos = 3
8330 * f.read # => "barbaz"
8331 *
8332 * f.seek(-3, :END)
8333 * f.read # => "baz"
8334 *
8335 * f.pos = 800
8336 * f.read # => ""
8337 *
8338 * ==== \Data Mode
8339 *
8340 * To specify whether data is to be treated as text or as binary data,
8341 * either of the following may be suffixed to any of the string read/write modes
8342 * above:
8343 *
8344 * - <tt>'t'</tt>: Text data; sets the default external encoding
8345 * to <tt>Encoding::UTF_8</tt>;
8346 * on Windows, enables conversion between EOL and CRLF
8347 * and enables interpreting <tt>0x1A</tt> as an end-of-file marker.
8348 * - <tt>'b'</tt>: Binary data; sets the default external encoding
8349 * to <tt>Encoding::ASCII_8BIT</tt>;
8350 * on Windows, suppresses conversion between EOL and CRLF
8351 * and disables interpreting <tt>0x1A</tt> as an end-of-file marker.
8352 *
8353 * If neither is given, the stream defaults to text data.
8354 *
8355 * Examples:
8356 *
8357 * File.new('t.txt', 'rt')
8358 * File.new('t.dat', 'rb')
8359 *
8360 * When the data mode is specified, the read/write mode may not be omitted,
8361 * and the data mode must precede the file-create mode, if given:
8362 *
8363 * File.new('t.dat', 'b') # Raises an exception.
8364 * File.new('t.dat', 'rxb') # Raises an exception.
8365 *
8366 * ==== \File-Create Mode
8367 *
8368 * The following may be suffixed to any writable string mode above:
8369 *
8370 * - <tt>'x'</tt>: Creates the file if it does not exist;
8371 * raises an exception if the file exists.
8372 *
8373 * Example:
8374 *
8375 * File.new('t.tmp', 'wx')
8376 *
8377 * When the file-create mode is specified, the read/write mode may not be omitted,
8378 * and the file-create mode must follow the data mode:
8379 *
8380 * File.new('t.dat', 'x') # Raises an exception.
8381 * File.new('t.dat', 'rxb') # Raises an exception.
8382 *
8383 * === \Integer Access Modes
8384 *
8385 * When mode is an integer it must be one or more of the following constants,
8386 * which may be combined by the bitwise OR operator <tt>|</tt>:
8387 *
8388 * - +File::RDONLY+: Open for reading only.
8389 * - +File::WRONLY+: Open for writing only.
8390 * - +File::RDWR+: Open for reading and writing.
8391 * - +File::APPEND+: Open for appending only.
8392 *
8393 * Examples:
8394 *
8395 * File.new('t.txt', File::RDONLY)
8396 * File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
8397 *
8398 * Note: Method IO#set_encoding does not allow the mode to be specified as an integer.
8399 *
8400 * === File-Create Mode Specified as an \Integer
8401 *
8402 * These constants may also be ORed into the integer mode:
8403 *
8404 * - +File::CREAT+: Create file if it does not exist.
8405 * - +File::EXCL+: Raise an exception if +File::CREAT+ is given and the file exists.
8406 *
8407 * === \Data Mode Specified as an \Integer
8408 *
8409 * \Data mode cannot be specified as an integer.
8410 * When the stream access mode is given as an integer,
8411 * the data mode is always text, never binary.
8412 *
8413 * Note that although there is a constant +File::BINARY+,
8414 * setting its value in an integer stream mode has no effect;
8415 * this is because, as documented in File::Constants,
8416 * the +File::BINARY+ value disables line code conversion,
8417 * but does not change the external encoding.
8418 *
8419 * === Encodings
8420 *
8421 * Any of the string modes above may specify encodings -
8422 * either external encoding only or both external and internal encodings -
8423 * by appending one or both encoding names, separated by colons:
8424 *
8425 * f = File.new('t.dat', 'rb')
8426 * f.external_encoding # => #<Encoding:ASCII-8BIT>
8427 * f.internal_encoding # => nil
8428 * f = File.new('t.dat', 'rb:UTF-16')
8429 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
8430 * f.internal_encoding # => nil
8431 * f = File.new('t.dat', 'rb:UTF-16:UTF-16')
8432 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
8433 * f.internal_encoding # => #<Encoding:UTF-16>
8434 * f.close
8435 *
8436 * The numerous encoding names are available in array Encoding.name_list:
8437 *
8438 * Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
8439 *
8440 * When the external encoding is set, strings read are tagged by that encoding
8441 * when reading, and strings written are converted to that encoding when
8442 * writing.
8443 *
8444 * When both external and internal encodings are set,
8445 * strings read are converted from external to internal encoding,
8446 * and strings written are converted from internal to external encoding.
8447 * For further details about transcoding input and output,
8448 * see {Encodings}[rdoc-ref:encodings.rdoc@Encodings].
8449 *
8450 * If the external encoding is <tt>'BOM|UTF-8'</tt>, <tt>'BOM|UTF-16LE'</tt>
8451 * or <tt>'BOM|UTF16-BE'</tt>,
8452 * Ruby checks for a Unicode BOM in the input document
8453 * to help determine the encoding.
8454 * For UTF-16 encodings the file open mode must be binary.
8455 * If the BOM is found,
8456 * it is stripped and the external encoding from the BOM is used.
8457 *
8458 * Note that the BOM-style encoding option is case insensitive,
8459 * so <tt>'bom|utf-8'</tt> is also valid.
8460 *
8461 * == \File Permissions
8462 *
8463 * A \File object has _permissions_, an octal integer representing
8464 * the permissions of an actual file in the underlying platform.
8465 *
8466 * Note that file permissions are quite different from the _mode_
8467 * of a file stream (\File object).
8468 *
8469 * In a \File object, the permissions are available thus,
8470 * where method +mode+, despite its name, returns permissions:
8471 *
8472 * f = File.new('t.txt')
8473 * f.lstat.mode.to_s(8) # => "100644"
8474 *
8475 * On a Unix-based operating system,
8476 * the three low-order octal digits represent the permissions
8477 * for owner (6), group (4), and world (4).
8478 * The triplet of bits in each octal digit represent, respectively,
8479 * read, write, and execute permissions.
8480 *
8481 * Permissions <tt>0644</tt> thus represent read-write access for owner
8482 * and read-only access for group and world.
8483 * See man pages {open(2)}[https://www.unix.com/man-page/bsd/2/open]
8484 * and {chmod(2)}[https://www.unix.com/man-page/bsd/2/chmod].
8485 *
8486 * For a directory, the meaning of the execute bit changes:
8487 * when set, the directory can be searched.
8488 *
8489 * Higher-order bits in permissions may indicate the type of file
8490 * (plain, directory, pipe, socket, etc.) and various other special features.
8491 *
8492 * On non-Posix operating systems, permissions may include only read-only or
8493 * read-write, in which case, the remaining permission will resemble typical
8494 * values. On Windows, for instance, the default permissions are +0644+; The
8495 * only change that can be made is to make the file read-only, which is
8496 * reported as +0444+.
8497 *
8498 * For a method that actually creates a file in the underlying platform
8499 * (as opposed to merely creating a \File object),
8500 * permissions may be specified:
8501 *
8502 * File.new('t.tmp', File::CREAT, 0644)
8503 * File.new('t.tmp', File::CREAT, 0444)
8504 *
8505 * Permissions may also be changed:
8506 *
8507 * f = File.new('t.tmp', File::CREAT, 0444)
8508 * f.chmod(0644)
8509 * f.chmod(0444)
8510 *
8511 * == \File \Constants
8512 *
8513 * Various constants for use in \File and IO methods
8514 * may be found in module File::Constants;
8515 * an array of their names is returned by <tt>File::Constants.constants</tt>.
8516 *
8517 * == What's Here
8518 *
8519 * First, what's elsewhere. Class \File:
8520 *
8521 * - Inherits from {class IO}[rdoc-ref:IO@Whats+Here],
8522 * in particular, methods for creating, reading, and writing files
8523 * - Includes module FileTest,
8524 * which provides dozens of additional methods.
8525 *
8526 * Here, class \File provides methods that are useful for:
8527 *
8528 * - {Creating}[rdoc-ref:File@Creating]
8529 * - {Querying}[rdoc-ref:File@Querying]
8530 * - {Settings}[rdoc-ref:File@Settings]
8531 * - {Other}[rdoc-ref:File@Other]
8532 *
8533 * === Creating
8534 *
8535 * - ::new: Opens the file at the given path; returns the file.
8536 * - ::open: Same as ::new, but when given a block will yield the file to the block,
8537 * and close the file upon exiting the block.
8538 * - ::link: Creates a new name for an existing file using a hard link.
8539 * - ::mkfifo: Returns the FIFO file created at the given path.
8540 * - ::symlink: Creates a symbolic link for the given file path.
8541 *
8542 * === Querying
8543 *
8544 * _Paths_
8545 *
8546 * - ::absolute_path: Returns the absolute file path for the given path.
8547 * - ::absolute_path?: Returns whether the given path is the absolute file path.
8548 * - ::basename: Returns the last component of the given file path.
8549 * - ::dirname: Returns all but the last component of the given file path.
8550 * - ::expand_path: Returns the absolute file path for the given path,
8551 * expanding <tt>~</tt> for a home directory.
8552 * - ::extname: Returns the file extension for the given file path.
8553 * - ::fnmatch? (aliased as ::fnmatch): Returns whether the given file path
8554 * matches the given pattern.
8555 * - ::join: Joins path components into a single path string.
8556 * - ::path: Returns the string representation of the given path.
8557 * - ::readlink: Returns the path to the file at the given symbolic link.
8558 * - ::realdirpath: Returns the real path for the given file path,
8559 * where the last component need not exist.
8560 * - ::realpath: Returns the real path for the given file path,
8561 * where all components must exist.
8562 * - ::split: Returns an array of two strings: the directory name and basename
8563 * of the file at the given path.
8564 * - #path (aliased as #to_path): Returns the string representation of the given path.
8565 *
8566 * _Times_
8567 *
8568 * - ::atime: Returns a Time for the most recent access to the given file.
8569 * - ::birthtime: Returns a Time for the creation of the given file.
8570 * - ::ctime: Returns a Time for the metadata change of the given file.
8571 * - ::mtime: Returns a Time for the most recent data modification to
8572 * the content of the given file.
8573 * - #atime: Returns a Time for the most recent access to +self+.
8574 * - #birthtime: Returns a Time the creation for +self+.
8575 * - #ctime: Returns a Time for the metadata change of +self+.
8576 * - #mtime: Returns a Time for the most recent data modification
8577 * to the content of +self+.
8578 *
8579 * _Types_
8580 *
8581 * - ::blockdev?: Returns whether the file at the given path is a block device.
8582 * - ::chardev?: Returns whether the file at the given path is a character device.
8583 * - ::directory?: Returns whether the file at the given path is a directory.
8584 * - ::executable?: Returns whether the file at the given path is executable
8585 * by the effective user and group of the current process.
8586 * - ::executable_real?: Returns whether the file at the given path is executable
8587 * by the real user and group of the current process.
8588 * - ::exist?: Returns whether the file at the given path exists.
8589 * - ::file?: Returns whether the file at the given path is a regular file.
8590 * - ::ftype: Returns a string giving the type of the file at the given path.
8591 * - ::grpowned?: Returns whether the effective group of the current process
8592 * owns the file at the given path.
8593 * - ::identical?: Returns whether the files at two given paths are identical.
8594 * - ::lstat: Returns the File::Stat object for the last symbolic link
8595 * in the given path.
8596 * - ::owned?: Returns whether the effective user of the current process
8597 * owns the file at the given path.
8598 * - ::pipe?: Returns whether the file at the given path is a pipe.
8599 * - ::readable?: Returns whether the file at the given path is readable
8600 * by the effective user and group of the current process.
8601 * - ::readable_real?: Returns whether the file at the given path is readable
8602 * by the real user and group of the current process.
8603 * - ::setgid?: Returns whether the setgid bit is set for the file at the given path.
8604 * - ::setuid?: Returns whether the setuid bit is set for the file at the given path.
8605 * - ::socket?: Returns whether the file at the given path is a socket.
8606 * - ::stat: Returns the File::Stat object for the file at the given path.
8607 * - ::sticky?: Returns whether the file at the given path has its sticky bit set.
8608 * - ::symlink?: Returns whether the file at the given path is a symbolic link.
8609 * - ::umask: Returns the umask value for the current process.
8610 * - ::world_readable?: Returns whether the file at the given path is readable
8611 * by others.
8612 * - ::world_writable?: Returns whether the file at the given path is writable
8613 * by others.
8614 * - ::writable?: Returns whether the file at the given path is writable
8615 * by the effective user and group of the current process.
8616 * - ::writable_real?: Returns whether the file at the given path is writable
8617 * by the real user and group of the current process.
8618 * - #lstat: Returns the File::Stat object for the last symbolic link
8619 * in the path for +self+.
8620 *
8621 * _Contents_
8622 *
8623 * - ::empty? (aliased as ::zero?): Returns whether the file at the given path
8624 * exists and is empty.
8625 * - ::size: Returns the size (bytes) of the file at the given path.
8626 * - ::size?: Returns +nil+ if there is no file at the given path,
8627 * or if that file is empty; otherwise returns the file size (bytes).
8628 * - #size: Returns the size (bytes) of +self+.
8629 *
8630 * === Settings
8631 *
8632 * - ::chmod: Changes permissions of the file at the given path.
8633 * - ::chown: Change ownership of the file at the given path.
8634 * - ::lchmod: Changes permissions of the last symbolic link in the given path.
8635 * - ::lchown: Change ownership of the last symbolic in the given path.
8636 * - ::lutime: For each given file path, sets the access time and modification time
8637 * of the last symbolic link in the path.
8638 * - ::rename: Moves the file at one given path to another given path.
8639 * - ::utime: Sets the access time and modification time of each file
8640 * at the given paths.
8641 * - #flock: Locks or unlocks +self+.
8642 *
8643 * === Other
8644 *
8645 * - ::truncate: Truncates the file at the given file path to the given size.
8646 * - ::unlink (aliased as ::delete): Deletes the file for each given file path.
8647 * - #truncate: Truncates +self+ to the given size.
8648 *
8649 */
8650
8651void
8652Init_File(void)
8653{
8654#if defined(__APPLE__) && defined(HAVE_WORKING_FORK)
8655 rb_CFString_class_initialize_before_fork();
8656#endif
8657
8658 VALUE separator;
8659
8660 rb_mFileTest = rb_define_module("FileTest");
8661 rb_cFile = rb_define_class("File", rb_cIO);
8662
8663 define_filetest_function("directory?", rb_file_directory_p, 1);
8664 define_filetest_function("exist?", rb_file_exist_p, 1);
8665 define_filetest_function("readable?", rb_file_readable_p, 1);
8666 define_filetest_function("readable_real?", rb_file_readable_real_p, 1);
8667 define_filetest_function("world_readable?", rb_file_world_readable_p, 1);
8668 define_filetest_function("writable?", rb_file_writable_p, 1);
8669 define_filetest_function("writable_real?", rb_file_writable_real_p, 1);
8670 define_filetest_function("world_writable?", rb_file_world_writable_p, 1);
8671 define_filetest_function("executable?", rb_file_executable_p, 1);
8672 define_filetest_function("executable_real?", rb_file_executable_real_p, 1);
8673 define_filetest_function("file?", rb_file_file_p, 1);
8674 define_filetest_function("zero?", rb_file_zero_p, 1);
8675 define_filetest_function("empty?", rb_file_zero_p, 1);
8676 define_filetest_function("size?", rb_file_size_p, 1);
8677 define_filetest_function("size", rb_file_s_size, 1);
8678 define_filetest_function("owned?", rb_file_owned_p, 1);
8679 define_filetest_function("grpowned?", rb_file_grpowned_p, 1);
8680
8681 define_filetest_function("pipe?", rb_file_pipe_p, 1);
8682 define_filetest_function("symlink?", rb_file_symlink_p, 1);
8683 define_filetest_function("socket?", rb_file_socket_p, 1);
8684
8685 define_filetest_function("blockdev?", rb_file_blockdev_p, 1);
8686 define_filetest_function("chardev?", rb_file_chardev_p, 1);
8687
8688 define_filetest_function("setuid?", rb_file_suid_p, 1);
8689 define_filetest_function("setgid?", rb_file_sgid_p, 1);
8690 define_filetest_function("sticky?", rb_file_sticky_p, 1);
8691
8692 define_filetest_function("identical?", rb_file_identical_p, 2);
8693
8694 rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
8695 rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
8696 rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
8697
8698 rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
8699 rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
8700 rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
8701 rb_define_singleton_method(rb_cFile, "birthtime", rb_file_s_birthtime, 1);
8702
8703 rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
8704 rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
8705 rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
8706 rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
8707 rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
8708 rb_define_singleton_method(rb_cFile, "lutime", rb_file_s_lutime, -1);
8709
8710 rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
8711 rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
8712 rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
8713
8714 rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -1);
8715 rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -1);
8716 rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
8717 rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
8718 rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
8719 rb_define_singleton_method(rb_cFile, "mkfifo", rb_file_s_mkfifo, -1);
8720 rb_define_singleton_method(rb_cFile, "expand_path", s_expand_path, -1);
8721 rb_define_singleton_method(rb_cFile, "absolute_path", s_absolute_path, -1);
8722 rb_define_singleton_method(rb_cFile, "absolute_path?", s_absolute_path_p, 1);
8723 rb_define_singleton_method(rb_cFile, "realpath", rb_file_s_realpath, -1);
8724 rb_define_singleton_method(rb_cFile, "realdirpath", rb_file_s_realdirpath, -1);
8725 rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
8726 rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, -1);
8727 rb_define_singleton_method(rb_cFile, "extname", rb_file_s_extname, 1);
8728 rb_define_singleton_method(rb_cFile, "path", rb_file_s_path, 1);
8729
8730 separator = rb_fstring_lit("/");
8731 /* separates directory parts in path */
8732 rb_define_const(rb_cFile, "Separator", separator);
8733 /* separates directory parts in path */
8734 rb_define_const(rb_cFile, "SEPARATOR", separator);
8735 rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
8736 rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -1);
8737
8738#ifdef DOSISH
8739 /* platform specific alternative separator */
8740 rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator)));
8741#else
8742 rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
8743#endif
8744 /* path list separator */
8745 rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP));
8746
8747 rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
8748 rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
8749
8750 rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
8751 rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
8752 rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
8753 rb_define_method(rb_cFile, "birthtime", rb_file_birthtime, 0);
8754 rb_define_method(rb_cFile, "size", file_size, 0);
8755
8756 rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
8757 rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
8758 rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
8759
8760 rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
8761
8762 /*
8763 * Document-module: File::Constants
8764 *
8765 * Module +File::Constants+ defines file-related constants.
8766 *
8767 * There are two families of constants here:
8768 *
8769 * - Those having to do with {file access}[rdoc-ref:File::Constants@File+Access].
8770 * - Those having to do with {filename globbing}[rdoc-ref:File::Constants@Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29].
8771 *
8772 * \File constants defined for the local process may be retrieved
8773 * with method File::Constants.constants:
8774 *
8775 * File::Constants.constants.take(5)
8776 * # => [:RDONLY, :WRONLY, :RDWR, :APPEND, :CREAT]
8777 *
8778 * == \File Access
8779 *
8780 * \File-access constants may be used with optional argument +mode+ in calls
8781 * to the following methods:
8782 *
8783 * - File.new.
8784 * - File.open.
8785 * - IO.for_fd.
8786 * - IO.new.
8787 * - IO.open.
8788 * - IO.popen.
8789 * - IO.reopen.
8790 * - IO.sysopen.
8791 * - StringIO.new.
8792 * - StringIO.open.
8793 * - StringIO#reopen.
8794 *
8795 * === Read/Write Access
8796 *
8797 * Read-write access for a stream
8798 * may be specified by a file-access constant.
8799 *
8800 * The constant may be specified as part of a bitwise OR of other such constants.
8801 *
8802 * Any combination of the constants in this section may be specified.
8803 *
8804 * ==== File::RDONLY
8805 *
8806 * Flag File::RDONLY specifies the stream should be opened for reading only:
8807 *
8808 * filepath = '/tmp/t.tmp'
8809 * f = File.new(filepath, File::RDONLY)
8810 * f.write('Foo') # Raises IOError (not opened for writing).
8811 *
8812 * ==== File::WRONLY
8813 *
8814 * Flag File::WRONLY specifies that the stream should be opened for writing only:
8815 *
8816 * f = File.new(filepath, File::WRONLY)
8817 * f.read # Raises IOError (not opened for reading).
8818 *
8819 * ==== File::RDWR
8820 *
8821 * Flag File::RDWR specifies that the stream should be opened
8822 * for both reading and writing:
8823 *
8824 * f = File.new(filepath, File::RDWR)
8825 * f.write('Foo') # => 3
8826 * f.rewind # => 0
8827 * f.read # => "Foo"
8828 *
8829 * === \File Positioning
8830 *
8831 * ==== File::APPEND
8832 *
8833 * Flag File::APPEND specifies that the stream should be opened
8834 * in append mode.
8835 *
8836 * Before each write operation, the position is set to end-of-stream.
8837 * The modification of the position and the following write operation
8838 * are performed as a single atomic step.
8839 *
8840 * ==== File::TRUNC
8841 *
8842 * Flag File::TRUNC specifies that the stream should be truncated
8843 * at its beginning.
8844 * If the file exists and is successfully opened for writing,
8845 * it is to be truncated to position zero;
8846 * its ctime and mtime are updated.
8847 *
8848 * There is no effect on a FIFO special file or a terminal device.
8849 * The effect on other file types is implementation-defined.
8850 * The result of using File::TRUNC with File::RDONLY is undefined.
8851 *
8852 * === Creating and Preserving
8853 *
8854 * ==== File::CREAT
8855 *
8856 * Flag File::CREAT specifies that the stream should be created
8857 * if it does not already exist.
8858 *
8859 * If the file exists:
8860 *
8861 * - Raise an exception if File::EXCL is also specified.
8862 * - Otherwise, do nothing.
8863 *
8864 * If the file does not exist, then it is created.
8865 * Upon successful completion, the atime, ctime, and mtime of the file are updated,
8866 * and the ctime and mtime of the parent directory are updated.
8867 *
8868 * ==== File::EXCL
8869 *
8870 * Flag File::EXCL specifies that the stream should not already exist;
8871 * If flags File::CREAT and File::EXCL are both specified
8872 * and the stream already exists, an exception is raised.
8873 *
8874 * The check for the existence and creation of the file is performed as an
8875 * atomic operation.
8876 *
8877 * If both File::EXCL and File::CREAT are specified and the path names a symbolic link,
8878 * an exception is raised regardless of the contents of the symbolic link.
8879 *
8880 * If File::EXCL is specified and File::CREAT is not specified,
8881 * the result is undefined.
8882 *
8883 * === POSIX \File \Constants
8884 *
8885 * Some file-access constants are defined only on POSIX-compliant systems;
8886 * those are:
8887 *
8888 * - File::SYNC.
8889 * - File::DSYNC.
8890 * - File::RSYNC.
8891 * - File::DIRECT.
8892 * - File::NOATIME.
8893 * - File::NOCTTY.
8894 * - File::NOFOLLOW.
8895 * - File::TMPFILE.
8896 *
8897 * ==== File::SYNC, File::RSYNC, and File::DSYNC
8898 *
8899 * Flag File::SYNC, File::RSYNC, or File::DSYNC
8900 * specifies synchronization of I/O operations with the underlying file system.
8901 *
8902 * These flags are valid only for POSIX-compliant systems.
8903 *
8904 * - File::SYNC specifies that all write operations (both data and metadata)
8905 * are immediately to be flushed to the underlying storage device.
8906 * This means that the data is written to the storage device,
8907 * and the file's metadata (e.g., file size, timestamps, permissions)
8908 * are also synchronized.
8909 * This guarantees that data is safely stored on the storage medium
8910 * before returning control to the calling program.
8911 * This flag can have a significant impact on performance
8912 * since it requires synchronous writes, which can be slower
8913 * compared to asynchronous writes.
8914 *
8915 * - File::RSYNC specifies that any read operations on the file will not return
8916 * until all outstanding write operations
8917 * (those that have been issued but not completed) are also synchronized.
8918 * This is useful when you want to read the most up-to-date data,
8919 * which may still be in the process of being written.
8920 *
8921 * - File::DSYNC specifies that all _data_ write operations
8922 * are immediately to be flushed to the underlying storage device;
8923 * this differs from File::SYNC, which requires that _metadata_
8924 * also be synchronized.
8925 *
8926 * Note that the behavior of these flags may vary slightly
8927 * depending on the operating system and filesystem being used.
8928 * Additionally, using these flags can have an impact on performance
8929 * due to the synchronous nature of the I/O operations,
8930 * so they should be used judiciously,
8931 * especially in performance-critical applications.
8932 *
8933 * ==== File::NOCTTY
8934 *
8935 * Flag File::NOCTTY specifies that if the stream is a terminal device,
8936 * that device does not become the controlling terminal for the process.
8937 *
8938 * Defined only for POSIX-compliant systems.
8939 *
8940 * ==== File::DIRECT
8941 *
8942 * Flag File::DIRECT requests that cache effects of the I/O to and from the stream
8943 * be minimized.
8944 *
8945 * Defined only for POSIX-compliant systems.
8946 *
8947 * ==== File::NOATIME
8948 *
8949 * Flag File::NOATIME specifies that act of opening the stream
8950 * should not modify its access time (atime).
8951 *
8952 * Defined only for POSIX-compliant systems.
8953 *
8954 * ==== File::NOFOLLOW
8955 *
8956 * Flag File::NOFOLLOW specifies that if path is a symbolic link,
8957 * it should not be followed.
8958 *
8959 * Defined only for POSIX-compliant systems.
8960 *
8961 * ==== File::TMPFILE
8962 *
8963 * Flag File::TMPFILE specifies that the opened stream
8964 * should be a new temporary file.
8965 *
8966 * Defined only for POSIX-compliant systems.
8967 *
8968 * === Other File-Access \Constants
8969 *
8970 * ==== File::NONBLOCK
8971 *
8972 * When possible, the file is opened in nonblocking mode.
8973 * Neither the open operation nor any subsequent I/O operations on
8974 * the file will cause the calling process to wait.
8975 *
8976 * ==== File::BINARY
8977 *
8978 * Flag File::BINARY specifies that the stream is to be accessed in binary mode.
8979 *
8980 * ==== File::SHARE_DELETE
8981 *
8982 * Flag File::SHARE_DELETE enables other processes to open the stream
8983 * with delete access.
8984 *
8985 * Windows only.
8986 *
8987 * If the stream is opened for (local) delete access without File::SHARE_DELETE,
8988 * and another process attempts to open it with delete access,
8989 * the attempt fails and the stream is not opened for that process.
8990 *
8991 * == Locking
8992 *
8993 * Four file constants relate to stream locking;
8994 * see File#flock:
8995 *
8996 * ==== File::LOCK_EX
8997 *
8998 * Flag File::LOCK_EX specifies an exclusive lock;
8999 * only one process a a time may lock the stream.
9000 *
9001 * ==== File::LOCK_NB
9002 *
9003 * Flag File::LOCK_NB specifies non-blocking locking for the stream;
9004 * may be combined with File::LOCK_EX or File::LOCK_SH.
9005 *
9006 * ==== File::LOCK_SH
9007 *
9008 * Flag File::LOCK_SH specifies that multiple processes may lock
9009 * the stream at the same time.
9010 *
9011 * ==== File::LOCK_UN
9012 *
9013 * Flag File::LOCK_UN specifies that the stream is not to be locked.
9014 *
9015 * == Filename Globbing \Constants (File::FNM_*)
9016 *
9017 * Filename-globbing constants may be used with optional argument +flags+
9018 * in calls to the following methods:
9019 *
9020 * - Dir.glob.
9021 * - File.fnmatch.
9022 * - Pathname#fnmatch.
9023 * - Pathname.glob.
9024 * - Pathname#glob.
9025 *
9026 * The constants are:
9027 *
9028 * ==== File::FNM_CASEFOLD
9029 *
9030 * Flag File::FNM_CASEFOLD makes patterns case insensitive
9031 * for File.fnmatch (but not Dir.glob).
9032 *
9033 * ==== File::FNM_DOTMATCH
9034 *
9035 * Flag File::FNM_DOTMATCH makes the <tt>'*'</tt> pattern
9036 * match a filename starting with <tt>'.'</tt>.
9037 *
9038 * ==== File::FNM_EXTGLOB
9039 *
9040 * Flag File::FNM_EXTGLOB enables pattern <tt>'{a,b}'</tt>,
9041 * which matches pattern '_a_' and pattern '_b_';
9042 * behaves like
9043 * a {regexp union}[rdoc-ref:Regexp.union]
9044 * (e.g., <tt>'(?:a|b)'</tt>):
9045 *
9046 * pattern = '{LEGAL,BSDL}'
9047 * Dir.glob(pattern) # => ["LEGAL", "BSDL"]
9048 * Pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
9049 * pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
9050 *
9051 * ==== File::FNM_NOESCAPE
9052 *
9053 * Flag File::FNM_NOESCAPE disables <tt>'\'</tt> escaping.
9054 *
9055 * ==== File::FNM_PATHNAME
9056 *
9057 * Flag File::FNM_PATHNAME specifies that patterns <tt>'*'</tt> and <tt>'?'</tt>
9058 * do not match the directory separator
9059 * (the value of constant File::SEPARATOR).
9060 *
9061 * ==== File::FNM_SHORTNAME
9062 *
9063 * Flag File::FNM_SHORTNAME allows patterns to match short names if they exist.
9064 *
9065 * Windows only.
9066 *
9067 * ==== File::FNM_SYSCASE
9068 *
9069 * Flag File::FNM_SYSCASE specifies that case sensitivity
9070 * is the same as in the underlying operating system;
9071 * effective for File.fnmatch, but not Dir.glob.
9072 *
9073 * == Other \Constants
9074 *
9075 * ==== File::NULL
9076 *
9077 * Flag File::NULL contains the string value of the null device:
9078 *
9079 * - On a Unix-like OS, <tt>'/dev/null'</tt>.
9080 * - On Windows, <tt>'NUL'</tt>.
9081 *
9082 */
9083 rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
9084 rb_include_module(rb_cIO, rb_mFConst);
9085 /* {File::RDONLY}[rdoc-ref:File::Constants@File-3A-3ARDONLY] */
9086 rb_define_const(rb_mFConst, "RDONLY", INT2FIX(O_RDONLY));
9087 /* {File::WRONLY}[rdoc-ref:File::Constants@File-3A-3AWRONLY] */
9088 rb_define_const(rb_mFConst, "WRONLY", INT2FIX(O_WRONLY));
9089 /* {File::RDWR}[rdoc-ref:File::Constants@File-3A-3ARDWR] */
9090 rb_define_const(rb_mFConst, "RDWR", INT2FIX(O_RDWR));
9091 /* {File::APPEND}[rdoc-ref:File::Constants@File-3A-3AAPPEND] */
9092 rb_define_const(rb_mFConst, "APPEND", INT2FIX(O_APPEND));
9093 /* {File::CREAT}[rdoc-ref:File::Constants@File-3A-3ACREAT] */
9094 rb_define_const(rb_mFConst, "CREAT", INT2FIX(O_CREAT));
9095 /* {File::EXCL}[rdoc-ref:File::Constants@File-3A-3AEXCL] */
9096 rb_define_const(rb_mFConst, "EXCL", INT2FIX(O_EXCL));
9097#if defined(O_NDELAY) || defined(O_NONBLOCK)
9098# ifndef O_NONBLOCK
9099# define O_NONBLOCK O_NDELAY
9100# endif
9101 /* {File::NONBLOCK}[rdoc-ref:File::Constants@File-3A-3ANONBLOCK] */
9102 rb_define_const(rb_mFConst, "NONBLOCK", INT2FIX(O_NONBLOCK));
9103#endif
9104 /* {File::TRUNC}[rdoc-ref:File::Constants@File-3A-3ATRUNC] */
9105 rb_define_const(rb_mFConst, "TRUNC", INT2FIX(O_TRUNC));
9106#ifdef O_NOCTTY
9107 /* {File::NOCTTY}[rdoc-ref:File::Constants@File-3A-3ANOCTTY] */
9108 rb_define_const(rb_mFConst, "NOCTTY", INT2FIX(O_NOCTTY));
9109#endif
9110#ifndef O_BINARY
9111# define O_BINARY 0
9112#endif
9113 /* {File::BINARY}[rdoc-ref:File::Constants@File-3A-3ABINARY] */
9114 rb_define_const(rb_mFConst, "BINARY", INT2FIX(O_BINARY));
9115#ifndef O_SHARE_DELETE
9116# define O_SHARE_DELETE 0
9117#endif
9118 /* {File::SHARE_DELETE}[rdoc-ref:File::Constants@File-3A-3ASHARE_DELETE] */
9119 rb_define_const(rb_mFConst, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE));
9120#ifdef O_SYNC
9121 /* {File::SYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
9122 rb_define_const(rb_mFConst, "SYNC", INT2FIX(O_SYNC));
9123#endif
9124#ifdef O_DSYNC
9125 /* {File::DSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
9126 rb_define_const(rb_mFConst, "DSYNC", INT2FIX(O_DSYNC));
9127#endif
9128#ifdef O_RSYNC
9129 /* {File::RSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
9130 rb_define_const(rb_mFConst, "RSYNC", INT2FIX(O_RSYNC));
9131#endif
9132#ifdef O_NOFOLLOW
9133 /* {File::NOFOLLOW}[rdoc-ref:File::Constants@File-3A-3ANOFOLLOW] */
9134 rb_define_const(rb_mFConst, "NOFOLLOW", INT2FIX(O_NOFOLLOW)); /* FreeBSD, Linux */
9135#endif
9136#ifdef O_NOATIME
9137 /* {File::NOATIME}[rdoc-ref:File::Constants@File-3A-3ANOATIME] */
9138 rb_define_const(rb_mFConst, "NOATIME", INT2FIX(O_NOATIME)); /* Linux */
9139#endif
9140#ifdef O_DIRECT
9141 /* {File::DIRECT}[rdoc-ref:File::Constants@File-3A-3ADIRECT] */
9142 rb_define_const(rb_mFConst, "DIRECT", INT2FIX(O_DIRECT));
9143#endif
9144#ifdef O_TMPFILE
9145 /* {File::TMPFILE}[rdoc-ref:File::Constants@File-3A-3ATMPFILE] */
9146 rb_define_const(rb_mFConst, "TMPFILE", INT2FIX(O_TMPFILE));
9147#endif
9148
9149 /* {File::LOCK_SH}[rdoc-ref:File::Constants@File-3A-3ALOCK_SH] */
9150 rb_define_const(rb_mFConst, "LOCK_SH", INT2FIX(LOCK_SH));
9151 /* {File::LOCK_EX}[rdoc-ref:File::Constants@File-3A-3ALOCK_EX] */
9152 rb_define_const(rb_mFConst, "LOCK_EX", INT2FIX(LOCK_EX));
9153 /* {File::LOCK_UN}[rdoc-ref:File::Constants@File-3A-3ALOCK_UN] */
9154 rb_define_const(rb_mFConst, "LOCK_UN", INT2FIX(LOCK_UN));
9155 /* {File::LOCK_NB}[rdoc-ref:File::Constants@File-3A-3ALOCK_NB] */
9156 rb_define_const(rb_mFConst, "LOCK_NB", INT2FIX(LOCK_NB));
9157
9158 /* {File::NULL}[rdoc-ref:File::Constants@File-3A-3ANULL] */
9159 rb_define_const(rb_mFConst, "NULL", rb_fstring_cstr(ruby_null_device));
9160
9161 rb_define_global_function("test", rb_f_test, -1);
9162
9163 rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
9164 rb_define_alloc_func(rb_cStat, rb_stat_s_alloc);
9165 rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
9166 rb_define_method(rb_cStat, "initialize_copy", rb_stat_init_copy, 1);
9167
9169
9170 rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
9171
9172 rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
9173 rb_define_method(rb_cStat, "dev_major", rb_stat_dev_major, 0);
9174 rb_define_method(rb_cStat, "dev_minor", rb_stat_dev_minor, 0);
9175 rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
9176 rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
9177 rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
9178 rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
9179 rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
9180 rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
9181 rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
9182 rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
9183 rb_define_method(rb_cStat, "size", rb_stat_size, 0);
9184 rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
9185 rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
9186 rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
9187 rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
9188 rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
9189 rb_define_method(rb_cStat, "birthtime", rb_stat_birthtime, 0);
9190
9191 rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
9192
9193 rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
9194
9195 rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
9196 rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
9197 rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
9198 rb_define_method(rb_cStat, "world_readable?", rb_stat_wr, 0);
9199 rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
9200 rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
9201 rb_define_method(rb_cStat, "world_writable?", rb_stat_ww, 0);
9202 rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
9203 rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
9204 rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
9205 rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
9206 rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
9207 rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
9208 rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
9209
9210 rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
9211 rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
9212 rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
9213
9214 rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
9215 rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
9216
9217 rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
9218 rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
9219 rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);
9220}
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#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_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define PATH_SEP
The delimiter of PATH environment variable.
Definition dosish.h:45
#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
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1769
#define ENCODING_SET_INLINED(obj, i)
Old name of RB_ENCODING_SET_INLINED.
Definition encoding.h:106
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition long.h:52
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:404
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1680
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:131
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define ISALPHA
Old name of rb_isalpha.
Definition ctype.h:92
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define TOLOWER
Old name of rb_tolower.
Definition ctype.h:101
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define ISPRINT
Old name of rb_isprint.
Definition ctype.h:86
#define NUM2CHR
Old name of RB_NUM2CHR.
Definition char.h:33
#define ENCODING_GET_INLINED(obj)
Old name of RB_ENCODING_GET_INLINED.
Definition encoding.h:108
#define ENC_CODERANGE_CLEAR(obj)
Old name of RB_ENC_CODERANGE_CLEAR.
Definition coderange.h:187
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1483
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eIOError
IOError exception.
Definition io.c:193
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition error.c:1480
void rb_enc_raise(rb_encoding *enc, VALUE exc, const char *fmt,...)
Identical to rb_raise(), except it additionally takes an encoding.
Definition error.c:3952
VALUE rb_eSystemCallError
SystemCallError exception.
Definition error.c:1493
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2293
VALUE rb_cIO
IO class.
Definition io.c:191
VALUE rb_cStat
File::Stat class.
Definition file.c:178
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:669
VALUE rb_mFileTest
FileTest module.
Definition file.c:177
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
VALUE rb_obj_is_kind_of(VALUE obj, VALUE klass)
Queries if the given object is an instance (of possibly descendants) of the given class.
Definition object.c:906
VALUE rb_obj_freeze(VALUE obj)
Same as RB_OBJ_FREEZE(), but returns the given object.
Definition object.c:1309
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFile
File class.
Definition file.c:176
VALUE rb_cString
String class.
Definition string.c:85
Encoding relates APIs.
static char * rb_enc_left_char_head(const char *s, const char *p, const char *e, rb_encoding *enc)
Queries the left boundary of a character.
Definition encoding.h:683
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1379
VALUE rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.c:1175
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:988
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_ary_new_from_values(long n, const VALUE *elts)
Identical to rb_ary_new_from_args(), except how objects are passed.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:550
#define INTEGER_PACK_2COMP
Uses 2's complement representation.
Definition bignum.h:553
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:532
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
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:287
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:367
VALUE rb_str_new_shared(VALUE str)
Identical to rb_str_new_cstr(), except it takes a Ruby's string instead of C's.
Definition string.c:1549
VALUE rb_str_plus(VALUE lhs, VALUE rhs)
Generates a new string, concatenating the former to the latter.
Definition string.c:2549
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:3906
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition string.c:1791
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3259
VALUE rb_str_ellipsize(VALUE str, long len)
Shortens str and adds three dots, an ellipsis, if it is longer than len characters.
Definition string.c:13139
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_str_buf_cat
Just another name of rb_str_cat.
Definition string.h:1682
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1023
VALUE rb_str_new_frozen(VALUE str)
Creates a frozen copy of the string, if necessary.
Definition string.c:1555
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2031
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3674
VALUE rb_str_replace(VALUE dst, VALUE src)
Replaces the contents of the former object with the stringised contents of the latter.
Definition string.c:6669
VALUE rb_str_buf_append(VALUE dst, VALUE src)
Identical to rb_str_cat_cstr(), except it takes Ruby's string instead of C's.
Definition string.c:3872
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3493
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:8145
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4323
#define rb_str_dup_frozen
Just another name of rb_str_new_frozen.
Definition string.h:632
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1550
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2809
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1763
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
Definition thread.c:1624
VALUE rb_time_nano_new(time_t sec, long nsec)
Identical to rb_time_new(), except it accepts the time in nanoseconds resolution.
Definition time.c:2837
struct timespec rb_time_timespec(VALUE time)
Identical to rb_time_timeval(), except for return type.
Definition time.c:3007
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
#define GetOpenFile
This is an old name of RB_IO_POINTER.
Definition io.h:442
#define FMODE_WRITABLE
The IO is opened for writing.
Definition io.h:165
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
Definition io.h:436
void rb_io_check_closed(rb_io_t *fptr)
This badly named function asserts that the passed IO is open.
Definition io.c:858
int len
Length of the buffer.
Definition io.h:8
char * ruby_getcwd(void)
This is our own version of getcwd(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition util.c:575
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
#define MODET2NUM
Converts an instance of rb_cNumeric into C's mode_t.
Definition mode_t.h:33
VALUE rb_rescue(type *q, VALUE w, type *e, VALUE r)
An equivalent of rescue clause.
Defines RBIMPL_ATTR_NONSTRING.
#define RBIMPL_ATTR_NONSTRING()
Wraps (or simulates) __attribute__((nonstring))
Definition nonstring.h:36
#define OFFT2NUM
Converts a C's off_t into an instance of rb_cInteger.
Definition off_t.h:33
#define NUM2OFFT
Converts an instance of rb_cNumeric into C's off_t.
Definition off_t.h:44
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#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
#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_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:533
#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 FilePathStringValue(v)
This macro actually does the same thing as FilePathValue now.
Definition ruby.h:105
#define RTEST
This is an old name of RB_TEST.
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
Ruby's IO, metadata and buffers.
Definition io.h:295
enum rb_io_mode mode
mode flags: FMODE_XXXs
Definition io.h:310
int fd
file descriptor.
Definition io.h:306
VALUE pathv
pathname for file
Definition io.h:322
#define UIDT2NUM
Converts a C's uid_t into an instance of rb_cInteger.
Definition uid_t.h:28
#define NUM2UIDT
Converts an instance of rb_cNumeric into C's uid_t.
Definition uid_t.h:33
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
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
#define RBIMPL_WARNING_IGNORED(flag)
Suppresses a warning.
#define RBIMPL_WARNING_PUSH()
Pushes compiler warning state.
#define RBIMPL_WARNING_POP()
Pops compiler warning state.