Ruby 4.0.10p0 (2026-11-19 revision a704b7cd95a42cc0cf5f307137bf3aac0285b915)
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"
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
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
227VALUE
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
242VALUE
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
255VALUE
256rb_get_path_no_checksafe(VALUE obj)
257{
258 return rb_get_path(obj);
259}
260
261VALUE
262rb_get_path(VALUE obj)
263{
264 return rb_get_path_check_convert(rb_get_path_check_to_string(obj));
265}
266
267VALUE
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
362VALUE
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 }
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
444 const char *ptr;
445 VALUE path;
446};
447
448struct 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,
521 NULL, // No external memory to report
522 },
523 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE
524};
525
526struct 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
539VALUE
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
574VALUE
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,
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("#<");
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
1242typedef struct no_gvl_stat_data {
1243 struct stat *st;
1244 union {
1245 const char *path;
1246 int fd;
1247 } file;
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
1427rb_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
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
1742VALUE
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
2599VALUE
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
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
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
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
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);
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
3070RBIMPL_WARNING_IGNORED(-Wunguarded-availability-new)
3071static inline utimensat_func *
3072rb_utimensat(void)
3073{
3074 return &utimensat;
3075}
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
3144struct 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
3365VALUE
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
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
3826VALUE
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 */
3862VALUE
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
3961VALUE
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 {
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
4333VALUE
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
4340VALUE
4341rb_file_expand_path_fast(VALUE fname, VALUE dname)
4342{
4343 return expand_path(fname, dname, 0, 0, EXPAND_PATH_BUFFER());
4344}
4345
4346VALUE
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
4387VALUE
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
4394VALUE
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_GC_GUARD(link);
4547 rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp));
4548 }
4549 else
4550#endif /* HAVE_READLINK */
4551 {
4552 VALUE s = rb_str_dup_frozen(testpath);
4553 rb_hash_aset(loopcheck, s, s);
4554 *resolvedp = testpath;
4555 }
4556 }
4557 }
4558 }
4559 return 0;
4560}
4561
4562static VALUE
4563rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4564{
4565 long prefixlen;
4566 VALUE resolved;
4567 VALUE unresolved_path;
4568 VALUE loopcheck;
4569 VALUE curdir = Qnil;
4570
4571 rb_encoding *enc;
4572 char *path_names = NULL, *basedir_names = NULL, *curdir_names = NULL;
4573 char *ptr, *prefixptr = NULL, *pend;
4574 long len;
4575
4576 unresolved_path = rb_str_dup_frozen(path);
4577
4578 if (!NIL_P(basedir)) {
4579 FilePathValue(basedir);
4580 basedir = TO_OSPATH(rb_str_dup_frozen(basedir));
4581 }
4582
4583 enc = rb_enc_get(unresolved_path);
4584 unresolved_path = TO_OSPATH(unresolved_path);
4585 RSTRING_GETMEM(unresolved_path, ptr, len);
4586 path_names = skipprefixroot(ptr, ptr + len, rb_enc_get(unresolved_path));
4587 if (ptr != path_names) {
4588 resolved = rb_str_subseq(unresolved_path, 0, path_names - ptr);
4589 goto root_found;
4590 }
4591
4592 if (!NIL_P(basedir)) {
4593 RSTRING_GETMEM(basedir, ptr, len);
4594 basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir));
4595 if (ptr != basedir_names) {
4596 resolved = rb_str_subseq(basedir, 0, basedir_names - ptr);
4597 goto root_found;
4598 }
4599 }
4600
4601 curdir = rb_dir_getwd_ospath();
4602 RSTRING_GETMEM(curdir, ptr, len);
4603 curdir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(curdir));
4604 resolved = rb_str_subseq(curdir, 0, curdir_names - ptr);
4605
4606 root_found:
4607 RSTRING_GETMEM(resolved, prefixptr, prefixlen);
4608 pend = prefixptr + prefixlen;
4609 ptr = chompdirsep(prefixptr, pend, enc);
4610 if (ptr < pend) {
4611 prefixlen = ++ptr - prefixptr;
4612 rb_str_set_len(resolved, prefixlen);
4613 }
4614#ifdef FILE_ALT_SEPARATOR
4615 while (prefixptr < ptr) {
4616 if (*prefixptr == FILE_ALT_SEPARATOR) {
4617 *prefixptr = '/';
4618 }
4619 Inc(prefixptr, pend, enc);
4620 }
4621#endif
4622
4623 switch (rb_enc_to_index(enc)) {
4624 case ENCINDEX_ASCII_8BIT:
4625 case ENCINDEX_US_ASCII:
4626 rb_enc_associate_index(resolved, rb_filesystem_encindex());
4627 }
4628
4629 loopcheck = rb_hash_new();
4630 if (curdir_names) {
4631 if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0))
4632 return Qnil;
4633 }
4634 if (basedir_names) {
4635 if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0))
4636 return Qnil;
4637 }
4638 if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1))
4639 return Qnil;
4640
4641 if (origenc && origenc != rb_enc_get(resolved)) {
4642 if (rb_enc_str_asciionly_p(resolved)) {
4643 rb_enc_associate(resolved, origenc);
4644 }
4645 else {
4646 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4647 }
4648 }
4649
4650 RB_GC_GUARD(unresolved_path);
4651 RB_GC_GUARD(curdir);
4652 return resolved;
4653}
4654
4655static VALUE rb_file_join(VALUE ary);
4656
4657#ifndef HAVE_REALPATH
4658static VALUE
4659rb_check_realpath_emulate_try(VALUE arg)
4660{
4661 VALUE *args = (VALUE *)arg;
4662 return rb_check_realpath_emulate(args[0], args[1], (rb_encoding *)args[2], RB_REALPATH_CHECK);
4663}
4664
4665static VALUE
4666rb_check_realpath_emulate_rescue(VALUE arg, VALUE exc)
4667{
4668 return Qnil;
4669}
4670#elif !defined(NEEDS_REALPATH_BUFFER) && defined(__APPLE__) && \
4671 (!defined(MAC_OS_X_VERSION_10_6) || (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_6))
4672/* realpath() on OSX < 10.6 doesn't implement automatic allocation */
4673# include <sys/syslimits.h>
4674# define NEEDS_REALPATH_BUFFER 1
4675#endif /* HAVE_REALPATH */
4676
4677static VALUE
4678rb_check_realpath_internal(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4679{
4680#ifdef HAVE_REALPATH
4681 VALUE unresolved_path;
4682 char *resolved_ptr = NULL;
4683 VALUE resolved;
4684# if defined(NEEDS_REALPATH_BUFFER) && NEEDS_REALPATH_BUFFER
4685 char resolved_buffer[PATH_MAX];
4686# else
4687 char *const resolved_buffer = NULL;
4688# endif
4689
4690 if (mode == RB_REALPATH_DIR) {
4691 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4692 }
4693
4694 unresolved_path = rb_str_dup_frozen(path);
4695 if (*RSTRING_PTR(unresolved_path) != '/' && !NIL_P(basedir)) {
4696 unresolved_path = rb_file_join(rb_assoc_new(basedir, unresolved_path));
4697 }
4698 if (origenc) unresolved_path = TO_OSPATH(unresolved_path);
4699
4700 if ((resolved_ptr = realpath(RSTRING_PTR(unresolved_path), resolved_buffer)) == NULL) {
4701 /*
4702 wasi-libc 22 and later support realpath(3) but return ENOTSUP
4703 when the underlying host syscall returns it.
4704 glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4705 returning ENOTDIR in that case.
4706 glibc realpath(3) can also return ENOENT for paths that exist,
4707 such as /dev/fd/5.
4708 Fallback to the emulated approach in either of those cases. */
4709 if (errno == ENOTSUP ||
4710 errno == ENOTDIR ||
4711 (errno == ENOENT && rb_file_exist_p(0, unresolved_path))) {
4712 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4713
4714 }
4715 if (mode == RB_REALPATH_CHECK) {
4716 return Qnil;
4717 }
4718 rb_sys_fail_path(unresolved_path);
4719 }
4720 resolved = ospath_new(resolved_ptr, strlen(resolved_ptr), rb_filesystem_encoding());
4721# if !(defined(NEEDS_REALPATH_BUFFER) && NEEDS_REALPATH_BUFFER)
4722 free(resolved_ptr);
4723# endif
4724
4725# if !defined(__linux__) && !defined(__APPLE__)
4726 /* As `resolved` is a String in the filesystem encoding, no
4727 * conversion is needed */
4728 struct stat st;
4729 if (stat_without_gvl(RSTRING_PTR(resolved), &st) < 0) {
4730 if (mode == RB_REALPATH_CHECK) {
4731 return Qnil;
4732 }
4733 rb_sys_fail_path(unresolved_path);
4734 }
4735# endif /* !defined(__linux__) && !defined(__APPLE__) */
4736
4737 if (origenc && origenc != rb_enc_get(resolved)) {
4738 if (!rb_enc_str_asciionly_p(resolved)) {
4739 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4740 }
4741 rb_enc_associate(resolved, origenc);
4742 }
4743
4744 if (is_broken_string(resolved)) {
4745 rb_enc_associate(resolved, rb_filesystem_encoding());
4746 if (is_broken_string(resolved)) {
4747 rb_enc_associate(resolved, rb_ascii8bit_encoding());
4748 }
4749 }
4750
4751 RB_GC_GUARD(unresolved_path);
4752 return resolved;
4753#else /* !HAVE_REALPATH */
4754 if (mode == RB_REALPATH_CHECK) {
4755 VALUE arg[3];
4756 arg[0] = basedir;
4757 arg[1] = path;
4758 arg[2] = (VALUE)origenc;
4759
4760 return rb_rescue(rb_check_realpath_emulate_try, (VALUE)arg,
4761 rb_check_realpath_emulate_rescue, Qnil);
4762 }
4763 else {
4764 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4765 }
4766#endif /* HAVE_REALPATH */
4767}
4768
4769VALUE
4770rb_realpath_internal(VALUE basedir, VALUE path, int strict)
4771{
4772 const enum rb_realpath_mode mode =
4773 strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR;
4774 return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode);
4775}
4776
4777VALUE
4778rb_check_realpath(VALUE basedir, VALUE path, rb_encoding *enc)
4779{
4780 return rb_check_realpath_internal(basedir, path, enc, RB_REALPATH_CHECK);
4781}
4782
4783/*
4784 * call-seq:
4785 * File.realpath(pathname [, dir_string]) -> real_pathname
4786 *
4787 * Returns the real (absolute) pathname of _pathname_ in the actual
4788 * filesystem not containing symlinks or useless dots.
4789 *
4790 * If _dir_string_ is given, it is used as a base directory
4791 * for interpreting relative pathname instead of the current directory.
4792 *
4793 * All components of the pathname must exist when this method is
4794 * called.
4795 */
4796static VALUE
4797rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
4798{
4799 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4800 VALUE path = argv[0];
4801 FilePathValue(path);
4802 return rb_realpath_internal(basedir, path, 1);
4803}
4804
4805/*
4806 * call-seq:
4807 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4808 *
4809 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4810 * The real pathname doesn't contain symlinks or useless dots.
4811 *
4812 * If _dir_string_ is given, it is used as a base directory
4813 * for interpreting relative pathname instead of the current directory.
4814 *
4815 * The last component of the real pathname can be nonexistent.
4816 */
4817static VALUE
4818rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
4819{
4820 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4821 VALUE path = argv[0];
4822 FilePathValue(path);
4823 return rb_realpath_internal(basedir, path, 0);
4824}
4825
4826static size_t
4827rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc)
4828{
4829 int len1, len2;
4830 unsigned int c;
4831 const char *s, *last;
4832
4833 if (!e || !l2) return 0;
4834
4835 c = rb_enc_codepoint_len(e, e + l2, &len1, enc);
4836 if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) {
4837 if (c == '.') return l0;
4838 s = p;
4839 e = p + l1;
4840 last = e;
4841 while (s < e) {
4842 if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s;
4843 s += len1;
4844 }
4845 return last - p;
4846 }
4847 if (l1 < l2) return l1;
4848
4849 s = p+l1-l2;
4850 if (!at_char_boundary(p, s, p+l1, enc)) return 0;
4851#if CASEFOLD_FILESYSTEM
4852#define fncomp strncasecmp
4853#else
4854#define fncomp strncmp
4855#endif
4856 if (fncomp(s, e, l2) == 0) {
4857 return l1-l2;
4858 }
4859 return 0;
4860}
4861
4862const char *
4863ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encoding *enc)
4864{
4865 const char *p, *q, *e, *end;
4866#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4867 const char *root;
4868#endif
4869 long f = 0, n = -1;
4870
4871 end = name + (alllen ? (size_t)*alllen : strlen(name));
4872 name = skipprefix(name, end, enc);
4873#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4874 root = name;
4875#endif
4876 while (isdirsep(*name))
4877 name++;
4878 if (!*name) {
4879 p = name - 1;
4880 f = 1;
4881#if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4882 if (name != root) {
4883 /* has slashes */
4884 }
4885#ifdef DOSISH_DRIVE_LETTER
4886 else if (*p == ':') {
4887 p++;
4888 f = 0;
4889 }
4890#endif /* DOSISH_DRIVE_LETTER */
4891#ifdef DOSISH_UNC
4892 else {
4893 p = "/";
4894 }
4895#endif /* DOSISH_UNC */
4896#endif /* defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC */
4897 }
4898 else {
4899 if (!(p = strrdirsep(name, end, enc))) {
4900 p = name;
4901 }
4902 else {
4903 while (isdirsep(*p)) p++; /* skip last / */
4904 }
4905#if USE_NTFS
4906 n = ntfs_tail(p, end, enc) - p;
4907#else
4908 n = chompdirsep(p, end, enc) - p;
4909#endif
4910 for (q = p; q - p < n && *q == '.'; q++);
4911 for (e = 0; q - p < n; Inc(q, end, enc)) {
4912 if (*q == '.') e = q;
4913 }
4914 if (e) f = e - p;
4915 else f = n;
4916 }
4917
4918 if (baselen)
4919 *baselen = f;
4920 if (alllen)
4921 *alllen = n;
4922 return p;
4923}
4924
4925/*
4926 * call-seq:
4927 * File.basename(file_name [, suffix] ) -> base_name
4928 *
4929 * Returns the last component of the filename given in
4930 * <i>file_name</i> (after first stripping trailing separators),
4931 * which can be formed using both File::SEPARATOR and
4932 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4933 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4934 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4935 * any extension will be removed.
4936 *
4937 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4938 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4939 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4940 */
4941
4942static VALUE
4943rb_file_s_basename(int argc, VALUE *argv, VALUE _)
4944{
4945 VALUE fname, fext, basename;
4946 const char *name, *p;
4947 long f, n;
4948 rb_encoding *enc;
4949
4950 fext = Qnil;
4951 if (rb_check_arity(argc, 1, 2) == 2) {
4952 fext = argv[1];
4953 StringValue(fext);
4954 enc = check_path_encoding(fext);
4955 }
4956 fname = argv[0];
4957 FilePathStringValue(fname);
4958 if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
4959 enc = rb_enc_get(fname);
4960 fext = Qnil;
4961 }
4962 if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
4963 return rb_str_new_shared(fname);
4964
4965 p = ruby_enc_find_basename(name, &f, &n, enc);
4966 if (n >= 0) {
4967 if (NIL_P(fext)) {
4968 f = n;
4969 }
4970 else {
4971 const char *fp;
4972 fp = StringValueCStr(fext);
4973 if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
4974 f = n;
4975 }
4976 RB_GC_GUARD(fext);
4977 }
4978 if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
4979 }
4980
4981 basename = rb_str_new(p, f);
4982 rb_enc_copy(basename, fname);
4983 return basename;
4984}
4985
4986static VALUE rb_file_dirname_n(VALUE fname, int n);
4987
4988/*
4989 * call-seq:
4990 * File.dirname(file_name, level = 1) -> dir_name
4991 *
4992 * Returns all components of the filename given in <i>file_name</i>
4993 * except the last one (after first stripping trailing separators).
4994 * The filename can be formed using both File::SEPARATOR and
4995 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4996 * not <code>nil</code>.
4997 *
4998 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4999 *
5000 * If +level+ is given, removes the last +level+ components, not only
5001 * one.
5002 *
5003 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
5004 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
5005 */
5006
5007static VALUE
5008rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
5009{
5010 int n = 1;
5011 if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
5012 n = NUM2INT(argv[1]);
5013 }
5014 return rb_file_dirname_n(argv[0], n);
5015}
5016
5017VALUE
5018rb_file_dirname(VALUE fname)
5019{
5020 return rb_file_dirname_n(fname, 1);
5021}
5022
5023static VALUE
5024rb_file_dirname_n(VALUE fname, int n)
5025{
5026 const char *name, *root, *p, *end;
5027 VALUE dirname;
5028 rb_encoding *enc;
5029 VALUE sepsv = 0;
5030 const char **seps;
5031
5032 if (n < 0) rb_raise(rb_eArgError, "negative level: %d", n);
5033 FilePathStringValue(fname);
5034 name = StringValueCStr(fname);
5035 end = name + RSTRING_LEN(fname);
5036 enc = rb_enc_get(fname);
5037 root = skiproot(name, end, enc);
5038#ifdef DOSISH_UNC
5039 if (root > name + 1 && isdirsep(*name))
5040 root = skipprefix(name = root - 2, end, enc);
5041#else
5042 if (root > name + 1)
5043 name = root - 1;
5044#endif
5045 if (n > (end - root + 1) / 2) {
5046 p = root;
5047 }
5048 else {
5049 int i;
5050 switch (n) {
5051 case 0:
5052 p = end;
5053 break;
5054 case 1:
5055 if (!(p = strrdirsep(root, end, enc))) p = root;
5056 break;
5057 default:
5058 seps = ALLOCV_N(const char *, sepsv, n);
5059 for (i = 0; i < n; ++i) seps[i] = root;
5060 i = 0;
5061 for (p = root; p < end; ) {
5062 if (isdirsep(*p)) {
5063 const char *tmp = p++;
5064 while (p < end && isdirsep(*p)) p++;
5065 if (p >= end) break;
5066 seps[i++] = tmp;
5067 if (i == n) i = 0;
5068 }
5069 else {
5070 Inc(p, end, enc);
5071 }
5072 }
5073 p = seps[i];
5074 ALLOCV_END(sepsv);
5075 break;
5076 }
5077 }
5078 if (p == name) {
5079 dirname = rb_str_new(".", 1);
5080 rb_enc_copy(dirname, fname);
5081 return dirname;
5082 }
5083#ifdef DOSISH_DRIVE_LETTER
5084 if (has_drive_letter(name) && isdirsep(*(name + 2))) {
5085 const char *top = skiproot(name + 2, end, enc);
5086 dirname = rb_str_new(name, 3);
5087 rb_str_cat(dirname, top, p - top);
5088 }
5089 else
5090#endif
5091 dirname = rb_str_new(name, p - name);
5092#ifdef DOSISH_DRIVE_LETTER
5093 if (has_drive_letter(name) && root == name + 2 && p - name == 2)
5094 rb_str_cat(dirname, ".", 1);
5095#endif
5096 rb_enc_copy(dirname, fname);
5097 return dirname;
5098}
5099
5100/*
5101 * accept a String, and return the pointer of the extension.
5102 * if len is passed, set the length of extension to it.
5103 * returned pointer is in ``name'' or NULL.
5104 * returns *len
5105 * no dot NULL 0
5106 * dotfile top 0
5107 * end with dot dot 1
5108 * .ext dot len of .ext
5109 * .ext:stream dot len of .ext without :stream (NTFS only)
5110 *
5111 */
5112const char *
5113ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc)
5114{
5115 const char *p, *e, *end = name + (len ? *len : (long)strlen(name));
5116
5117 p = strrdirsep(name, end, enc); /* get the last path component */
5118 if (!p)
5119 p = name;
5120 else
5121 do name = ++p; while (isdirsep(*p));
5122
5123 e = 0;
5124 while (*p && *p == '.') p++;
5125 while (*p) {
5126 if (*p == '.' || istrailinggarbage(*p)) {
5127#if USE_NTFS
5128 const char *last = p++, *dot = last;
5129 while (istrailinggarbage(*p)) {
5130 if (*p == '.') dot = p;
5131 p++;
5132 }
5133 if (!*p || isADS(*p)) {
5134 p = last;
5135 break;
5136 }
5137 if (*last == '.' || dot > last) e = dot;
5138 continue;
5139#else
5140 e = p; /* get the last dot of the last component */
5141#endif /* USE_NTFS */
5142 }
5143#if USE_NTFS
5144 else if (isADS(*p)) {
5145 break;
5146 }
5147#endif
5148 else if (isdirsep(*p))
5149 break;
5150 Inc(p, end, enc);
5151 }
5152
5153 if (len) {
5154 /* no dot, or the only dot is first or end? */
5155 if (!e || e == name)
5156 *len = 0;
5157 else if (e+1 == p)
5158 *len = 1;
5159 else
5160 *len = p - e;
5161 }
5162 return e;
5163}
5164
5165/*
5166 * call-seq:
5167 * File.extname(path) -> string
5168 *
5169 * Returns the extension (the portion of file name in +path+
5170 * starting from the last period).
5171 *
5172 * If +path+ is a dotfile, or starts with a period, then the starting
5173 * dot is not dealt with the start of the extension.
5174 *
5175 * An empty string will also be returned when the period is the last character
5176 * in +path+.
5177 *
5178 * On Windows, trailing dots are truncated.
5179 *
5180 * File.extname("test.rb") #=> ".rb"
5181 * File.extname("a/b/d/test.rb") #=> ".rb"
5182 * File.extname(".a/b/d/test.rb") #=> ".rb"
5183 * File.extname("foo.") #=> "" on Windows
5184 * File.extname("foo.") #=> "." on non-Windows
5185 * File.extname("test") #=> ""
5186 * File.extname(".profile") #=> ""
5187 * File.extname(".profile.sh") #=> ".sh"
5188 *
5189 */
5190
5191static VALUE
5192rb_file_s_extname(VALUE klass, VALUE fname)
5193{
5194 const char *name, *e;
5195 long len;
5196 VALUE extname;
5197
5198 FilePathStringValue(fname);
5199 name = StringValueCStr(fname);
5200 len = RSTRING_LEN(fname);
5201 e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
5202 if (len < 1)
5203 return rb_str_new(0, 0);
5204 extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
5205 return extname;
5206}
5207
5208/*
5209 * call-seq:
5210 * File.path(path) -> string
5211 *
5212 * Returns the string representation of the path
5213 *
5214 * File.path(File::NULL) #=> "/dev/null"
5215 * File.path(Pathname.new("/tmp")) #=> "/tmp"
5216 *
5217 * If +path+ is not a String:
5218 *
5219 * 1. If it has the +to_path+ method, that method will be called to
5220 * coerce to a String.
5221 *
5222 * 2. Otherwise, or if the coerced result is not a String too, the
5223 * standard coersion using +to_str+ method will take place on that
5224 * object. (See also String.try_convert)
5225 *
5226 * The coerced string must satisfy the following conditions:
5227 *
5228 * 1. It must be in an ASCII-compatible encoding; otherwise, an
5229 * Encoding::CompatibilityError is raised.
5230 *
5231 * 2. It must not contain the NUL character (<tt>\0</tt>); otherwise,
5232 * an ArgumentError is raised.
5233 */
5234
5235static VALUE
5236rb_file_s_path(VALUE klass, VALUE fname)
5237{
5238 return rb_get_path(fname);
5239}
5240
5241/*
5242 * call-seq:
5243 * File.split(file_name) -> array
5244 *
5245 * Splits the given string into a directory and a file component and
5246 * returns them in a two-element array. See also File::dirname and
5247 * File::basename.
5248 *
5249 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
5250 */
5251
5252static VALUE
5253rb_file_s_split(VALUE klass, VALUE path)
5254{
5255 FilePathStringValue(path); /* get rid of converting twice */
5256 return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));
5257}
5258
5259static VALUE
5260file_inspect_join(VALUE ary, VALUE arg, int recur)
5261{
5262 if (recur || ary == arg) rb_raise(rb_eArgError, "recursive array");
5263 return rb_file_join(arg);
5264}
5265
5266static VALUE
5267rb_file_join(VALUE ary)
5268{
5269 long len, i;
5270 VALUE result, tmp;
5271 const char *name, *tail;
5272 int checked = TRUE;
5273 rb_encoding *enc;
5274
5275 if (RARRAY_LEN(ary) == 0) return rb_str_new(0, 0);
5276
5277 len = 1;
5278 for (i=0; i<RARRAY_LEN(ary); i++) {
5279 tmp = RARRAY_AREF(ary, i);
5280 if (RB_TYPE_P(tmp, T_STRING)) {
5281 check_path_encoding(tmp);
5282 len += RSTRING_LEN(tmp);
5283 }
5284 else {
5285 len += 10;
5286 }
5287 }
5288 len += RARRAY_LEN(ary) - 1;
5289 result = rb_str_buf_new(len);
5290 RBASIC_CLEAR_CLASS(result);
5291 for (i=0; i<RARRAY_LEN(ary); i++) {
5292 tmp = RARRAY_AREF(ary, i);
5293 switch (OBJ_BUILTIN_TYPE(tmp)) {
5294 case T_STRING:
5295 if (!checked) check_path_encoding(tmp);
5296 StringValueCStr(tmp);
5297 break;
5298 case T_ARRAY:
5299 if (ary == tmp) {
5300 rb_raise(rb_eArgError, "recursive array");
5301 }
5302 else {
5303 tmp = rb_exec_recursive(file_inspect_join, ary, tmp);
5304 }
5305 break;
5306 default:
5308 checked = FALSE;
5309 }
5310 RSTRING_GETMEM(result, name, len);
5311 if (i == 0) {
5312 rb_enc_copy(result, tmp);
5313 }
5314 else {
5315 tail = chompdirsep(name, name + len, rb_enc_get(result));
5316 if (RSTRING_PTR(tmp) && isdirsep(RSTRING_PTR(tmp)[0])) {
5317 rb_str_set_len(result, tail - name);
5318 }
5319 else if (!*tail) {
5320 rb_str_cat(result, "/", 1);
5321 }
5322 }
5323 enc = fs_enc_check(result, tmp);
5324 rb_str_buf_append(result, tmp);
5325 rb_enc_associate(result, enc);
5326 }
5327 RBASIC_SET_CLASS_RAW(result, rb_cString);
5328
5329 return result;
5330}
5331
5332/*
5333 * call-seq:
5334 * File.join(string, ...) -> string
5335 *
5336 * Returns a new string formed by joining the strings using
5337 * <code>"/"</code>.
5338 *
5339 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5340 *
5341 */
5342
5343static VALUE
5344rb_file_s_join(VALUE klass, VALUE args)
5345{
5346 return rb_file_join(args);
5347}
5348
5349#if defined(HAVE_TRUNCATE)
5350struct truncate_arg {
5351 const char *path;
5352 rb_off_t pos;
5353};
5354
5355static void *
5356nogvl_truncate(void *ptr)
5357{
5358 struct truncate_arg *ta = ptr;
5359 return (void *)(VALUE)truncate(ta->path, ta->pos);
5360}
5361
5362/*
5363 * call-seq:
5364 * File.truncate(file_name, integer) -> 0
5365 *
5366 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5367 * bytes long. Not available on all platforms.
5368 *
5369 * f = File.new("out", "w")
5370 * f.write("1234567890") #=> 10
5371 * f.close #=> nil
5372 * File.truncate("out", 5) #=> 0
5373 * File.size("out") #=> 5
5374 *
5375 */
5376
5377static VALUE
5378rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
5379{
5380 struct truncate_arg ta;
5381 int r;
5382
5383 ta.pos = NUM2OFFT(len);
5384 FilePathValue(path);
5385 path = rb_str_encode_ospath(path);
5386 ta.path = StringValueCStr(path);
5387
5388 r = IO_WITHOUT_GVL_INT(nogvl_truncate, &ta);
5389 if (r < 0)
5390 rb_sys_fail_path(path);
5391 return INT2FIX(0);
5392}
5393#else
5394#define rb_file_s_truncate rb_f_notimplement
5395#endif
5396
5397#if defined(HAVE_FTRUNCATE)
5398struct ftruncate_arg {
5399 int fd;
5400 rb_off_t pos;
5401};
5402
5403static VALUE
5404nogvl_ftruncate(void *ptr)
5405{
5406 struct ftruncate_arg *fa = ptr;
5407
5408 return (VALUE)ftruncate(fa->fd, fa->pos);
5409}
5410
5411/*
5412 * call-seq:
5413 * file.truncate(integer) -> 0
5414 *
5415 * Truncates <i>file</i> to at most <i>integer</i> bytes. The file
5416 * must be opened for writing. Not available on all platforms.
5417 *
5418 * f = File.new("out", "w")
5419 * f.syswrite("1234567890") #=> 10
5420 * f.truncate(5) #=> 0
5421 * f.close() #=> nil
5422 * File.size("out") #=> 5
5423 */
5424
5425static VALUE
5426rb_file_truncate(VALUE obj, VALUE len)
5427{
5428 rb_io_t *fptr;
5429 struct ftruncate_arg fa;
5430
5431 fa.pos = NUM2OFFT(len);
5432 GetOpenFile(obj, fptr);
5433 if (!(fptr->mode & FMODE_WRITABLE)) {
5434 rb_raise(rb_eIOError, "not opened for writing");
5435 }
5436 rb_io_flush_raw(obj, 0);
5437 fa.fd = fptr->fd;
5438 if ((int)rb_io_blocking_region(fptr, nogvl_ftruncate, &fa) < 0) {
5439 rb_sys_fail_path(fptr->pathv);
5440 }
5441 return INT2FIX(0);
5442}
5443#else
5444#define rb_file_truncate rb_f_notimplement
5445#endif
5446
5447# ifndef LOCK_SH
5448# define LOCK_SH 1
5449# endif
5450# ifndef LOCK_EX
5451# define LOCK_EX 2
5452# endif
5453# ifndef LOCK_NB
5454# define LOCK_NB 4
5455# endif
5456# ifndef LOCK_UN
5457# define LOCK_UN 8
5458# endif
5459
5460#ifdef __CYGWIN__
5461#include <winerror.h>
5462#endif
5463
5464static VALUE
5465rb_thread_flock(void *data)
5466{
5467#ifdef __CYGWIN__
5468 int old_errno = errno;
5469#endif
5470 int *op = data, ret = flock(op[0], op[1]);
5471
5472#ifdef __CYGWIN__
5473 if (GetLastError() == ERROR_NOT_LOCKED) {
5474 ret = 0;
5475 errno = old_errno;
5476 }
5477#endif
5478 return (VALUE)ret;
5479}
5480
5481/* :markup: markdown
5482 *
5483 * call-seq:
5484 * flock(locking_constant) -> 0 or false
5485 *
5486 * Locks or unlocks file +self+ according to the given `locking_constant`,
5487 * a bitwise OR of the values in the table below.
5488 *
5489 * Not available on all platforms.
5490 *
5491 * Returns `false` if `File::LOCK_NB` is specified and the operation would have blocked;
5492 * otherwise returns `0`.
5493 *
5494 * | Constant | Lock | Effect
5495 * |-----------------|--------------|-----------------------------------------------------------------------------------------------------------------|
5496 * | +File::LOCK_EX+ | Exclusive | Only one process may hold an exclusive lock for +self+ at a time. |
5497 * | +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>. |
5498 * | +File::LOCK_SH+ | Shared | Multiple processes may each hold a shared lock for +self+ at the same time. |
5499 * | +File::LOCK_UN+ | Unlock | Remove an existing lock held by this process. |
5500 *
5501 * Example:
5502 *
5503 * ```ruby
5504 * # Update a counter using an exclusive lock.
5505 * # Don't use File::WRONLY because it truncates the file.
5506 * File.open('counter', File::RDWR | File::CREAT, 0644) do |f|
5507 * f.flock(File::LOCK_EX)
5508 * value = f.read.to_i + 1
5509 * f.rewind
5510 * f.write("#{value}\n")
5511 * f.flush
5512 * f.truncate(f.pos)
5513 * end
5514 *
5515 * # Read the counter using a shared lock.
5516 * File.open('counter', 'r') do |f|
5517 * f.flock(File::LOCK_SH)
5518 * f.read
5519 * end
5520 * ```
5521 *
5522 */
5523
5524static VALUE
5525rb_file_flock(VALUE obj, VALUE operation)
5526{
5527 rb_io_t *fptr;
5528 int op[2], op1;
5529 struct timeval time;
5530
5531 op[1] = op1 = NUM2INT(operation);
5532 GetOpenFile(obj, fptr);
5533 op[0] = fptr->fd;
5534
5535 if (fptr->mode & FMODE_WRITABLE) {
5536 rb_io_flush_raw(obj, 0);
5537 }
5538 while ((int)rb_io_blocking_region(fptr, rb_thread_flock, op) < 0) {
5539 int e = errno;
5540 switch (e) {
5541 case EAGAIN:
5542 case EACCES:
5543#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5544 case EWOULDBLOCK:
5545#endif
5546 if (op1 & LOCK_NB) return Qfalse;
5547
5548 time.tv_sec = 0;
5549 time.tv_usec = 100 * 1000; /* 0.1 sec */
5550 rb_thread_wait_for(time);
5551 rb_io_check_closed(fptr);
5552 continue;
5553
5554 case EINTR:
5555#if defined(ERESTART)
5556 case ERESTART:
5557#endif
5558 break;
5559
5560 default:
5561 rb_syserr_fail_path(e, fptr->pathv);
5562 }
5563 }
5564 return INT2FIX(0);
5565}
5566
5567static void
5568test_check(int n, int argc, VALUE *argv)
5569{
5570 int i;
5571
5572 n+=1;
5573 rb_check_arity(argc, n, n);
5574 for (i=1; i<n; i++) {
5575 if (!RB_TYPE_P(argv[i], T_FILE)) {
5576 FilePathValue(argv[i]);
5577 }
5578 }
5579}
5580
5581#define CHECK(n) test_check((n), argc, argv)
5582
5583/*
5584 * :markup: markdown
5585 *
5586 * call-seq:
5587 * test(char, path0, path1 = nil) -> object
5588 *
5589 * Performs a test on one or both of the <i>filesystem entities</i> at the given paths
5590 * `path0` and `path1`:
5591 *
5592 * - Each path `path0` or `path1` points to a file, directory, device, pipe, etc.
5593 * - Character `char` selects a specific test.
5594 *
5595 * The tests:
5596 *
5597 * - Each of these tests operates only on the entity at `path0`,
5598 * and returns `true` or `false`;
5599 * for a non-existent entity, returns `false` (does not raise exception):
5600 *
5601 * | Character | Test |
5602 * |:------------:|:--------------------------------------------------------------------------|
5603 * | <tt>'b'</tt> | Whether the entity is a block device. |
5604 * | <tt>'c'</tt> | Whether the entity is a character device. |
5605 * | <tt>'d'</tt> | Whether the entity is a directory. |
5606 * | <tt>'e'</tt> | Whether the entity is an existing entity. |
5607 * | <tt>'f'</tt> | Whether the entity is an existing regular file. |
5608 * | <tt>'g'</tt> | Whether the entity's setgid bit is set. |
5609 * | <tt>'G'</tt> | Whether the entity's group ownership is equal to the caller's. |
5610 * | <tt>'k'</tt> | Whether the entity's sticky bit is set. |
5611 * | <tt>'l'</tt> | Whether the entity is a symbolic link. |
5612 * | <tt>'o'</tt> | Whether the entity is owned by the caller's effective uid. |
5613 * | <tt>'O'</tt> | Like <tt>'o'</tt>, but uses the real uid (not the effective uid). |
5614 * | <tt>'p'</tt> | Whether the entity is a FIFO device (named pipe). |
5615 * | <tt>'r'</tt> | Whether the entity is readable by the caller's effective uid/gid. |
5616 * | <tt>'R'</tt> | Like <tt>'r'</tt>, but uses the real uid/gid (not the effective uid/gid). |
5617 * | <tt>'S'</tt> | Whether the entity is a socket. |
5618 * | <tt>'u'</tt> | Whether the entity's setuid bit is set. |
5619 * | <tt>'w'</tt> | Whether the entity is writable by the caller's effective uid/gid. |
5620 * | <tt>'W'</tt> | Like <tt>'w'</tt>, but uses the real uid/gid (not the effective uid/gid). |
5621 * | <tt>'x'</tt> | Whether the entity is executable by the caller's effective uid/gid. |
5622 * | <tt>'X'</tt> | Like <tt>'x'</tt>, but uses the real uid/gid (not the effective uid/git). |
5623 * | <tt>'z'</tt> | Whether the entity exists and is of length zero. |
5624 *
5625 * - This test operates only on the entity at `path0`,
5626 * and returns an integer size or +nil+:
5627 *
5628 * | Character | Test |
5629 * |:------------:|:---------------------------------------------------------------------------------------------|
5630 * | <tt>'s'</tt> | Returns positive integer size if the entity exists and has non-zero length, +nil+ otherwise. |
5631 *
5632 * - Each of these tests operates only on the entity at `path0`,
5633 * and returns a Time object;
5634 * raises an exception if the entity does not exist:
5635 *
5636 * | Character | Test |
5637 * |:------------:|:---------------------------------------|
5638 * | <tt>'A'</tt> | Last access time for the entity. |
5639 * | <tt>'C'</tt> | Last change time for the entity. |
5640 * | <tt>'M'</tt> | Last modification time for the entity. |
5641 *
5642 * - Each of these tests operates on the modification time (`mtime`)
5643 * of each of the entities at `path0` and `path1`,
5644 * and returns a `true` or `false`;
5645 * returns `false` if either entity does not exist:
5646 *
5647 * | Character | Test |
5648 * |:------------:|:----------------------------------------------------------------|
5649 * | <tt>'<'</tt> | Whether the `mtime` at `path0` is less than that at `path1`. |
5650 * | <tt>'='</tt> | Whether the `mtime` at `path0` is equal to that at `path1`. |
5651 * | <tt>'>'</tt> | Whether the `mtime` at `path0` is greater than that at `path1`. |
5652 *
5653 * - This test operates on the content of each of the entities at `path0` and `path1`,
5654 * and returns a `true` or `false`;
5655 * returns `false` if either entity does not exist:
5656 *
5657 * | Character | Test |
5658 * |:------------:|:----------------------------------------------|
5659 * | <tt>'-'</tt> | Whether the entities exist and are identical. |
5660 *
5661 */
5662
5663static VALUE
5664rb_f_test(int argc, VALUE *argv, VALUE _)
5665{
5666 int cmd;
5667
5668 if (argc == 0) rb_check_arity(argc, 2, 3);
5669 cmd = NUM2CHR(argv[0]);
5670 if (cmd == 0) {
5671 goto unknown;
5672 }
5673 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
5674 CHECK(1);
5675 switch (cmd) {
5676 case 'b':
5677 return rb_file_blockdev_p(0, argv[1]);
5678
5679 case 'c':
5680 return rb_file_chardev_p(0, argv[1]);
5681
5682 case 'd':
5683 return rb_file_directory_p(0, argv[1]);
5684
5685 case 'e':
5686 return rb_file_exist_p(0, argv[1]);
5687
5688 case 'f':
5689 return rb_file_file_p(0, argv[1]);
5690
5691 case 'g':
5692 return rb_file_sgid_p(0, argv[1]);
5693
5694 case 'G':
5695 return rb_file_grpowned_p(0, argv[1]);
5696
5697 case 'k':
5698 return rb_file_sticky_p(0, argv[1]);
5699
5700 case 'l':
5701 return rb_file_symlink_p(0, argv[1]);
5702
5703 case 'o':
5704 return rb_file_owned_p(0, argv[1]);
5705
5706 case 'O':
5707 return rb_file_rowned_p(0, argv[1]);
5708
5709 case 'p':
5710 return rb_file_pipe_p(0, argv[1]);
5711
5712 case 'r':
5713 return rb_file_readable_p(0, argv[1]);
5714
5715 case 'R':
5716 return rb_file_readable_real_p(0, argv[1]);
5717
5718 case 's':
5719 return rb_file_size_p(0, argv[1]);
5720
5721 case 'S':
5722 return rb_file_socket_p(0, argv[1]);
5723
5724 case 'u':
5725 return rb_file_suid_p(0, argv[1]);
5726
5727 case 'w':
5728 return rb_file_writable_p(0, argv[1]);
5729
5730 case 'W':
5731 return rb_file_writable_real_p(0, argv[1]);
5732
5733 case 'x':
5734 return rb_file_executable_p(0, argv[1]);
5735
5736 case 'X':
5737 return rb_file_executable_real_p(0, argv[1]);
5738
5739 case 'z':
5740 return rb_file_zero_p(0, argv[1]);
5741 }
5742 }
5743
5744 if (strchr("MAC", cmd)) {
5745 struct stat st;
5746 VALUE fname = argv[1];
5747
5748 CHECK(1);
5749 if (rb_stat(fname, &st) == -1) {
5750 int e = errno;
5751 FilePathValue(fname);
5752 rb_syserr_fail_path(e, fname);
5753 }
5754
5755 switch (cmd) {
5756 case 'A':
5757 return stat_atime(&st);
5758 case 'M':
5759 return stat_mtime(&st);
5760 case 'C':
5761 return stat_ctime(&st);
5762 }
5763 }
5764
5765 if (cmd == '-') {
5766 CHECK(2);
5767 return rb_file_identical_p(0, argv[1], argv[2]);
5768 }
5769
5770 if (strchr("=<>", cmd)) {
5771 struct stat st1, st2;
5772 stat_timestamp t1, t2;
5773
5774 CHECK(2);
5775 if (rb_stat(argv[1], &st1) < 0) return Qfalse;
5776 if (rb_stat(argv[2], &st2) < 0) return Qfalse;
5777
5778 t1 = stat_mtimespec(&st1);
5779 t2 = stat_mtimespec(&st2);
5780
5781 switch (cmd) {
5782 case '=':
5783 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
5784 return Qfalse;
5785
5786 case '>':
5787 if (t1.tv_sec > t2.tv_sec) return Qtrue;
5788 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
5789 return Qfalse;
5790
5791 case '<':
5792 if (t1.tv_sec < t2.tv_sec) return Qtrue;
5793 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
5794 return Qfalse;
5795 }
5796 }
5797 unknown:
5798 /* unknown command */
5799 if (ISPRINT(cmd)) {
5800 rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
5801 }
5802 else {
5803 rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
5804 }
5806}
5807
5808
5809/*
5810 * Document-class: File::Stat
5811 *
5812 * Objects of class File::Stat encapsulate common status information
5813 * for File objects. The information is recorded at the moment the
5814 * File::Stat object is created; changes made to the file after that
5815 * point will not be reflected. File::Stat objects are returned by
5816 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5817 * methods return platform-specific values, and not all values are
5818 * meaningful on all systems. See also Kernel#test.
5819 */
5820
5821static VALUE
5822rb_stat_s_alloc(VALUE klass)
5823{
5824 VALUE obj;
5825 stat_alloc(rb_cStat, &obj);
5826 return obj;
5827}
5828
5829/*
5830 * call-seq:
5831 * File::Stat.new(file_name) -> stat
5832 *
5833 * Create a File::Stat object for the given file name (raising an
5834 * exception if the file doesn't exist).
5835 */
5836
5837static VALUE
5838rb_stat_init(VALUE obj, VALUE fname)
5839{
5840 rb_io_stat_data st;
5841
5842 FilePathValue(fname);
5843 fname = rb_str_encode_ospath(fname);
5844 if (STATX(StringValueCStr(fname), &st, STATX_ALL) == -1) {
5845 rb_sys_fail_path(fname);
5846 }
5847
5848 struct rb_stat *rb_st;
5849 TypedData_Get_Struct(obj, struct rb_stat, &stat_data_type, rb_st);
5850
5851 rb_st->stat = st;
5852 rb_st->initialized = true;
5853
5854 return Qnil;
5855}
5856
5857/* :nodoc: */
5858static VALUE
5859rb_stat_init_copy(VALUE copy, VALUE orig)
5860{
5861 if (!OBJ_INIT_COPY(copy, orig)) return copy;
5862
5863 struct rb_stat *orig_rb_st;
5864 TypedData_Get_Struct(orig, struct rb_stat, &stat_data_type, orig_rb_st);
5865
5866 struct rb_stat *copy_rb_st;
5867 TypedData_Get_Struct(copy, struct rb_stat, &stat_data_type, copy_rb_st);
5868
5869 *copy_rb_st = *orig_rb_st;
5870 return copy;
5871}
5872
5873/*
5874 * call-seq:
5875 * stat.ftype -> string
5876 *
5877 * Identifies the type of <i>stat</i>. The return string is one of:
5878 * ``<code>file</code>'', ``<code>directory</code>'',
5879 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5880 * ``<code>fifo</code>'', ``<code>link</code>'',
5881 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5882 *
5883 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5884 *
5885 */
5886
5887static VALUE
5888rb_stat_ftype(VALUE obj)
5889{
5890 return rb_file_ftype(get_stat(obj)->ST_(mode));
5891}
5892
5893/*
5894 * call-seq:
5895 * stat.directory? -> true or false
5896 *
5897 * Returns <code>true</code> if <i>stat</i> is a directory,
5898 * <code>false</code> otherwise.
5899 *
5900 * File.stat("testfile").directory? #=> false
5901 * File.stat(".").directory? #=> true
5902 */
5903
5904static VALUE
5905rb_stat_d(VALUE obj)
5906{
5907 if (S_ISDIR(get_stat(obj)->ST_(mode))) return Qtrue;
5908 return Qfalse;
5909}
5910
5911/*
5912 * call-seq:
5913 * stat.pipe? -> true or false
5914 *
5915 * Returns <code>true</code> if the operating system supports pipes and
5916 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5917 */
5918
5919static VALUE
5920rb_stat_p(VALUE obj)
5921{
5922#ifdef S_IFIFO
5923 if (S_ISFIFO(get_stat(obj)->ST_(mode))) return Qtrue;
5924
5925#endif
5926 return Qfalse;
5927}
5928
5929/*
5930 * call-seq:
5931 * stat.symlink? -> true or false
5932 *
5933 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5934 * <code>false</code> if it isn't or if the operating system doesn't
5935 * support this feature. As File::stat automatically follows symbolic
5936 * links, #symlink? will always be <code>false</code> for an object
5937 * returned by File::stat.
5938 *
5939 * File.symlink("testfile", "alink") #=> 0
5940 * File.stat("alink").symlink? #=> false
5941 * File.lstat("alink").symlink? #=> true
5942 *
5943 */
5944
5945static VALUE
5946rb_stat_l(VALUE obj)
5947{
5948#ifdef S_ISLNK
5949 if (S_ISLNK(get_stat(obj)->ST_(mode))) return Qtrue;
5950#endif
5951 return Qfalse;
5952}
5953
5954/*
5955 * call-seq:
5956 * stat.socket? -> true or false
5957 *
5958 * Returns <code>true</code> if <i>stat</i> is a socket,
5959 * <code>false</code> if it isn't or if the operating system doesn't
5960 * support this feature.
5961 *
5962 * File.stat("testfile").socket? #=> false
5963 *
5964 */
5965
5966static VALUE
5967rb_stat_S(VALUE obj)
5968{
5969#ifdef S_ISSOCK
5970 if (S_ISSOCK(get_stat(obj)->ST_(mode))) return Qtrue;
5971
5972#endif
5973 return Qfalse;
5974}
5975
5976/*
5977 * call-seq:
5978 * stat.blockdev? -> true or false
5979 *
5980 * Returns <code>true</code> if the file is a block device,
5981 * <code>false</code> if it isn't or if the operating system doesn't
5982 * support this feature.
5983 *
5984 * File.stat("testfile").blockdev? #=> false
5985 * File.stat("/dev/hda1").blockdev? #=> true
5986 *
5987 */
5988
5989static VALUE
5990rb_stat_b(VALUE obj)
5991{
5992#ifdef S_ISBLK
5993 if (S_ISBLK(get_stat(obj)->ST_(mode))) return Qtrue;
5994
5995#endif
5996 return Qfalse;
5997}
5998
5999/*
6000 * call-seq:
6001 * stat.chardev? -> true or false
6002 *
6003 * Returns <code>true</code> if the file is a character device,
6004 * <code>false</code> if it isn't or if the operating system doesn't
6005 * support this feature.
6006 *
6007 * File.stat("/dev/tty").chardev? #=> true
6008 *
6009 */
6010
6011static VALUE
6012rb_stat_c(VALUE obj)
6013{
6014 if (S_ISCHR(get_stat(obj)->ST_(mode))) return Qtrue;
6015
6016 return Qfalse;
6017}
6018
6019/*
6020 * call-seq:
6021 * stat.owned? -> true or false
6022 *
6023 * Returns <code>true</code> if the effective user id of the process is
6024 * the same as the owner of <i>stat</i>.
6025 *
6026 * File.stat("testfile").owned? #=> true
6027 * File.stat("/etc/passwd").owned? #=> false
6028 *
6029 */
6030
6031static VALUE
6032rb_stat_owned(VALUE obj)
6033{
6034 if (get_stat(obj)->ST_(uid) == geteuid()) return Qtrue;
6035 return Qfalse;
6036}
6037
6038static VALUE
6039rb_stat_rowned(VALUE obj)
6040{
6041 if (get_stat(obj)->ST_(uid) == getuid()) return Qtrue;
6042 return Qfalse;
6043}
6044
6045/*
6046 * call-seq:
6047 * stat.grpowned? -> true or false
6048 *
6049 * Returns true if the effective group id of the process is the same as
6050 * the group id of <i>stat</i>. On Windows, returns <code>false</code>.
6051 *
6052 * File.stat("testfile").grpowned? #=> true
6053 * File.stat("/etc/passwd").grpowned? #=> false
6054 *
6055 */
6056
6057static VALUE
6058rb_stat_grpowned(VALUE obj)
6059{
6060#ifndef _WIN32
6061 if (rb_group_member(get_stat(obj)->ST_(gid))) return Qtrue;
6062#endif
6063 return Qfalse;
6064}
6065
6066/*
6067 * call-seq:
6068 * stat.readable? -> true or false
6069 *
6070 * Returns <code>true</code> if <i>stat</i> is readable by the
6071 * effective user id of this process.
6072 *
6073 * File.stat("testfile").readable? #=> true
6074 *
6075 */
6076
6077static VALUE
6078rb_stat_r(VALUE obj)
6079{
6080 rb_io_stat_data *st = get_stat(obj);
6081
6082#ifdef USE_GETEUID
6083 if (geteuid() == 0) return Qtrue;
6084#endif
6085#ifdef S_IRUSR
6086 if (rb_stat_owned(obj))
6087 return RBOOL(st->ST_(mode) & S_IRUSR);
6088#endif
6089#ifdef S_IRGRP
6090 if (rb_stat_grpowned(obj))
6091 return RBOOL(st->ST_(mode) & S_IRGRP);
6092#endif
6093#ifdef S_IROTH
6094 if (!(st->ST_(mode) & S_IROTH)) return Qfalse;
6095#endif
6096 return Qtrue;
6097}
6098
6099/*
6100 * call-seq:
6101 * stat.readable_real? -> true or false
6102 *
6103 * Returns <code>true</code> if <i>stat</i> is readable by the real
6104 * user id of this process.
6105 *
6106 * File.stat("testfile").readable_real? #=> true
6107 *
6108 */
6109
6110static VALUE
6111rb_stat_R(VALUE obj)
6112{
6113 rb_io_stat_data *st = get_stat(obj);
6114
6115#ifdef USE_GETEUID
6116 if (getuid() == 0) return Qtrue;
6117#endif
6118#ifdef S_IRUSR
6119 if (rb_stat_rowned(obj))
6120 return RBOOL(st->ST_(mode) & S_IRUSR);
6121#endif
6122#ifdef S_IRGRP
6123 if (rb_group_member(get_stat(obj)->ST_(gid)))
6124 return RBOOL(st->ST_(mode) & S_IRGRP);
6125#endif
6126#ifdef S_IROTH
6127 if (!(st->ST_(mode) & S_IROTH)) return Qfalse;
6128#endif
6129 return Qtrue;
6130}
6131
6132/*
6133 * call-seq:
6134 * stat.world_readable? -> integer or nil
6135 *
6136 * If <i>stat</i> is readable by others, returns an integer
6137 * representing the file permission bits of <i>stat</i>. Returns
6138 * <code>nil</code> otherwise. The meaning of the bits is platform
6139 * dependent; on Unix systems, see <code>stat(2)</code>.
6140 *
6141 * m = File.stat("/etc/passwd").world_readable? #=> 420
6142 * sprintf("%o", m) #=> "644"
6143 */
6144
6145static VALUE
6146rb_stat_wr(VALUE obj)
6147{
6148#ifdef S_IROTH
6149 rb_io_stat_data *st = get_stat(obj);
6150 if ((st->ST_(mode) & (S_IROTH)) == S_IROTH) {
6151 return UINT2NUM(st->ST_(mode) & (S_IRUGO|S_IWUGO|S_IXUGO));
6152 }
6153#endif
6154 return Qnil;
6155}
6156
6157/*
6158 * call-seq:
6159 * stat.writable? -> true or false
6160 *
6161 * Returns <code>true</code> if <i>stat</i> is writable by the
6162 * effective user id of this process.
6163 *
6164 * File.stat("testfile").writable? #=> true
6165 *
6166 */
6167
6168static VALUE
6169rb_stat_w(VALUE obj)
6170{
6171 rb_io_stat_data *st = get_stat(obj);
6172
6173#ifdef USE_GETEUID
6174 if (geteuid() == 0) return Qtrue;
6175#endif
6176#ifdef S_IWUSR
6177 if (rb_stat_owned(obj))
6178 return RBOOL(st->ST_(mode) & S_IWUSR);
6179#endif
6180#ifdef S_IWGRP
6181 if (rb_stat_grpowned(obj))
6182 return RBOOL(st->ST_(mode) & S_IWGRP);
6183#endif
6184#ifdef S_IWOTH
6185 if (!(st->ST_(mode) & S_IWOTH)) return Qfalse;
6186#endif
6187 return Qtrue;
6188}
6189
6190/*
6191 * call-seq:
6192 * stat.writable_real? -> true or false
6193 *
6194 * Returns <code>true</code> if <i>stat</i> is writable by the real
6195 * user id of this process.
6196 *
6197 * File.stat("testfile").writable_real? #=> true
6198 *
6199 */
6200
6201static VALUE
6202rb_stat_W(VALUE obj)
6203{
6204 rb_io_stat_data *st = get_stat(obj);
6205
6206#ifdef USE_GETEUID
6207 if (getuid() == 0) return Qtrue;
6208#endif
6209#ifdef S_IWUSR
6210 if (rb_stat_rowned(obj))
6211 return RBOOL(st->ST_(mode) & S_IWUSR);
6212#endif
6213#ifdef S_IWGRP
6214 if (rb_group_member(get_stat(obj)->ST_(gid)))
6215 return RBOOL(st->ST_(mode) & S_IWGRP);
6216#endif
6217#ifdef S_IWOTH
6218 if (!(st->ST_(mode) & S_IWOTH)) return Qfalse;
6219#endif
6220 return Qtrue;
6221}
6222
6223/*
6224 * call-seq:
6225 * stat.world_writable? -> integer or nil
6226 *
6227 * If <i>stat</i> is writable by others, returns an integer
6228 * representing the file permission bits of <i>stat</i>. Returns
6229 * <code>nil</code> otherwise. The meaning of the bits is platform
6230 * dependent; on Unix systems, see <code>stat(2)</code>.
6231 *
6232 * m = File.stat("/tmp").world_writable? #=> 511
6233 * sprintf("%o", m) #=> "777"
6234 */
6235
6236static VALUE
6237rb_stat_ww(VALUE obj)
6238{
6239#ifdef S_IWOTH
6240 rb_io_stat_data *st = get_stat(obj);
6241 if ((st->ST_(mode) & (S_IWOTH)) == S_IWOTH) {
6242 return UINT2NUM(st->ST_(mode) & (S_IRUGO|S_IWUGO|S_IXUGO));
6243 }
6244#endif
6245 return Qnil;
6246}
6247
6248/*
6249 * call-seq:
6250 * stat.executable? -> true or false
6251 *
6252 * Returns <code>true</code> if <i>stat</i> is executable or if the
6253 * operating system doesn't distinguish executable files from
6254 * nonexecutable files. The tests are made using the effective owner of
6255 * the process.
6256 *
6257 * File.stat("testfile").executable? #=> false
6258 *
6259 */
6260
6261static VALUE
6262rb_stat_x(VALUE obj)
6263{
6264 rb_io_stat_data *st = get_stat(obj);
6265
6266#ifdef USE_GETEUID
6267 if (geteuid() == 0) {
6268 return RBOOL(st->ST_(mode) & S_IXUGO);
6269 }
6270#endif
6271#ifdef S_IXUSR
6272 if (rb_stat_owned(obj))
6273 return RBOOL(st->ST_(mode) & S_IXUSR);
6274#endif
6275#ifdef S_IXGRP
6276 if (rb_stat_grpowned(obj))
6277 return RBOOL(st->ST_(mode) & S_IXGRP);
6278#endif
6279#ifdef S_IXOTH
6280 if (!(st->ST_(mode) & S_IXOTH)) return Qfalse;
6281#endif
6282 return Qtrue;
6283}
6284
6285/*
6286 * call-seq:
6287 * stat.executable_real? -> true or false
6288 *
6289 * Same as <code>executable?</code>, but tests using the real owner of
6290 * the process.
6291 */
6292
6293static VALUE
6294rb_stat_X(VALUE obj)
6295{
6296 rb_io_stat_data *st = get_stat(obj);
6297
6298#ifdef USE_GETEUID
6299 if (getuid() == 0) {
6300 return RBOOL(st->ST_(mode) & S_IXUGO);
6301 }
6302#endif
6303#ifdef S_IXUSR
6304 if (rb_stat_rowned(obj))
6305 return RBOOL(st->ST_(mode) & S_IXUSR);
6306#endif
6307#ifdef S_IXGRP
6308 if (rb_group_member(get_stat(obj)->ST_(gid)))
6309 return RBOOL(st->ST_(mode) & S_IXGRP);
6310#endif
6311#ifdef S_IXOTH
6312 if (!(st->ST_(mode) & S_IXOTH)) return Qfalse;
6313#endif
6314 return Qtrue;
6315}
6316
6317/*
6318 * call-seq:
6319 * stat.file? -> true or false
6320 *
6321 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6322 * a device file, pipe, socket, etc.).
6323 *
6324 * File.stat("testfile").file? #=> true
6325 *
6326 */
6327
6328static VALUE
6329rb_stat_f(VALUE obj)
6330{
6331 if (S_ISREG(get_stat(obj)->ST_(mode))) return Qtrue;
6332 return Qfalse;
6333}
6334
6335/*
6336 * call-seq:
6337 * stat.zero? -> true or false
6338 *
6339 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6340 * <code>false</code> otherwise.
6341 *
6342 * File.stat("testfile").zero? #=> false
6343 *
6344 */
6345
6346static VALUE
6347rb_stat_z(VALUE obj)
6348{
6349 if (get_stat(obj)->ST_(size) == 0) return Qtrue;
6350 return Qfalse;
6351}
6352
6353/*
6354 * call-seq:
6355 * stat.size? -> Integer or nil
6356 *
6357 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6358 * the file otherwise.
6359 *
6360 * File.stat("testfile").size? #=> 66
6361 * File.stat(File::NULL).size? #=> nil
6362 *
6363 */
6364
6365static VALUE
6366rb_stat_s(VALUE obj)
6367{
6368 rb_off_t size = get_stat(obj)->ST_(size);
6369
6370 if (size == 0) return Qnil;
6371 return OFFT2NUM(size);
6372}
6373
6374/*
6375 * call-seq:
6376 * stat.setuid? -> true or false
6377 *
6378 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6379 * permission bit set, <code>false</code> if it doesn't or if the
6380 * operating system doesn't support this feature.
6381 *
6382 * File.stat("/bin/su").setuid? #=> true
6383 */
6384
6385static VALUE
6386rb_stat_suid(VALUE obj)
6387{
6388#ifdef S_ISUID
6389 if (get_stat(obj)->ST_(mode) & S_ISUID) return Qtrue;
6390#endif
6391 return Qfalse;
6392}
6393
6394/*
6395 * call-seq:
6396 * stat.setgid? -> true or false
6397 *
6398 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6399 * permission bit set, <code>false</code> if it doesn't or if the
6400 * operating system doesn't support this feature.
6401 *
6402 * File.stat("/usr/sbin/lpc").setgid? #=> true
6403 *
6404 */
6405
6406static VALUE
6407rb_stat_sgid(VALUE obj)
6408{
6409#ifdef S_ISGID
6410 if (get_stat(obj)->ST_(mode) & S_ISGID) return Qtrue;
6411#endif
6412 return Qfalse;
6413}
6414
6415/*
6416 * call-seq:
6417 * stat.sticky? -> true or false
6418 *
6419 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6420 * <code>false</code> if it doesn't or if the operating system doesn't
6421 * support this feature.
6422 *
6423 * File.stat("testfile").sticky? #=> false
6424 *
6425 */
6426
6427static VALUE
6428rb_stat_sticky(VALUE obj)
6429{
6430#ifdef S_ISVTX
6431 if (get_stat(obj)->ST_(mode) & S_ISVTX) return Qtrue;
6432#endif
6433 return Qfalse;
6434}
6435
6436#if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6437#define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6438#define HAVE_MKFIFO
6439#endif
6440
6441#ifdef HAVE_MKFIFO
6442struct mkfifo_arg {
6443 const char *path;
6444 mode_t mode;
6445};
6446
6447static void *
6448nogvl_mkfifo(void *ptr)
6449{
6450 struct mkfifo_arg *ma = ptr;
6451
6452 return (void *)(VALUE)mkfifo(ma->path, ma->mode);
6453}
6454
6455/*
6456 * call-seq:
6457 * File.mkfifo(file_name, mode=0666) => 0
6458 *
6459 * Creates a FIFO special file with name _file_name_. _mode_
6460 * specifies the FIFO's permissions. It is modified by the process's
6461 * umask in the usual way: the permissions of the created file are
6462 * (mode & ~umask).
6463 */
6464
6465static VALUE
6466rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _)
6467{
6468 VALUE path;
6469 struct mkfifo_arg ma;
6470
6471 ma.mode = 0666;
6472 rb_check_arity(argc, 1, 2);
6473 if (argc > 1) {
6474 ma.mode = NUM2MODET(argv[1]);
6475 }
6476 path = argv[0];
6477 FilePathValue(path);
6478 path = rb_str_encode_ospath(path);
6479 ma.path = RSTRING_PTR(path);
6480 if (IO_WITHOUT_GVL(nogvl_mkfifo, &ma)) {
6481 rb_sys_fail_path(path);
6482 }
6483 return INT2FIX(0);
6484}
6485#else
6486#define rb_file_s_mkfifo rb_f_notimplement
6487#endif
6488
6489static VALUE rb_mFConst;
6490
6491void
6492rb_file_const(const char *name, VALUE value)
6493{
6494 rb_define_const(rb_mFConst, name, value);
6495}
6496
6497int
6498rb_is_absolute_path(const char *path)
6499{
6500#ifdef DOSISH_DRIVE_LETTER
6501 if (has_drive_letter(path) && isdirsep(path[2])) return 1;
6502#endif
6503#ifdef DOSISH_UNC
6504 if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
6505#endif
6506#ifndef DOSISH
6507 if (path[0] == '/') return 1;
6508#endif
6509 return 0;
6510}
6511
6512int
6513ruby_is_fd_loadable(int fd)
6514{
6515#ifdef _WIN32
6516 return 1;
6517#else
6518 struct stat st;
6519
6520 if (fstat(fd, &st) < 0)
6521 return 0;
6522
6523 if (S_ISREG(st.st_mode))
6524 return 1;
6525
6526 if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
6527 return -1;
6528
6529 if (S_ISDIR(st.st_mode))
6530 errno = EISDIR;
6531 else
6532 errno = ENXIO;
6533
6534 return 0;
6535#endif
6536}
6537
6538#ifndef _WIN32
6539int
6540rb_file_load_ok(const char *path)
6541{
6542 int ret = 1;
6543 /*
6544 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6545 FIXME: Why O_NDELAY is checked?
6546 */
6547 int mode = (O_RDONLY |
6548#if defined O_NONBLOCK
6549 O_NONBLOCK |
6550#elif defined O_NDELAY
6551 O_NDELAY |
6552#endif
6553 0);
6554 int fd = rb_cloexec_open(path, mode, 0);
6555 if (fd < 0) {
6556 if (!rb_gc_for_fd(errno)) return 0;
6557 fd = rb_cloexec_open(path, mode, 0);
6558 if (fd < 0) return 0;
6559 }
6560 rb_update_max_fd(fd);
6561 ret = ruby_is_fd_loadable(fd);
6562 (void)close(fd);
6563 return ret;
6564}
6565#endif
6566
6567static int
6568is_explicit_relative(const char *path)
6569{
6570 if (*path++ != '.') return 0;
6571 if (*path == '.') path++;
6572 return isdirsep(*path);
6573}
6574
6575static VALUE
6576copy_path_class(VALUE path, VALUE orig)
6577{
6578 int encidx = rb_enc_get_index(orig);
6579 if (encidx == ENCINDEX_ASCII_8BIT || encidx == ENCINDEX_US_ASCII)
6580 encidx = rb_filesystem_encindex();
6581 rb_enc_associate_index(path, encidx);
6582 str_shrink(path);
6583 RBASIC_SET_CLASS(path, rb_obj_class(orig));
6584 OBJ_FREEZE(path);
6585 return path;
6586}
6587
6588int
6589rb_find_file_ext(VALUE *filep, const char *const *ext)
6590{
6591 const char *f = StringValueCStr(*filep);
6592 VALUE fname = *filep, load_path, tmp;
6593 long i, j, fnlen;
6594 int expanded = 0;
6595
6596 if (!ext[0]) return 0;
6597
6598 if (f[0] == '~') {
6599 fname = file_expand_path_1(fname);
6600 f = RSTRING_PTR(fname);
6601 *filep = fname;
6602 expanded = 1;
6603 }
6604
6605 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6606 if (!expanded) fname = file_expand_path_1(fname);
6607 fnlen = RSTRING_LEN(fname);
6608 for (i=0; ext[i]; i++) {
6609 rb_str_cat2(fname, ext[i]);
6610 if (rb_file_load_ok(RSTRING_PTR(fname))) {
6611 *filep = copy_path_class(fname, *filep);
6612 return (int)(i+1);
6613 }
6614 rb_str_set_len(fname, fnlen);
6615 }
6616 return 0;
6617 }
6618
6619 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6620 if (!load_path) return 0;
6621
6622 fname = rb_str_dup(*filep);
6623 RBASIC_CLEAR_CLASS(fname);
6624 fnlen = RSTRING_LEN(fname);
6625 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6626 rb_enc_associate_index(tmp, rb_usascii_encindex());
6627 for (j=0; ext[j]; j++) {
6628 rb_str_cat2(fname, ext[j]);
6629 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6630 VALUE str = RARRAY_AREF(load_path, i);
6631
6632 RB_GC_GUARD(str) = rb_get_path(str);
6633 if (RSTRING_LEN(str) == 0) continue;
6634 rb_file_expand_path_internal(fname, str, 0, 0, tmp);
6635 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
6636 *filep = copy_path_class(tmp, *filep);
6637 return (int)(j+1);
6638 }
6639 }
6640 rb_str_set_len(fname, fnlen);
6641 }
6642 rb_str_resize(tmp, 0);
6643 RB_GC_GUARD(load_path);
6644 return 0;
6645}
6646
6647VALUE
6648rb_find_file(VALUE path)
6649{
6650 VALUE tmp, load_path;
6651 const char *f = StringValueCStr(path);
6652 int expanded = 0;
6653
6654 if (f[0] == '~') {
6655 tmp = file_expand_path_1(path);
6656 path = copy_path_class(tmp, path);
6657 f = RSTRING_PTR(path);
6658 expanded = 1;
6659 }
6660
6661 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6662 if (!rb_file_load_ok(f)) return 0;
6663 if (!expanded)
6664 path = copy_path_class(file_expand_path_1(path), path);
6665 return path;
6666 }
6667
6668 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6669 if (load_path) {
6670 long i;
6671
6672 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6673 rb_enc_associate_index(tmp, rb_usascii_encindex());
6674 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6675 VALUE str = RARRAY_AREF(load_path, i);
6676 RB_GC_GUARD(str) = rb_get_path(str);
6677 if (RSTRING_LEN(str) > 0) {
6678 rb_file_expand_path_internal(path, str, 0, 0, tmp);
6679 f = RSTRING_PTR(tmp);
6680 if (rb_file_load_ok(f)) goto found;
6681 }
6682 }
6683 rb_str_resize(tmp, 0);
6684 return 0;
6685 }
6686 else {
6687 return 0; /* no path, no load */
6688 }
6689
6690 found:
6691 return copy_path_class(tmp, path);
6692}
6693
6694#define define_filetest_function(name, func, argc) do { \
6695 rb_define_module_function(rb_mFileTest, name, func, argc); \
6696 rb_define_singleton_method(rb_cFile, name, func, argc); \
6697} while(false)
6698
6699const char ruby_null_device[] =
6700#if defined DOSISH
6701 "NUL"
6702#elif defined AMIGA || defined __amigaos__
6703 "NIL"
6704#elif defined __VMS
6705 "NL:"
6706#else
6707 "/dev/null"
6708#endif
6709 ;
6710
6711/*
6712 * A \File object is a representation of a file in the underlying platform.
6713 *
6714 * Class \File extends module FileTest, supporting such singleton methods
6715 * as <tt>File.exist?</tt>.
6716 *
6717 * == About the Examples
6718 *
6719 * Many examples here use these variables:
6720 *
6721 * :include: doc/examples/files.rdoc
6722 *
6723 * == Access Modes
6724 *
6725 * Methods File.new and File.open each create a \File object for a given file path.
6726 *
6727 * === \String Access Modes
6728 *
6729 * Methods File.new and File.open each may take string argument +mode+, which:
6730 *
6731 * - Begins with a 1- or 2-character
6732 * {read/write mode}[rdoc-ref:File@Read-2FWrite+Mode].
6733 * - May also contain a 1-character {data mode}[rdoc-ref:File@Data+Mode].
6734 * - May also contain a 1-character
6735 * {file-create mode}[rdoc-ref:File@File-Create+Mode].
6736 *
6737 * ==== Read/Write Mode
6738 *
6739 * The read/write +mode+ determines:
6740 *
6741 * - Whether the file is to be initially truncated.
6742 *
6743 * - Whether reading is allowed, and if so:
6744 *
6745 * - The initial read position in the file.
6746 * - Where in the file reading can occur.
6747 *
6748 * - Whether writing is allowed, and if so:
6749 *
6750 * - The initial write position in the file.
6751 * - Where in the file writing can occur.
6752 *
6753 * These tables summarize:
6754 *
6755 * Read/Write Modes for Existing File
6756 *
6757 * |------|-----------|----------|----------|----------|-----------|
6758 * | R/W | Initial | | Initial | | Initial |
6759 * | Mode | Truncate? | Read | Read Pos | Write | Write Pos |
6760 * |------|-----------|----------|----------|----------|-----------|
6761 * | 'r' | No | Anywhere | 0 | Error | - |
6762 * | 'w' | Yes | Error | - | Anywhere | 0 |
6763 * | 'a' | No | Error | - | End only | End |
6764 * | 'r+' | No | Anywhere | 0 | Anywhere | 0 |
6765 * | 'w+' | Yes | Anywhere | 0 | Anywhere | 0 |
6766 * | 'a+' | No | Anywhere | End | End only | End |
6767 * |------|-----------|----------|----------|----------|-----------|
6768 *
6769 * Read/Write Modes for \File To Be Created
6770 *
6771 * |------|----------|----------|----------|-----------|
6772 * | R/W | | Initial | | Initial |
6773 * | Mode | Read | Read Pos | Write | Write Pos |
6774 * |------|----------|----------|----------|-----------|
6775 * | 'w' | Error | - | Anywhere | 0 |
6776 * | 'a' | Error | - | End only | 0 |
6777 * | 'w+' | Anywhere | 0 | Anywhere | 0 |
6778 * | 'a+' | Anywhere | 0 | End only | End |
6779 * |------|----------|----------|----------|-----------|
6780 *
6781 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
6782 * for a non-existent file (exception raised).
6783 *
6784 * In the tables:
6785 *
6786 * - +Anywhere+ means that methods IO#rewind, IO#pos=, and IO#seek
6787 * may be used to change the file's position,
6788 * so that allowed reading or writing may occur anywhere in the file.
6789 * - <tt>End only</tt> means that writing can occur only at end-of-file,
6790 * and that methods IO#rewind, IO#pos=, and IO#seek do not affect writing.
6791 * - +Error+ means that an exception is raised if disallowed reading or writing
6792 * is attempted.
6793 *
6794 * ===== Read/Write Modes for Existing \File
6795 *
6796 * - <tt>'r'</tt>:
6797 *
6798 * - \File is not initially truncated:
6799 *
6800 * f = File.new('t.txt') # => #<File:t.txt>
6801 * f.size == 0 # => false
6802 *
6803 * - File's initial read position is 0:
6804 *
6805 * f.pos # => 0
6806 *
6807 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
6808 *
6809 * f.readline # => "First line\n"
6810 * f.readline # => "Second line\n"
6811 *
6812 * f.rewind
6813 * f.readline # => "First line\n"
6814 *
6815 * f.pos = 1
6816 * f.readline # => "irst line\n"
6817 *
6818 * f.seek(1, :CUR)
6819 * f.readline # => "econd line\n"
6820 *
6821 * - Writing is not allowed:
6822 *
6823 * f.write('foo') # Raises IOError.
6824 *
6825 * - <tt>'w'</tt>:
6826 *
6827 * - \File is initially truncated:
6828 *
6829 * path = 't.tmp'
6830 * File.write(path, text)
6831 * f = File.new(path, 'w')
6832 * f.size == 0 # => true
6833 *
6834 * - File's initial write position is 0:
6835 *
6836 * f.pos # => 0
6837 *
6838 * - \File may be written anywhere (even past end-of-file);
6839 * see IO#rewind, IO#pos=, IO#seek:
6840 *
6841 * f.write('foo')
6842 * f.flush
6843 * File.read(path) # => "foo"
6844 * f.pos # => 3
6845 *
6846 * f.write('bar')
6847 * f.flush
6848 * File.read(path) # => "foobar"
6849 * f.pos # => 6
6850 *
6851 * f.rewind
6852 * f.write('baz')
6853 * f.flush
6854 * File.read(path) # => "bazbar"
6855 * f.pos # => 3
6856 *
6857 * f.pos = 3
6858 * f.write('foo')
6859 * f.flush
6860 * File.read(path) # => "bazfoo"
6861 * f.pos # => 6
6862 *
6863 * f.seek(-3, :END)
6864 * f.write('bam')
6865 * f.flush
6866 * File.read(path) # => "bazbam"
6867 * f.pos # => 6
6868 *
6869 * f.pos = 8
6870 * f.write('bah') # Zero padding as needed.
6871 * f.flush
6872 * File.read(path) # => "bazbam\u0000\u0000bah"
6873 * f.pos # => 11
6874 *
6875 * - Reading is not allowed:
6876 *
6877 * f.read # Raises IOError.
6878 *
6879 * - <tt>'a'</tt>:
6880 *
6881 * - \File is not initially truncated:
6882 *
6883 * path = 't.tmp'
6884 * File.write(path, 'foo')
6885 * f = File.new(path, 'a')
6886 * f.size == 0 # => false
6887 *
6888 * - File's initial position is 0 (but is ignored):
6889 *
6890 * f.pos # => 0
6891 *
6892 * - \File may be written only at end-of-file;
6893 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6894 *
6895 * f.write('bar')
6896 * f.flush
6897 * File.read(path) # => "foobar"
6898 * f.write('baz')
6899 * f.flush
6900 * File.read(path) # => "foobarbaz"
6901 *
6902 * f.rewind
6903 * f.write('bat')
6904 * f.flush
6905 * File.read(path) # => "foobarbazbat"
6906 *
6907 * - Reading is not allowed:
6908 *
6909 * f.read # Raises IOError.
6910 *
6911 * - <tt>'r+'</tt>:
6912 *
6913 * - \File is not initially truncated:
6914 *
6915 * path = 't.tmp'
6916 * File.write(path, text)
6917 * f = File.new(path, 'r+')
6918 * f.size == 0 # => false
6919 *
6920 * - File's initial read position is 0:
6921 *
6922 * f.pos # => 0
6923 *
6924 * - \File may be read or written anywhere (even past end-of-file);
6925 * see IO#rewind, IO#pos=, IO#seek:
6926 *
6927 * f.readline # => "First line\n"
6928 * f.readline # => "Second line\n"
6929 *
6930 * f.rewind
6931 * f.readline # => "First line\n"
6932 *
6933 * f.pos = 1
6934 * f.readline # => "irst line\n"
6935 *
6936 * f.seek(1, :CUR)
6937 * f.readline # => "econd line\n"
6938 *
6939 * f.rewind
6940 * f.write('WWW')
6941 * f.flush
6942 * File.read(path)
6943 * # => "WWWst line\nSecond line\nFourth line\nFifth line\n"
6944 *
6945 * f.pos = 10
6946 * f.write('XXX')
6947 * f.flush
6948 * File.read(path)
6949 * # => "WWWst lineXXXecond line\nFourth line\nFifth line\n"
6950 *
6951 * f.seek(-6, :END)
6952 * # => 0
6953 * f.write('YYY')
6954 * # => 3
6955 * f.flush
6956 * # => #<File:t.tmp>
6957 * File.read(path)
6958 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n"
6959 *
6960 * f.seek(2, :END)
6961 * f.write('ZZZ') # Zero padding as needed.
6962 * f.flush
6963 * File.read(path)
6964 * # => "WWWst lineXXXecond line\nFourth line\nFifth YYYe\n\u0000\u0000ZZZ"
6965 *
6966 *
6967 * - <tt>'a+'</tt>:
6968 *
6969 * - \File is not initially truncated:
6970 *
6971 * path = 't.tmp'
6972 * File.write(path, 'foo')
6973 * f = File.new(path, 'a+')
6974 * f.size == 0 # => false
6975 *
6976 * - File's initial read position is 0:
6977 *
6978 * f.pos # => 0
6979 *
6980 * - \File may be written only at end-of-file;
6981 * IO#rewind, IO#pos=, IO#seek do not affect writing:
6982 *
6983 * f.write('bar')
6984 * f.flush
6985 * File.read(path) # => "foobar"
6986 * f.write('baz')
6987 * f.flush
6988 * File.read(path) # => "foobarbaz"
6989 *
6990 * f.rewind
6991 * f.write('bat')
6992 * f.flush
6993 * File.read(path) # => "foobarbazbat"
6994 *
6995 * - \File may be read anywhere; see IO#rewind, IO#pos=, IO#seek:
6996 *
6997 * f.rewind
6998 * f.read # => "foobarbazbat"
6999 *
7000 * f.pos = 3
7001 * f.read # => "barbazbat"
7002 *
7003 * f.seek(-3, :END)
7004 * f.read # => "bat"
7005 *
7006 * ===== Read/Write Modes for \File To Be Created
7007 *
7008 * Note that modes <tt>'r'</tt> and <tt>'r+'</tt> are not allowed
7009 * for a non-existent file (exception raised).
7010 *
7011 * - <tt>'w'</tt>:
7012 *
7013 * - File's initial write position is 0:
7014 *
7015 * path = 't.tmp'
7016 * FileUtils.rm_f(path)
7017 * f = File.new(path, 'w')
7018 * f.pos # => 0
7019 *
7020 * - \File may be written anywhere (even past end-of-file);
7021 * see IO#rewind, IO#pos=, IO#seek:
7022 *
7023 * f.write('foo')
7024 * f.flush
7025 * File.read(path) # => "foo"
7026 * f.pos # => 3
7027 *
7028 * f.write('bar')
7029 * f.flush
7030 * File.read(path) # => "foobar"
7031 * f.pos # => 6
7032 *
7033 * f.rewind
7034 * f.write('baz')
7035 * f.flush
7036 * File.read(path) # => "bazbar"
7037 * f.pos # => 3
7038 *
7039 * f.pos = 3
7040 * f.write('foo')
7041 * f.flush
7042 * File.read(path) # => "bazfoo"
7043 * f.pos # => 6
7044 *
7045 * f.seek(-3, :END)
7046 * f.write('bam')
7047 * f.flush
7048 * File.read(path) # => "bazbam"
7049 * f.pos # => 6
7050 *
7051 * f.pos = 8
7052 * f.write('bah') # Zero padding as needed.
7053 * f.flush
7054 * File.read(path) # => "bazbam\u0000\u0000bah"
7055 * f.pos # => 11
7056 *
7057 * - Reading is not allowed:
7058 *
7059 * f.read # Raises IOError.
7060 *
7061 * - <tt>'a'</tt>:
7062 *
7063 * - File's initial write position is 0:
7064 *
7065 * path = 't.tmp'
7066 * FileUtils.rm_f(path)
7067 * f = File.new(path, 'a')
7068 * f.pos # => 0
7069 *
7070 * - Writing occurs only at end-of-file:
7071 *
7072 * f.write('foo')
7073 * f.pos # => 3
7074 * f.write('bar')
7075 * f.pos # => 6
7076 * f.flush
7077 * File.read(path) # => "foobar"
7078 *
7079 * f.rewind
7080 * f.write('baz')
7081 * f.flush
7082 * File.read(path) # => "foobarbaz"
7083 *
7084 * - Reading is not allowed:
7085 *
7086 * f.read # Raises IOError.
7087 *
7088 * - <tt>'w+'</tt>:
7089 *
7090 * - File's initial position is 0:
7091 *
7092 * path = 't.tmp'
7093 * FileUtils.rm_f(path)
7094 * f = File.new(path, 'w+')
7095 * f.pos # => 0
7096 *
7097 * - \File may be written anywhere (even past end-of-file);
7098 * see IO#rewind, IO#pos=, IO#seek:
7099 *
7100 * f.write('foo')
7101 * f.flush
7102 * File.read(path) # => "foo"
7103 * f.pos # => 3
7104 *
7105 * f.write('bar')
7106 * f.flush
7107 * File.read(path) # => "foobar"
7108 * f.pos # => 6
7109 *
7110 * f.rewind
7111 * f.write('baz')
7112 * f.flush
7113 * File.read(path) # => "bazbar"
7114 * f.pos # => 3
7115 *
7116 * f.pos = 3
7117 * f.write('foo')
7118 * f.flush
7119 * File.read(path) # => "bazfoo"
7120 * f.pos # => 6
7121 *
7122 * f.seek(-3, :END)
7123 * f.write('bam')
7124 * f.flush
7125 * File.read(path) # => "bazbam"
7126 * f.pos # => 6
7127 *
7128 * f.pos = 8
7129 * f.write('bah') # Zero padding as needed.
7130 * f.flush
7131 * File.read(path) # => "bazbam\u0000\u0000bah"
7132 * f.pos # => 11
7133 *
7134 * - \File may be read anywhere (even past end-of-file);
7135 * see IO#rewind, IO#pos=, IO#seek:
7136 *
7137 * f.rewind
7138 * # => 0
7139 * f.read
7140 * # => "bazbam\u0000\u0000bah"
7141 *
7142 * f.pos = 3
7143 * # => 3
7144 * f.read
7145 * # => "bam\u0000\u0000bah"
7146 *
7147 * f.seek(-3, :END)
7148 * # => 0
7149 * f.read
7150 * # => "bah"
7151 *
7152 * - <tt>'a+'</tt>:
7153 *
7154 * - File's initial write position is 0:
7155 *
7156 * path = 't.tmp'
7157 * FileUtils.rm_f(path)
7158 * f = File.new(path, 'a+')
7159 * f.pos # => 0
7160 *
7161 * - Writing occurs only at end-of-file:
7162 *
7163 * f.write('foo')
7164 * f.pos # => 3
7165 * f.write('bar')
7166 * f.pos # => 6
7167 * f.flush
7168 * File.read(path) # => "foobar"
7169 *
7170 * f.rewind
7171 * f.write('baz')
7172 * f.flush
7173 * File.read(path) # => "foobarbaz"
7174 *
7175 * - \File may be read anywhere (even past end-of-file);
7176 * see IO#rewind, IO#pos=, IO#seek:
7177 *
7178 * f.rewind
7179 * f.read # => "foobarbaz"
7180 *
7181 * f.pos = 3
7182 * f.read # => "barbaz"
7183 *
7184 * f.seek(-3, :END)
7185 * f.read # => "baz"
7186 *
7187 * f.pos = 800
7188 * f.read # => ""
7189 *
7190 * ==== \Data Mode
7191 *
7192 * To specify whether data is to be treated as text or as binary data,
7193 * either of the following may be suffixed to any of the string read/write modes
7194 * above:
7195 *
7196 * - <tt>'t'</tt>: Text data; sets the default external encoding
7197 * to <tt>Encoding::UTF_8</tt>;
7198 * on Windows, enables conversion between EOL and CRLF
7199 * and enables interpreting <tt>0x1A</tt> as an end-of-file marker.
7200 * - <tt>'b'</tt>: Binary data; sets the default external encoding
7201 * to <tt>Encoding::ASCII_8BIT</tt>;
7202 * on Windows, suppresses conversion between EOL and CRLF
7203 * and disables interpreting <tt>0x1A</tt> as an end-of-file marker.
7204 *
7205 * If neither is given, the stream defaults to text data.
7206 *
7207 * Examples:
7208 *
7209 * File.new('t.txt', 'rt')
7210 * File.new('t.dat', 'rb')
7211 *
7212 * When the data mode is specified, the read/write mode may not be omitted,
7213 * and the data mode must precede the file-create mode, if given:
7214 *
7215 * File.new('t.dat', 'b') # Raises an exception.
7216 * File.new('t.dat', 'rxb') # Raises an exception.
7217 *
7218 * ==== \File-Create Mode
7219 *
7220 * The following may be suffixed to any writable string mode above:
7221 *
7222 * - <tt>'x'</tt>: Creates the file if it does not exist;
7223 * raises an exception if the file exists.
7224 *
7225 * Example:
7226 *
7227 * File.new('t.tmp', 'wx')
7228 *
7229 * When the file-create mode is specified, the read/write mode may not be omitted,
7230 * and the file-create mode must follow the data mode:
7231 *
7232 * File.new('t.dat', 'x') # Raises an exception.
7233 * File.new('t.dat', 'rxb') # Raises an exception.
7234 *
7235 * === \Integer Access Modes
7236 *
7237 * When mode is an integer it must be one or more of the following constants,
7238 * which may be combined by the bitwise OR operator <tt>|</tt>:
7239 *
7240 * - +File::RDONLY+: Open for reading only.
7241 * - +File::WRONLY+: Open for writing only.
7242 * - +File::RDWR+: Open for reading and writing.
7243 * - +File::APPEND+: Open for appending only.
7244 *
7245 * Examples:
7246 *
7247 * File.new('t.txt', File::RDONLY)
7248 * File.new('t.tmp', File::RDWR | File::CREAT | File::EXCL)
7249 *
7250 * Note: Method IO#set_encoding does not allow the mode to be specified as an integer.
7251 *
7252 * === File-Create Mode Specified as an \Integer
7253 *
7254 * These constants may also be ORed into the integer mode:
7255 *
7256 * - +File::CREAT+: Create file if it does not exist.
7257 * - +File::EXCL+: Raise an exception if +File::CREAT+ is given and the file exists.
7258 *
7259 * === \Data Mode Specified as an \Integer
7260 *
7261 * \Data mode cannot be specified as an integer.
7262 * When the stream access mode is given as an integer,
7263 * the data mode is always text, never binary.
7264 *
7265 * Note that although there is a constant +File::BINARY+,
7266 * setting its value in an integer stream mode has no effect;
7267 * this is because, as documented in File::Constants,
7268 * the +File::BINARY+ value disables line code conversion,
7269 * but does not change the external encoding.
7270 *
7271 * === Encodings
7272 *
7273 * Any of the string modes above may specify encodings -
7274 * either external encoding only or both external and internal encodings -
7275 * by appending one or both encoding names, separated by colons:
7276 *
7277 * f = File.new('t.dat', 'rb')
7278 * f.external_encoding # => #<Encoding:ASCII-8BIT>
7279 * f.internal_encoding # => nil
7280 * f = File.new('t.dat', 'rb:UTF-16')
7281 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
7282 * f.internal_encoding # => nil
7283 * f = File.new('t.dat', 'rb:UTF-16:UTF-16')
7284 * f.external_encoding # => #<Encoding:UTF-16 (dummy)>
7285 * f.internal_encoding # => #<Encoding:UTF-16>
7286 * f.close
7287 *
7288 * The numerous encoding names are available in array Encoding.name_list:
7289 *
7290 * Encoding.name_list.take(3) # => ["ASCII-8BIT", "UTF-8", "US-ASCII"]
7291 *
7292 * When the external encoding is set, strings read are tagged by that encoding
7293 * when reading, and strings written are converted to that encoding when
7294 * writing.
7295 *
7296 * When both external and internal encodings are set,
7297 * strings read are converted from external to internal encoding,
7298 * and strings written are converted from internal to external encoding.
7299 * For further details about transcoding input and output,
7300 * see {Encodings}[rdoc-ref:encodings.rdoc@Encodings].
7301 *
7302 * If the external encoding is <tt>'BOM|UTF-8'</tt>, <tt>'BOM|UTF-16LE'</tt>
7303 * or <tt>'BOM|UTF16-BE'</tt>,
7304 * Ruby checks for a Unicode BOM in the input document
7305 * to help determine the encoding.
7306 * For UTF-16 encodings the file open mode must be binary.
7307 * If the BOM is found,
7308 * it is stripped and the external encoding from the BOM is used.
7309 *
7310 * Note that the BOM-style encoding option is case insensitive,
7311 * so <tt>'bom|utf-8'</tt> is also valid.
7312 *
7313 * == \File Permissions
7314 *
7315 * A \File object has _permissions_, an octal integer representing
7316 * the permissions of an actual file in the underlying platform.
7317 *
7318 * Note that file permissions are quite different from the _mode_
7319 * of a file stream (\File object).
7320 *
7321 * In a \File object, the permissions are available thus,
7322 * where method +mode+, despite its name, returns permissions:
7323 *
7324 * f = File.new('t.txt')
7325 * f.lstat.mode.to_s(8) # => "100644"
7326 *
7327 * On a Unix-based operating system,
7328 * the three low-order octal digits represent the permissions
7329 * for owner (6), group (4), and world (4).
7330 * The triplet of bits in each octal digit represent, respectively,
7331 * read, write, and execute permissions.
7332 *
7333 * Permissions <tt>0644</tt> thus represent read-write access for owner
7334 * and read-only access for group and world.
7335 * See man pages {open(2)}[https://www.unix.com/man-page/bsd/2/open]
7336 * and {chmod(2)}[https://www.unix.com/man-page/bsd/2/chmod].
7337 *
7338 * For a directory, the meaning of the execute bit changes:
7339 * when set, the directory can be searched.
7340 *
7341 * Higher-order bits in permissions may indicate the type of file
7342 * (plain, directory, pipe, socket, etc.) and various other special features.
7343 *
7344 * On non-Posix operating systems, permissions may include only read-only or read-write,
7345 * in which case, the remaining permission will resemble typical values.
7346 * On Windows, for instance, the default permissions are <code>0644</code>;
7347 * The only change that can be made is to make the file
7348 * read-only, which is reported as <code>0444</code>.
7349 *
7350 * For a method that actually creates a file in the underlying platform
7351 * (as opposed to merely creating a \File object),
7352 * permissions may be specified:
7353 *
7354 * File.new('t.tmp', File::CREAT, 0644)
7355 * File.new('t.tmp', File::CREAT, 0444)
7356 *
7357 * Permissions may also be changed:
7358 *
7359 * f = File.new('t.tmp', File::CREAT, 0444)
7360 * f.chmod(0644)
7361 * f.chmod(0444)
7362 *
7363 * == \File \Constants
7364 *
7365 * Various constants for use in \File and IO methods
7366 * may be found in module File::Constants;
7367 * an array of their names is returned by <tt>File::Constants.constants</tt>.
7368 *
7369 * == What's Here
7370 *
7371 * First, what's elsewhere. Class \File:
7372 *
7373 * - Inherits from {class IO}[rdoc-ref:IO@What-27s+Here],
7374 * in particular, methods for creating, reading, and writing files
7375 * - Includes module FileTest,
7376 * which provides dozens of additional methods.
7377 *
7378 * Here, class \File provides methods that are useful for:
7379 *
7380 * - {Creating}[rdoc-ref:File@Creating]
7381 * - {Querying}[rdoc-ref:File@Querying]
7382 * - {Settings}[rdoc-ref:File@Settings]
7383 * - {Other}[rdoc-ref:File@Other]
7384 *
7385 * === Creating
7386 *
7387 * - ::new: Opens the file at the given path; returns the file.
7388 * - ::open: Same as ::new, but when given a block will yield the file to the block,
7389 * and close the file upon exiting the block.
7390 * - ::link: Creates a new name for an existing file using a hard link.
7391 * - ::mkfifo: Returns the FIFO file created at the given path.
7392 * - ::symlink: Creates a symbolic link for the given file path.
7393 *
7394 * === Querying
7395 *
7396 * _Paths_
7397 *
7398 * - ::absolute_path: Returns the absolute file path for the given path.
7399 * - ::absolute_path?: Returns whether the given path is the absolute file path.
7400 * - ::basename: Returns the last component of the given file path.
7401 * - ::dirname: Returns all but the last component of the given file path.
7402 * - ::expand_path: Returns the absolute file path for the given path,
7403 * expanding <tt>~</tt> for a home directory.
7404 * - ::extname: Returns the file extension for the given file path.
7405 * - ::fnmatch? (aliased as ::fnmatch): Returns whether the given file path
7406 * matches the given pattern.
7407 * - ::join: Joins path components into a single path string.
7408 * - ::path: Returns the string representation of the given path.
7409 * - ::readlink: Returns the path to the file at the given symbolic link.
7410 * - ::realdirpath: Returns the real path for the given file path,
7411 * where the last component need not exist.
7412 * - ::realpath: Returns the real path for the given file path,
7413 * where all components must exist.
7414 * - ::split: Returns an array of two strings: the directory name and basename
7415 * of the file at the given path.
7416 * - #path (aliased as #to_path): Returns the string representation of the given path.
7417 *
7418 * _Times_
7419 *
7420 * - ::atime: Returns a Time for the most recent access to the given file.
7421 * - ::birthtime: Returns a Time for the creation of the given file.
7422 * - ::ctime: Returns a Time for the metadata change of the given file.
7423 * - ::mtime: Returns a Time for the most recent data modification to
7424 * the content of the given file.
7425 * - #atime: Returns a Time for the most recent access to +self+.
7426 * - #birthtime: Returns a Time the creation for +self+.
7427 * - #ctime: Returns a Time for the metadata change of +self+.
7428 * - #mtime: Returns a Time for the most recent data modification
7429 * to the content of +self+.
7430 *
7431 * _Types_
7432 *
7433 * - ::blockdev?: Returns whether the file at the given path is a block device.
7434 * - ::chardev?: Returns whether the file at the given path is a character device.
7435 * - ::directory?: Returns whether the file at the given path is a directory.
7436 * - ::executable?: Returns whether the file at the given path is executable
7437 * by the effective user and group of the current process.
7438 * - ::executable_real?: Returns whether the file at the given path is executable
7439 * by the real user and group of the current process.
7440 * - ::exist?: Returns whether the file at the given path exists.
7441 * - ::file?: Returns whether the file at the given path is a regular file.
7442 * - ::ftype: Returns a string giving the type of the file at the given path.
7443 * - ::grpowned?: Returns whether the effective group of the current process
7444 * owns the file at the given path.
7445 * - ::identical?: Returns whether the files at two given paths are identical.
7446 * - ::lstat: Returns the File::Stat object for the last symbolic link
7447 * in the given path.
7448 * - ::owned?: Returns whether the effective user of the current process
7449 * owns the file at the given path.
7450 * - ::pipe?: Returns whether the file at the given path is a pipe.
7451 * - ::readable?: Returns whether the file at the given path is readable
7452 * by the effective user and group of the current process.
7453 * - ::readable_real?: Returns whether the file at the given path is readable
7454 * by the real user and group of the current process.
7455 * - ::setgid?: Returns whether the setgid bit is set for the file at the given path.
7456 * - ::setuid?: Returns whether the setuid bit is set for the file at the given path.
7457 * - ::socket?: Returns whether the file at the given path is a socket.
7458 * - ::stat: Returns the File::Stat object for the file at the given path.
7459 * - ::sticky?: Returns whether the file at the given path has its sticky bit set.
7460 * - ::symlink?: Returns whether the file at the given path is a symbolic link.
7461 * - ::umask: Returns the umask value for the current process.
7462 * - ::world_readable?: Returns whether the file at the given path is readable
7463 * by others.
7464 * - ::world_writable?: Returns whether the file at the given path is writable
7465 * by others.
7466 * - ::writable?: Returns whether the file at the given path is writable
7467 * by the effective user and group of the current process.
7468 * - ::writable_real?: Returns whether the file at the given path is writable
7469 * by the real user and group of the current process.
7470 * - #lstat: Returns the File::Stat object for the last symbolic link
7471 * in the path for +self+.
7472 *
7473 * _Contents_
7474 *
7475 * - ::empty? (aliased as ::zero?): Returns whether the file at the given path
7476 * exists and is empty.
7477 * - ::size: Returns the size (bytes) of the file at the given path.
7478 * - ::size?: Returns +nil+ if there is no file at the given path,
7479 * or if that file is empty; otherwise returns the file size (bytes).
7480 * - #size: Returns the size (bytes) of +self+.
7481 *
7482 * === Settings
7483 *
7484 * - ::chmod: Changes permissions of the file at the given path.
7485 * - ::chown: Change ownership of the file at the given path.
7486 * - ::lchmod: Changes permissions of the last symbolic link in the given path.
7487 * - ::lchown: Change ownership of the last symbolic in the given path.
7488 * - ::lutime: For each given file path, sets the access time and modification time
7489 * of the last symbolic link in the path.
7490 * - ::rename: Moves the file at one given path to another given path.
7491 * - ::utime: Sets the access time and modification time of each file
7492 * at the given paths.
7493 * - #flock: Locks or unlocks +self+.
7494 *
7495 * === Other
7496 *
7497 * - ::truncate: Truncates the file at the given file path to the given size.
7498 * - ::unlink (aliased as ::delete): Deletes the file for each given file path.
7499 * - #truncate: Truncates +self+ to the given size.
7500 *
7501 */
7502
7503void
7504Init_File(void)
7505{
7506#if defined(__APPLE__) && defined(HAVE_WORKING_FORK)
7507 rb_CFString_class_initialize_before_fork();
7508#endif
7509
7510 VALUE separator;
7511
7512 rb_mFileTest = rb_define_module("FileTest");
7513 rb_cFile = rb_define_class("File", rb_cIO);
7514
7515 define_filetest_function("directory?", rb_file_directory_p, 1);
7516 define_filetest_function("exist?", rb_file_exist_p, 1);
7517 define_filetest_function("readable?", rb_file_readable_p, 1);
7518 define_filetest_function("readable_real?", rb_file_readable_real_p, 1);
7519 define_filetest_function("world_readable?", rb_file_world_readable_p, 1);
7520 define_filetest_function("writable?", rb_file_writable_p, 1);
7521 define_filetest_function("writable_real?", rb_file_writable_real_p, 1);
7522 define_filetest_function("world_writable?", rb_file_world_writable_p, 1);
7523 define_filetest_function("executable?", rb_file_executable_p, 1);
7524 define_filetest_function("executable_real?", rb_file_executable_real_p, 1);
7525 define_filetest_function("file?", rb_file_file_p, 1);
7526 define_filetest_function("zero?", rb_file_zero_p, 1);
7527 define_filetest_function("empty?", rb_file_zero_p, 1);
7528 define_filetest_function("size?", rb_file_size_p, 1);
7529 define_filetest_function("size", rb_file_s_size, 1);
7530 define_filetest_function("owned?", rb_file_owned_p, 1);
7531 define_filetest_function("grpowned?", rb_file_grpowned_p, 1);
7532
7533 define_filetest_function("pipe?", rb_file_pipe_p, 1);
7534 define_filetest_function("symlink?", rb_file_symlink_p, 1);
7535 define_filetest_function("socket?", rb_file_socket_p, 1);
7536
7537 define_filetest_function("blockdev?", rb_file_blockdev_p, 1);
7538 define_filetest_function("chardev?", rb_file_chardev_p, 1);
7539
7540 define_filetest_function("setuid?", rb_file_suid_p, 1);
7541 define_filetest_function("setgid?", rb_file_sgid_p, 1);
7542 define_filetest_function("sticky?", rb_file_sticky_p, 1);
7543
7544 define_filetest_function("identical?", rb_file_identical_p, 2);
7545
7546 rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
7547 rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
7548 rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
7549
7550 rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
7551 rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
7552 rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
7553 rb_define_singleton_method(rb_cFile, "birthtime", rb_file_s_birthtime, 1);
7554
7555 rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
7556 rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
7557 rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
7558 rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
7559 rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
7560 rb_define_singleton_method(rb_cFile, "lutime", rb_file_s_lutime, -1);
7561
7562 rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
7563 rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
7564 rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
7565
7566 rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -1);
7567 rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -1);
7568 rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
7569 rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
7570 rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
7571 rb_define_singleton_method(rb_cFile, "mkfifo", rb_file_s_mkfifo, -1);
7572 rb_define_singleton_method(rb_cFile, "expand_path", s_expand_path, -1);
7573 rb_define_singleton_method(rb_cFile, "absolute_path", s_absolute_path, -1);
7574 rb_define_singleton_method(rb_cFile, "absolute_path?", s_absolute_path_p, 1);
7575 rb_define_singleton_method(rb_cFile, "realpath", rb_file_s_realpath, -1);
7576 rb_define_singleton_method(rb_cFile, "realdirpath", rb_file_s_realdirpath, -1);
7577 rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
7578 rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, -1);
7579 rb_define_singleton_method(rb_cFile, "extname", rb_file_s_extname, 1);
7580 rb_define_singleton_method(rb_cFile, "path", rb_file_s_path, 1);
7581
7582 separator = rb_fstring_lit("/");
7583 /* separates directory parts in path */
7584 rb_define_const(rb_cFile, "Separator", separator);
7585 /* separates directory parts in path */
7586 rb_define_const(rb_cFile, "SEPARATOR", separator);
7587 rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
7588 rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -2);
7589
7590#ifdef DOSISH
7591 /* platform specific alternative separator */
7592 rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator)));
7593#else
7594 rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
7595#endif
7596 /* path list separator */
7597 rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP));
7598
7599 rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
7600 rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
7601
7602 rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
7603 rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
7604 rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
7605 rb_define_method(rb_cFile, "birthtime", rb_file_birthtime, 0);
7606 rb_define_method(rb_cFile, "size", file_size, 0);
7607
7608 rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
7609 rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
7610 rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
7611
7612 rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
7613
7614 /*
7615 * Document-module: File::Constants
7616 *
7617 * Module +File::Constants+ defines file-related constants.
7618 *
7619 * There are two families of constants here:
7620 *
7621 * - Those having to do with {file access}[rdoc-ref:File::Constants@File+Access].
7622 * - Those having to do with {filename globbing}[rdoc-ref:File::Constants@Filename+Globbing+Constants+-28File-3A-3AFNM_-2A-29].
7623 *
7624 * \File constants defined for the local process may be retrieved
7625 * with method File::Constants.constants:
7626 *
7627 * File::Constants.constants.take(5)
7628 * # => [:RDONLY, :WRONLY, :RDWR, :APPEND, :CREAT]
7629 *
7630 * == \File Access
7631 *
7632 * \File-access constants may be used with optional argument +mode+ in calls
7633 * to the following methods:
7634 *
7635 * - File.new.
7636 * - File.open.
7637 * - IO.for_fd.
7638 * - IO.new.
7639 * - IO.open.
7640 * - IO.popen.
7641 * - IO.reopen.
7642 * - IO.sysopen.
7643 * - StringIO.new.
7644 * - StringIO.open.
7645 * - StringIO#reopen.
7646 *
7647 * === Read/Write Access
7648 *
7649 * Read-write access for a stream
7650 * may be specified by a file-access constant.
7651 *
7652 * The constant may be specified as part of a bitwise OR of other such constants.
7653 *
7654 * Any combination of the constants in this section may be specified.
7655 *
7656 * ==== File::RDONLY
7657 *
7658 * Flag File::RDONLY specifies the stream should be opened for reading only:
7659 *
7660 * filepath = '/tmp/t.tmp'
7661 * f = File.new(filepath, File::RDONLY)
7662 * f.write('Foo') # Raises IOError (not opened for writing).
7663 *
7664 * ==== File::WRONLY
7665 *
7666 * Flag File::WRONLY specifies that the stream should be opened for writing only:
7667 *
7668 * f = File.new(filepath, File::WRONLY)
7669 * f.read # Raises IOError (not opened for reading).
7670 *
7671 * ==== File::RDWR
7672 *
7673 * Flag File::RDWR specifies that the stream should be opened
7674 * for both reading and writing:
7675 *
7676 * f = File.new(filepath, File::RDWR)
7677 * f.write('Foo') # => 3
7678 * f.rewind # => 0
7679 * f.read # => "Foo"
7680 *
7681 * === \File Positioning
7682 *
7683 * ==== File::APPEND
7684 *
7685 * Flag File::APPEND specifies that the stream should be opened
7686 * in append mode.
7687 *
7688 * Before each write operation, the position is set to end-of-stream.
7689 * The modification of the position and the following write operation
7690 * are performed as a single atomic step.
7691 *
7692 * ==== File::TRUNC
7693 *
7694 * Flag File::TRUNC specifies that the stream should be truncated
7695 * at its beginning.
7696 * If the file exists and is successfully opened for writing,
7697 * it is to be truncated to position zero;
7698 * its ctime and mtime are updated.
7699 *
7700 * There is no effect on a FIFO special file or a terminal device.
7701 * The effect on other file types is implementation-defined.
7702 * The result of using File::TRUNC with File::RDONLY is undefined.
7703 *
7704 * === Creating and Preserving
7705 *
7706 * ==== File::CREAT
7707 *
7708 * Flag File::CREAT specifies that the stream should be created
7709 * if it does not already exist.
7710 *
7711 * If the file exists:
7712 *
7713 * - Raise an exception if File::EXCL is also specified.
7714 * - Otherwise, do nothing.
7715 *
7716 * If the file does not exist, then it is created.
7717 * Upon successful completion, the atime, ctime, and mtime of the file are updated,
7718 * and the ctime and mtime of the parent directory are updated.
7719 *
7720 * ==== File::EXCL
7721 *
7722 * Flag File::EXCL specifies that the stream should not already exist;
7723 * If flags File::CREAT and File::EXCL are both specified
7724 * and the stream already exists, an exception is raised.
7725 *
7726 * The check for the existence and creation of the file is performed as an
7727 * atomic operation.
7728 *
7729 * If both File::EXCL and File::CREAT are specified and the path names a symbolic link,
7730 * an exception is raised regardless of the contents of the symbolic link.
7731 *
7732 * If File::EXCL is specified and File::CREAT is not specified,
7733 * the result is undefined.
7734 *
7735 * === POSIX \File \Constants
7736 *
7737 * Some file-access constants are defined only on POSIX-compliant systems;
7738 * those are:
7739 *
7740 * - File::SYNC.
7741 * - File::DSYNC.
7742 * - File::RSYNC.
7743 * - File::DIRECT.
7744 * - File::NOATIME.
7745 * - File::NOCTTY.
7746 * - File::NOFOLLOW.
7747 * - File::TMPFILE.
7748 *
7749 * ==== File::SYNC, File::RSYNC, and File::DSYNC
7750 *
7751 * Flag File::SYNC, File::RSYNC, or File::DSYNC
7752 * specifies synchronization of I/O operations with the underlying file system.
7753 *
7754 * These flags are valid only for POSIX-compliant systems.
7755 *
7756 * - File::SYNC specifies that all write operations (both data and metadata)
7757 * are immediately to be flushed to the underlying storage device.
7758 * This means that the data is written to the storage device,
7759 * and the file's metadata (e.g., file size, timestamps, permissions)
7760 * are also synchronized.
7761 * This guarantees that data is safely stored on the storage medium
7762 * before returning control to the calling program.
7763 * This flag can have a significant impact on performance
7764 * since it requires synchronous writes, which can be slower
7765 * compared to asynchronous writes.
7766 *
7767 * - File::RSYNC specifies that any read operations on the file will not return
7768 * until all outstanding write operations
7769 * (those that have been issued but not completed) are also synchronized.
7770 * This is useful when you want to read the most up-to-date data,
7771 * which may still be in the process of being written.
7772 *
7773 * - File::DSYNC specifies that all _data_ write operations
7774 * are immediately to be flushed to the underlying storage device;
7775 * this differs from File::SYNC, which requires that _metadata_
7776 * also be synchronized.
7777 *
7778 * Note that the behavior of these flags may vary slightly
7779 * depending on the operating system and filesystem being used.
7780 * Additionally, using these flags can have an impact on performance
7781 * due to the synchronous nature of the I/O operations,
7782 * so they should be used judiciously,
7783 * especially in performance-critical applications.
7784 *
7785 * ==== File::NOCTTY
7786 *
7787 * Flag File::NOCTTY specifies that if the stream is a terminal device,
7788 * that device does not become the controlling terminal for the process.
7789 *
7790 * Defined only for POSIX-compliant systems.
7791 *
7792 * ==== File::DIRECT
7793 *
7794 * Flag File::DIRECT requests that cache effects of the I/O to and from the stream
7795 * be minimized.
7796 *
7797 * Defined only for POSIX-compliant systems.
7798 *
7799 * ==== File::NOATIME
7800 *
7801 * Flag File::NOATIME specifies that act of opening the stream
7802 * should not modify its access time (atime).
7803 *
7804 * Defined only for POSIX-compliant systems.
7805 *
7806 * ==== File::NOFOLLOW
7807 *
7808 * Flag File::NOFOLLOW specifies that if path is a symbolic link,
7809 * it should not be followed.
7810 *
7811 * Defined only for POSIX-compliant systems.
7812 *
7813 * ==== File::TMPFILE
7814 *
7815 * Flag File::TMPFILE specifies that the opened stream
7816 * should be a new temporary file.
7817 *
7818 * Defined only for POSIX-compliant systems.
7819 *
7820 * === Other File-Access \Constants
7821 *
7822 * ==== File::NONBLOCK
7823 *
7824 * When possible, the file is opened in nonblocking mode.
7825 * Neither the open operation nor any subsequent I/O operations on
7826 * the file will cause the calling process to wait.
7827 *
7828 * ==== File::BINARY
7829 *
7830 * Flag File::BINARY specifies that the stream is to be accessed in binary mode.
7831 *
7832 * ==== File::SHARE_DELETE
7833 *
7834 * Flag File::SHARE_DELETE enables other processes to open the stream
7835 * with delete access.
7836 *
7837 * Windows only.
7838 *
7839 * If the stream is opened for (local) delete access without File::SHARE_DELETE,
7840 * and another process attempts to open it with delete access,
7841 * the attempt fails and the stream is not opened for that process.
7842 *
7843 * == Locking
7844 *
7845 * Four file constants relate to stream locking;
7846 * see File#flock:
7847 *
7848 * ==== File::LOCK_EX
7849 *
7850 * Flag File::LOCK_EX specifies an exclusive lock;
7851 * only one process a a time may lock the stream.
7852 *
7853 * ==== File::LOCK_NB
7854 *
7855 * Flag File::LOCK_NB specifies non-blocking locking for the stream;
7856 * may be combined with File::LOCK_EX or File::LOCK_SH.
7857 *
7858 * ==== File::LOCK_SH
7859 *
7860 * Flag File::LOCK_SH specifies that multiple processes may lock
7861 * the stream at the same time.
7862 *
7863 * ==== File::LOCK_UN
7864 *
7865 * Flag File::LOCK_UN specifies that the stream is not to be locked.
7866 *
7867 * == Filename Globbing \Constants (File::FNM_*)
7868 *
7869 * Filename-globbing constants may be used with optional argument +flags+
7870 * in calls to the following methods:
7871 *
7872 * - Dir.glob.
7873 * - File.fnmatch.
7874 * - Pathname#fnmatch.
7875 * - Pathname.glob.
7876 * - Pathname#glob.
7877 *
7878 * The constants are:
7879 *
7880 * ==== File::FNM_CASEFOLD
7881 *
7882 * Flag File::FNM_CASEFOLD makes patterns case insensitive
7883 * for File.fnmatch (but not Dir.glob).
7884 *
7885 * ==== File::FNM_DOTMATCH
7886 *
7887 * Flag File::FNM_DOTMATCH makes the <tt>'*'</tt> pattern
7888 * match a filename starting with <tt>'.'</tt>.
7889 *
7890 * ==== File::FNM_EXTGLOB
7891 *
7892 * Flag File::FNM_EXTGLOB enables pattern <tt>'{_a_,_b_}'</tt>,
7893 * which matches pattern '_a_' and pattern '_b_';
7894 * behaves like
7895 * a {regexp union}[rdoc-ref:Regexp.union]
7896 * (e.g., <tt>'(?:_a_|_b_)'</tt>):
7897 *
7898 * pattern = '{LEGAL,BSDL}'
7899 * Dir.glob(pattern) # => ["LEGAL", "BSDL"]
7900 * Pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
7901 * pathname.glob(pattern) # => [#<Pathname:LEGAL>, #<Pathname:BSDL>]
7902 *
7903 * ==== File::FNM_NOESCAPE
7904 *
7905 * Flag File::FNM_NOESCAPE disables <tt>'\'</tt> escaping.
7906 *
7907 * ==== File::FNM_PATHNAME
7908 *
7909 * Flag File::FNM_PATHNAME specifies that patterns <tt>'*'</tt> and <tt>'?'</tt>
7910 * do not match the directory separator
7911 * (the value of constant File::SEPARATOR).
7912 *
7913 * ==== File::FNM_SHORTNAME
7914 *
7915 * Flag File::FNM_SHORTNAME allows patterns to match short names if they exist.
7916 *
7917 * Windows only.
7918 *
7919 * ==== File::FNM_SYSCASE
7920 *
7921 * Flag File::FNM_SYSCASE specifies that case sensitivity
7922 * is the same as in the underlying operating system;
7923 * effective for File.fnmatch, but not Dir.glob.
7924 *
7925 * == Other \Constants
7926 *
7927 * ==== File::NULL
7928 *
7929 * Flag File::NULL contains the string value of the null device:
7930 *
7931 * - On a Unix-like OS, <tt>'/dev/null'</tt>.
7932 * - On Windows, <tt>'NUL'</tt>.
7933 *
7934 */
7935 rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
7936 rb_include_module(rb_cIO, rb_mFConst);
7937 /* {File::RDONLY}[rdoc-ref:File::Constants@File-3A-3ARDONLY] */
7938 rb_define_const(rb_mFConst, "RDONLY", INT2FIX(O_RDONLY));
7939 /* {File::WRONLY}[rdoc-ref:File::Constants@File-3A-3AWRONLY] */
7940 rb_define_const(rb_mFConst, "WRONLY", INT2FIX(O_WRONLY));
7941 /* {File::RDWR}[rdoc-ref:File::Constants@File-3A-3ARDWR] */
7942 rb_define_const(rb_mFConst, "RDWR", INT2FIX(O_RDWR));
7943 /* {File::APPEND}[rdoc-ref:File::Constants@File-3A-3AAPPEND] */
7944 rb_define_const(rb_mFConst, "APPEND", INT2FIX(O_APPEND));
7945 /* {File::CREAT}[rdoc-ref:File::Constants@File-3A-3ACREAT] */
7946 rb_define_const(rb_mFConst, "CREAT", INT2FIX(O_CREAT));
7947 /* {File::EXCL}[rdoc-ref:File::Constants@File-3A-3AEXCL] */
7948 rb_define_const(rb_mFConst, "EXCL", INT2FIX(O_EXCL));
7949#if defined(O_NDELAY) || defined(O_NONBLOCK)
7950# ifndef O_NONBLOCK
7951# define O_NONBLOCK O_NDELAY
7952# endif
7953 /* {File::NONBLOCK}[rdoc-ref:File::Constants@File-3A-3ANONBLOCK] */
7954 rb_define_const(rb_mFConst, "NONBLOCK", INT2FIX(O_NONBLOCK));
7955#endif
7956 /* {File::TRUNC}[rdoc-ref:File::Constants@File-3A-3ATRUNC] */
7957 rb_define_const(rb_mFConst, "TRUNC", INT2FIX(O_TRUNC));
7958#ifdef O_NOCTTY
7959 /* {File::NOCTTY}[rdoc-ref:File::Constants@File-3A-3ANOCTTY] */
7960 rb_define_const(rb_mFConst, "NOCTTY", INT2FIX(O_NOCTTY));
7961#endif
7962#ifndef O_BINARY
7963# define O_BINARY 0
7964#endif
7965 /* {File::BINARY}[rdoc-ref:File::Constants@File-3A-3ABINARY] */
7966 rb_define_const(rb_mFConst, "BINARY", INT2FIX(O_BINARY));
7967#ifndef O_SHARE_DELETE
7968# define O_SHARE_DELETE 0
7969#endif
7970 /* {File::SHARE_DELETE}[rdoc-ref:File::Constants@File-3A-3ASHARE_DELETE] */
7971 rb_define_const(rb_mFConst, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE));
7972#ifdef O_SYNC
7973 /* {File::SYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7974 rb_define_const(rb_mFConst, "SYNC", INT2FIX(O_SYNC));
7975#endif
7976#ifdef O_DSYNC
7977 /* {File::DSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7978 rb_define_const(rb_mFConst, "DSYNC", INT2FIX(O_DSYNC));
7979#endif
7980#ifdef O_RSYNC
7981 /* {File::RSYNC}[rdoc-ref:File::Constants@File-3A-3ASYNC-2C+File-3A-3ARSYNC-2C+and+File-3A-3ADSYNC] */
7982 rb_define_const(rb_mFConst, "RSYNC", INT2FIX(O_RSYNC));
7983#endif
7984#ifdef O_NOFOLLOW
7985 /* {File::NOFOLLOW}[rdoc-ref:File::Constants@File-3A-3ANOFOLLOW] */
7986 rb_define_const(rb_mFConst, "NOFOLLOW", INT2FIX(O_NOFOLLOW)); /* FreeBSD, Linux */
7987#endif
7988#ifdef O_NOATIME
7989 /* {File::NOATIME}[rdoc-ref:File::Constants@File-3A-3ANOATIME] */
7990 rb_define_const(rb_mFConst, "NOATIME", INT2FIX(O_NOATIME)); /* Linux */
7991#endif
7992#ifdef O_DIRECT
7993 /* {File::DIRECT}[rdoc-ref:File::Constants@File-3A-3ADIRECT] */
7994 rb_define_const(rb_mFConst, "DIRECT", INT2FIX(O_DIRECT));
7995#endif
7996#ifdef O_TMPFILE
7997 /* {File::TMPFILE}[rdoc-ref:File::Constants@File-3A-3ATMPFILE] */
7998 rb_define_const(rb_mFConst, "TMPFILE", INT2FIX(O_TMPFILE));
7999#endif
8000
8001 /* {File::LOCK_SH}[rdoc-ref:File::Constants@File-3A-3ALOCK_SH] */
8002 rb_define_const(rb_mFConst, "LOCK_SH", INT2FIX(LOCK_SH));
8003 /* {File::LOCK_EX}[rdoc-ref:File::Constants@File-3A-3ALOCK_EX] */
8004 rb_define_const(rb_mFConst, "LOCK_EX", INT2FIX(LOCK_EX));
8005 /* {File::LOCK_UN}[rdoc-ref:File::Constants@File-3A-3ALOCK_UN] */
8006 rb_define_const(rb_mFConst, "LOCK_UN", INT2FIX(LOCK_UN));
8007 /* {File::LOCK_NB}[rdoc-ref:File::Constants@File-3A-3ALOCK_NB] */
8008 rb_define_const(rb_mFConst, "LOCK_NB", INT2FIX(LOCK_NB));
8009
8010 /* {File::NULL}[rdoc-ref:File::Constants@File-3A-3ANULL] */
8011 rb_define_const(rb_mFConst, "NULL", rb_fstring_cstr(ruby_null_device));
8012
8013 rb_define_global_function("test", rb_f_test, -1);
8014
8015 rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
8016 rb_define_alloc_func(rb_cStat, rb_stat_s_alloc);
8017 rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
8018 rb_define_method(rb_cStat, "initialize_copy", rb_stat_init_copy, 1);
8019
8021
8022 rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
8023
8024 rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
8025 rb_define_method(rb_cStat, "dev_major", rb_stat_dev_major, 0);
8026 rb_define_method(rb_cStat, "dev_minor", rb_stat_dev_minor, 0);
8027 rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
8028 rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
8029 rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
8030 rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
8031 rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
8032 rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
8033 rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
8034 rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
8035 rb_define_method(rb_cStat, "size", rb_stat_size, 0);
8036 rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
8037 rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
8038 rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
8039 rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
8040 rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
8041 rb_define_method(rb_cStat, "birthtime", rb_stat_birthtime, 0);
8042
8043 rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
8044
8045 rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
8046
8047 rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
8048 rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
8049 rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
8050 rb_define_method(rb_cStat, "world_readable?", rb_stat_wr, 0);
8051 rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
8052 rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
8053 rb_define_method(rb_cStat, "world_writable?", rb_stat_ww, 0);
8054 rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
8055 rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
8056 rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
8057 rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
8058 rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
8059 rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
8060 rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
8061
8062 rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
8063 rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
8064 rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
8065
8066 rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
8067 rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
8068
8069 rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
8070 rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
8071 rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);
8072}
#define STRCASECMP
@old{st_locale_insensitive_strcasecmp}
Definition ctype.h:102
#define ISALPHA
@old{rb_isalpha}
Definition ctype.h:92
#define TOLOWER
@old{rb_tolower}
Definition ctype.h:101
#define ISPRINT
@old{rb_isprint}
Definition ctype.h:86
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
#define PATH_SEP
The delimiter of PATH environment variable.
Definition dosish.h:45
#define GIDT2NUM
Converts a C's gid_t into an instance of rb_cInteger.
Definition gid_t.h:28
#define NUM2GIDT
Converts an instance of rb_cNumeric into C's gid_t.
Definition gid_t.h:33
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1695
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1488
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:1519
VALUE rb_define_module(const char *name)
Defines a top-level module.
Definition class.c:1601
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1624
#define T_FILE
Old name of RUBY_T_FILE.
Definition value_type.h:62
#define rb_str_buf_cat2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1683
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition long.h:52
#define ALLOCV
Old name of RB_ALLOCV.
Definition memory.h:404
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define rb_str_buf_new2
Old name of rb_str_buf_new_cstr.
Definition string.h:1680
#define OBJ_FREEZE
Old name of RB_OBJ_FREEZE.
Definition fl_type.h:134
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
Definition encoding.h:109
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define MBCLEN_CHARFOUND_LEN(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_LEN.
Definition encoding.h:517
#define rb_usascii_str_new2
Old name of rb_usascii_str_new_cstr.
Definition string.h:1681
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define NUM2CHR
Old name of RB_NUM2CHR.
Definition char.h:33
#define ENC_CODERANGE_CLEAR(obj)
Old name of RB_ENC_CODERANGE_CLEAR.
Definition coderange.h:187
#define UINT2NUM
Old name of RB_UINT2NUM.
Definition int.h:46
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define rb_str_new4
Old name of rb_str_new_frozen.
Definition string.h:1678
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
VALUE rb_eNotImpError
NotImplementedError exception.
Definition error.c:1441
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:664
VALUE rb_eIOError
IOError exception.
Definition io.c:194
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1431
VALUE rb_eEncCompatError
Encoding::CompatibilityError exception.
Definition error.c:1438
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:3779
VALUE rb_rescue(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2)
Identical to rb_rescue2(), except it does not take a list of exception classes.
Definition eval.c:1127
VALUE rb_eSystemCallError
SystemCallError exception.
Definition error.c:1451
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2249
VALUE rb_cIO
IO class.
Definition io.c:192
VALUE rb_cStat
File::Stat class.
Definition file.c:193
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:264
VALUE rb_inspect(VALUE obj)
Generates a human-readable textual representation of the given object.
Definition object.c:686
VALUE rb_mFileTest
FileTest module.
Definition file.c:192
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:176
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
VALUE rb_obj_freeze(VALUE obj)
Just calls rb_obj_freeze_inline() inside.
Definition object.c:1342
VALUE rb_mComparable
Comparable module.
Definition compar.c:19
VALUE rb_cFile
File class.
Definition file.c:191
VALUE rb_cString
String class.
Definition string.c:84
Encoding relates APIs.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1359
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:983
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1119
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:546
#define INTEGER_PACK_2COMP
Uses 2's complement representation.
Definition bignum.h:549
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:528
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:286
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:366
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:1529
VALUE rb_str_plus(VALUE lhs, VALUE rhs)
Generates a new string, concatenating the former to the latter.
Definition string.c:2516
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
Definition string.c:3833
VALUE rb_str_tmp_new(long len)
Allocates a "temporary" string.
Definition string.c:1763
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3184
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:11769
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1018
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2014
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3599
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:6606
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:3797
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3418
VALUE rb_str_inspect(VALUE str)
Generates a "readable" version of the receiver.
Definition string.c:7285
int rb_str_cmp(VALUE lhs, VALUE rhs)
Compares two strings, as in strcmp(3).
Definition string.c:4259
#define rb_str_dup_frozen
Just another name of rb_str_new_frozen.
Definition string.h:632
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2775
VALUE rb_str_buf_new(long capa)
Allocates a "string buffer".
Definition string.c:1735
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_exec_recursive(VALUE(*f)(VALUE g, VALUE h, int r), VALUE g, VALUE h)
"Recursion" API entry point.
Definition thread.c:5616
void rb_thread_wait_for(struct timeval time)
Identical to rb_thread_sleep(), except it takes struct timeval instead.
Definition thread.c:1445
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:2802
struct timespec rb_time_timespec(VALUE time)
Identical to rb_time_timeval(), except for return type.
Definition time.c:2973
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
#define GetOpenFile
This is an old name of RB_IO_POINTER.
Definition io.h:442
#define FMODE_WRITABLE
The IO is opened for writing.
Definition io.h:165
#define RB_IO_POINTER(obj, fp)
Queries the underlying IO pointer.
Definition io.h:436
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
Definition io.h:2
void rb_io_check_closed(rb_io_t *fptr)
This badly named function asserts that the passed IO is open.
Definition io.c:855
int len
Length of the buffer.
Definition io.h:8
char * ruby_getcwd(void)
This is our own version of getcwd(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
Definition util.c:581
#define strdup(s)
Just another name of ruby_strdup.
Definition util.h:187
#define ALLOCA_N(type, n)
Definition memory.h:292
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
#define MODET2NUM
Converts an instance of rb_cNumeric into C's mode_t.
Definition mode_t.h:33
Defines RBIMPL_ATTR_NONSTRING.
#define RBIMPL_ATTR_NONSTRING()
Wraps (or simulates) __attribute__((nonstring)).
Definition nonstring.h:36
#define OFFT2NUM
Converts a C's off_t into an instance of rb_cInteger.
Definition off_t.h:33
#define NUM2OFFT
Converts an instance of rb_cNumeric into C's off_t.
Definition off_t.h:44
#define inline
Old Visual Studio versions do not support the inline keyword, so we need to define it to be __inline.
Definition defines.h:91
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:80
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:649
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:205
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:508
const char * rb_obj_classname(VALUE obj)
Queries the name of the class of the passed object.
Definition variable.c:515
#define FilePathValue(v)
Ensures that the parameter object is a path.
Definition ruby.h:90
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define FilePathStringValue(v)
This macro actually does the same thing as FilePathValue now.
Definition ruby.h:105
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Ruby's IO, metadata and buffers.
Definition io.h:295
enum rb_io_mode mode
mode flags: FMODE_XXXs
Definition io.h:310
int fd
file descriptor.
Definition io.h:306
VALUE pathv
pathname for file
Definition io.h:322
#define UIDT2NUM
Converts a C's uid_t into an instance of rb_cInteger.
Definition uid_t.h:28
#define NUM2UIDT
Converts an instance of rb_cNumeric into C's uid_t.
Definition uid_t.h:33
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
#define RBIMPL_WARNING_IGNORED(flag)
Suppresses a warning.
#define RBIMPL_WARNING_PUSH()
Pushes compiler warning state.
#define RBIMPL_WARNING_POP()
Pops compiler warning state.