Ruby: file.c Source File

Ruby 3.3.5p100 (2024-09-03 revision ef084cc8f4958c1b6e4ead99136631bef6d8ddba)

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