Ruby: file.c Source File

Ruby 4.0.5p0 (2026-05-20 revision 64336ffd0ee9e1f4c05891695a3d7b49cb709721)

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