Fix typos [ci skip]
[ruby-80x24.org.git] / file.c
blob2d0f32340670cfc17949da392cc1deb445b98920
1 /**********************************************************************
3 file.c -
5 $Author$
6 created at: Mon Nov 15 12:24:34 JST 1993
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
12 **********************************************************************/
14 #include "ruby/internal/config.h"
16 #ifdef _WIN32
17 # include "missing/file.h"
18 # include "ruby.h"
19 #endif
21 #include <ctype.h>
22 #include <time.h>
24 #ifdef __CYGWIN__
25 # include <windows.h>
26 # include <sys/cygwin.h>
27 # include <wchar.h>
28 #endif
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
42 #ifdef HAVE_UNISTD_H
43 # include <unistd.h>
44 #endif
46 #ifdef HAVE_SYS_TIME_H
47 # include <sys/time.h>
48 #endif
50 #ifdef HAVE_SYS_FILE_H
51 # include <sys/file.h>
52 #else
53 int flock(int, int);
54 #endif
56 #ifdef HAVE_SYS_PARAM_H
57 # include <sys/param.h>
58 #endif
59 #ifndef MAXPATHLEN
60 # define MAXPATHLEN 1024
61 #endif
63 #ifdef HAVE_UTIME_H
64 # include <utime.h>
65 #elif defined HAVE_SYS_UTIME_H
66 # include <sys/utime.h>
67 #endif
69 #ifdef HAVE_PWD_H
70 # include <pwd.h>
71 #endif
73 #ifdef HAVE_SYS_SYSMACROS_H
74 # include <sys/sysmacros.h>
75 #endif
77 #include <sys/types.h>
78 #include <sys/stat.h>
80 #ifdef HAVE_SYS_MKDEV_H
81 # include <sys/mkdev.h>
82 #endif
84 #if defined(HAVE_FCNTL_H)
85 # include <fcntl.h>
86 #endif
88 #if defined(HAVE_SYS_TIME_H)
89 # include <sys/time.h>
90 #endif
92 #if !defined HAVE_LSTAT && !defined lstat
93 # define lstat stat
94 #endif
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 rename
119 # define rename(f, t) rb_w32_urename((f), (t))
120 # undef symlink
121 # define symlink(s, l) rb_w32_usymlink((s), (l))
123 # ifdef HAVE_REALPATH
124 /* Don't use native realpath(3) on Windows, as the check for
125 absolute paths does not work for drive letters. */
126 # undef HAVE_REALPATH
127 # endif
128 #else
129 # define STAT(p, s) stat((p), (s))
130 #endif
132 #if defined _WIN32 || defined __APPLE__
133 # define USE_OSPATH 1
134 # define TO_OSPATH(str) rb_str_encode_ospath(str)
135 #else
136 # define USE_OSPATH 0
137 # define TO_OSPATH(str) (str)
138 #endif
140 /* utime may fail if time is out-of-range for the FS [ruby-dev:38277] */
141 #if defined DOSISH || defined __CYGWIN__
142 # define UTIME_EINVAL
143 #endif
145 /* Solaris 10 realpath(3) doesn't support File.realpath */
146 #if defined HAVE_REALPATH && defined __sun && defined __SVR4
147 #undef HAVE_REALPATH
148 #endif
150 #ifdef HAVE_REALPATH
151 # include <limits.h>
152 # include <stdlib.h>
153 #endif
155 #include "dln.h"
156 #include "encindex.h"
157 #include "id.h"
158 #include "internal.h"
159 #include "internal/compilers.h"
160 #include "internal/dir.h"
161 #include "internal/error.h"
162 #include "internal/file.h"
163 #include "internal/io.h"
164 #include "internal/load.h"
165 #include "internal/object.h"
166 #include "internal/process.h"
167 #include "internal/thread.h"
168 #include "internal/vm.h"
169 #include "ruby/encoding.h"
170 #include "ruby/io.h"
171 #include "ruby/thread.h"
172 #include "ruby/util.h"
174 VALUE rb_cFile;
175 VALUE rb_mFileTest;
176 VALUE rb_cStat;
178 static VALUE
179 file_path_convert(VALUE name)
181 #ifndef _WIN32 /* non Windows == Unix */
182 int fname_encidx = ENCODING_GET(name);
183 int fs_encidx;
184 if (ENCINDEX_US_ASCII != fname_encidx &&
185 ENCINDEX_ASCII != fname_encidx &&
186 (fs_encidx = rb_filesystem_encindex()) != fname_encidx &&
187 rb_default_internal_encoding() &&
188 !rb_enc_str_asciionly_p(name)) {
189 /* Don't call rb_filesystem_encoding() before US-ASCII and ASCII-8BIT */
190 /* fs_encoding should be ascii compatible */
191 rb_encoding *fname_encoding = rb_enc_from_index(fname_encidx);
192 rb_encoding *fs_encoding = rb_enc_from_index(fs_encidx);
193 name = rb_str_conv_enc(name, fname_encoding, fs_encoding);
195 #endif
196 return name;
199 static rb_encoding *
200 check_path_encoding(VALUE str)
202 rb_encoding *enc = rb_enc_get(str);
203 if (!rb_enc_asciicompat(enc)) {
204 rb_raise(rb_eEncCompatError, "path name must be ASCII-compatible (%s): %"PRIsVALUE,
205 rb_enc_name(enc), rb_str_inspect(str));
207 return enc;
210 VALUE
211 rb_get_path_check_to_string(VALUE obj)
213 VALUE tmp;
214 ID to_path;
216 if (RB_TYPE_P(obj, T_STRING)) {
217 return obj;
219 CONST_ID(to_path, "to_path");
220 tmp = rb_check_funcall_default(obj, to_path, 0, 0, obj);
221 StringValue(tmp);
222 return tmp;
225 VALUE
226 rb_get_path_check_convert(VALUE obj)
228 obj = file_path_convert(obj);
230 check_path_encoding(obj);
231 if (!rb_str_to_cstr(obj)) {
232 rb_raise(rb_eArgError, "path name contains null byte");
235 return rb_str_new4(obj);
238 VALUE
239 rb_get_path_no_checksafe(VALUE obj)
241 return rb_get_path(obj);
244 VALUE
245 rb_get_path(VALUE obj)
247 return rb_get_path_check_convert(rb_get_path_check_to_string(obj));
250 VALUE
251 rb_str_encode_ospath(VALUE path)
253 #if USE_OSPATH
254 int encidx = ENCODING_GET(path);
255 #if 0 && defined _WIN32
256 if (encidx == ENCINDEX_ASCII) {
257 encidx = rb_filesystem_encindex();
259 #endif
260 if (encidx != ENCINDEX_ASCII && encidx != ENCINDEX_UTF_8) {
261 rb_encoding *enc = rb_enc_from_index(encidx);
262 rb_encoding *utf8 = rb_utf8_encoding();
263 path = rb_str_conv_enc(path, enc, utf8);
265 #endif
266 return path;
269 #ifdef __APPLE__
270 # define NORMALIZE_UTF8PATH 1
271 static VALUE
272 rb_str_append_normalized_ospath(VALUE str, const char *ptr, long len)
274 CFIndex buflen = 0;
275 CFRange all;
276 CFStringRef s = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault,
277 (const UInt8 *)ptr, len,
278 kCFStringEncodingUTF8, FALSE,
279 kCFAllocatorNull);
280 CFMutableStringRef m = CFStringCreateMutableCopy(kCFAllocatorDefault, len, s);
281 long oldlen = RSTRING_LEN(str);
283 CFStringNormalize(m, kCFStringNormalizationFormC);
284 all = CFRangeMake(0, CFStringGetLength(m));
285 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE, NULL, 0, &buflen);
286 rb_str_modify_expand(str, buflen);
287 CFStringGetBytes(m, all, kCFStringEncodingUTF8, '?', FALSE,
288 (UInt8 *)(RSTRING_PTR(str) + oldlen), buflen, &buflen);
289 rb_str_set_len(str, oldlen + buflen);
290 CFRelease(m);
291 CFRelease(s);
292 return str;
295 VALUE
296 rb_str_normalize_ospath(const char *ptr, long len)
298 const char *p = ptr;
299 const char *e = ptr + len;
300 const char *p1 = p;
301 VALUE str = rb_str_buf_new(len);
302 rb_encoding *enc = rb_utf8_encoding();
303 rb_enc_associate(str, enc);
305 while (p < e) {
306 int l, c;
307 int r = rb_enc_precise_mbclen(p, e, enc);
308 if (!MBCLEN_CHARFOUND_P(r)) {
309 /* invalid byte shall not happen but */
310 static const char invalid[3] = "\xEF\xBF\xBD";
311 rb_str_append_normalized_ospath(str, p1, p-p1);
312 rb_str_cat(str, invalid, sizeof(invalid));
313 p += 1;
314 p1 = p;
315 continue;
317 l = MBCLEN_CHARFOUND_LEN(r);
318 c = rb_enc_mbc_to_codepoint(p, e, enc);
319 if ((0x2000 <= c && c <= 0x2FFF) || (0xF900 <= c && c <= 0xFAFF) ||
320 (0x2F800 <= c && c <= 0x2FAFF)) {
321 if (p - p1 > 0) {
322 rb_str_append_normalized_ospath(str, p1, p-p1);
324 rb_str_cat(str, p, l);
325 p += l;
326 p1 = p;
328 else {
329 p += l;
332 if (p - p1 > 0) {
333 rb_str_append_normalized_ospath(str, p1, p-p1);
336 return str;
339 static int
340 ignored_char_p(const char *p, const char *e, rb_encoding *enc)
342 unsigned char c;
343 if (p+3 > e) return 0;
344 switch ((unsigned char)*p) {
345 case 0xe2:
346 switch ((unsigned char)p[1]) {
347 case 0x80:
348 c = (unsigned char)p[2];
349 /* c >= 0x200c && c <= 0x200f */
350 if (c >= 0x8c && c <= 0x8f) return 3;
351 /* c >= 0x202a && c <= 0x202e */
352 if (c >= 0xaa && c <= 0xae) return 3;
353 return 0;
354 case 0x81:
355 c = (unsigned char)p[2];
356 /* c >= 0x206a && c <= 0x206f */
357 if (c >= 0xaa && c <= 0xaf) return 3;
358 return 0;
360 break;
361 case 0xef:
362 /* c == 0xfeff */
363 if ((unsigned char)p[1] == 0xbb &&
364 (unsigned char)p[2] == 0xbf)
365 return 3;
366 break;
368 return 0;
370 #else
371 # define NORMALIZE_UTF8PATH 0
372 #endif
374 #define apply2args(n) (rb_check_arity(argc, n, UNLIMITED_ARGUMENTS), argc-=n)
376 struct apply_filename {
377 const char *ptr;
378 VALUE path;
381 struct apply_arg {
382 int i;
383 int argc;
384 int errnum;
385 int (*func)(const char *, void *);
386 void *arg;
387 struct apply_filename fn[FLEX_ARY_LEN];
390 static void *
391 no_gvl_apply2files(void *ptr)
393 struct apply_arg *aa = ptr;
395 for (aa->i = 0; aa->i < aa->argc; aa->i++) {
396 if (aa->func(aa->fn[aa->i].ptr, aa->arg) < 0) {
397 aa->errnum = errno;
398 break;
401 return 0;
404 #ifdef UTIME_EINVAL
405 NORETURN(static void utime_failed(struct apply_arg *));
406 static int utime_internal(const char *, void *);
407 #endif
409 static VALUE
410 apply2files(int (*func)(const char *, void *), int argc, VALUE *argv, void *arg)
412 VALUE v;
413 const size_t size = sizeof(struct apply_filename);
414 const long len = (long)(offsetof(struct apply_arg, fn) + (size * argc));
415 struct apply_arg *aa = ALLOCV(v, len);
417 aa->errnum = 0;
418 aa->argc = argc;
419 aa->arg = arg;
420 aa->func = func;
422 for (aa->i = 0; aa->i < argc; aa->i++) {
423 VALUE path = rb_get_path(argv[aa->i]);
425 path = rb_str_encode_ospath(path);
426 aa->fn[aa->i].ptr = RSTRING_PTR(path);
427 aa->fn[aa->i].path = path;
430 rb_thread_call_without_gvl(no_gvl_apply2files, aa, RUBY_UBF_IO, 0);
431 if (aa->errnum) {
432 #ifdef UTIME_EINVAL
433 if (func == utime_internal) {
434 utime_failed(aa);
436 #endif
437 rb_syserr_fail_path(aa->errnum, aa->fn[aa->i].path);
439 if (v) {
440 ALLOCV_END(v);
442 return LONG2FIX(argc);
446 * call-seq:
447 * file.path -> filename
448 * file.to_path -> filename
450 * Returns the pathname used to create <i>file</i> as a string. Does
451 * not normalize the name.
453 * The pathname may not point to the file corresponding to <i>file</i>.
454 * For instance, the pathname becomes void when the file has been
455 * moved or deleted.
457 * This method raises IOError for a <i>file</i> created using
458 * File::Constants::TMPFILE because they don't have a pathname.
460 * File.new("testfile").path #=> "testfile"
461 * File.new("/tmp/../tmp/xxx", "w").path #=> "/tmp/../tmp/xxx"
465 static VALUE
466 rb_file_path(VALUE obj)
468 rb_io_t *fptr;
470 fptr = RFILE(rb_io_taint_check(obj))->fptr;
471 rb_io_check_initialized(fptr);
473 if (NIL_P(fptr->pathv)) {
474 rb_raise(rb_eIOError, "File is unnamed (TMPFILE?)");
477 return rb_str_dup(fptr->pathv);
480 static size_t
481 stat_memsize(const void *p)
483 return sizeof(struct stat);
486 static const rb_data_type_t stat_data_type = {
487 "stat",
488 {NULL, RUBY_TYPED_DEFAULT_FREE, stat_memsize,},
489 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
492 static VALUE
493 stat_new_0(VALUE klass, const struct stat *st)
495 struct stat *nst = 0;
496 VALUE obj = TypedData_Wrap_Struct(klass, &stat_data_type, 0);
498 if (st) {
499 nst = ALLOC(struct stat);
500 *nst = *st;
501 RTYPEDDATA_DATA(obj) = nst;
503 return obj;
506 VALUE
507 rb_stat_new(const struct stat *st)
509 return stat_new_0(rb_cStat, st);
512 static struct stat*
513 get_stat(VALUE self)
515 struct stat* st;
516 TypedData_Get_Struct(self, struct stat, &stat_data_type, st);
517 if (!st) rb_raise(rb_eTypeError, "uninitialized File::Stat");
518 return st;
521 static struct timespec stat_mtimespec(const struct stat *st);
524 * call-seq:
525 * stat <=> other_stat -> -1, 0, 1, nil
527 * Compares File::Stat objects by comparing their respective modification
528 * times.
530 * +nil+ is returned if +other_stat+ is not a File::Stat object
532 * f1 = File.new("f1", "w")
533 * sleep 1
534 * f2 = File.new("f2", "w")
535 * f1.stat <=> f2.stat #=> -1
538 static VALUE
539 rb_stat_cmp(VALUE self, VALUE other)
541 if (rb_obj_is_kind_of(other, rb_obj_class(self))) {
542 struct timespec ts1 = stat_mtimespec(get_stat(self));
543 struct timespec ts2 = stat_mtimespec(get_stat(other));
544 if (ts1.tv_sec == ts2.tv_sec) {
545 if (ts1.tv_nsec == ts2.tv_nsec) return INT2FIX(0);
546 if (ts1.tv_nsec < ts2.tv_nsec) return INT2FIX(-1);
547 return INT2FIX(1);
549 if (ts1.tv_sec < ts2.tv_sec) return INT2FIX(-1);
550 return INT2FIX(1);
552 return Qnil;
555 #define ST2UINT(val) ((val) & ~(~1UL << (sizeof(val) * CHAR_BIT - 1)))
557 #ifndef NUM2DEVT
558 # define NUM2DEVT(v) NUM2UINT(v)
559 #endif
560 #ifndef DEVT2NUM
561 # define DEVT2NUM(v) UINT2NUM(v)
562 #endif
563 #ifndef PRI_DEVT_PREFIX
564 # define PRI_DEVT_PREFIX ""
565 #endif
568 * call-seq:
569 * stat.dev -> integer
571 * Returns an integer representing the device on which <i>stat</i>
572 * resides.
574 * File.stat("testfile").dev #=> 774
577 static VALUE
578 rb_stat_dev(VALUE self)
580 #if SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_DEV_T
581 return DEVT2NUM(get_stat(self)->st_dev);
582 #elif SIZEOF_STRUCT_STAT_ST_DEV <= SIZEOF_LONG
583 return ULONG2NUM(get_stat(self)->st_dev);
584 #else
585 return ULL2NUM(get_stat(self)->st_dev);
586 #endif
590 * call-seq:
591 * stat.dev_major -> integer
593 * Returns the major part of <code>File_Stat#dev</code> or
594 * <code>nil</code>.
596 * File.stat("/dev/fd1").dev_major #=> 2
597 * File.stat("/dev/tty").dev_major #=> 5
600 static VALUE
601 rb_stat_dev_major(VALUE self)
603 #if defined(major)
604 return UINT2NUM(major(get_stat(self)->st_dev));
605 #else
606 return Qnil;
607 #endif
611 * call-seq:
612 * stat.dev_minor -> integer
614 * Returns the minor part of <code>File_Stat#dev</code> or
615 * <code>nil</code>.
617 * File.stat("/dev/fd1").dev_minor #=> 1
618 * File.stat("/dev/tty").dev_minor #=> 0
621 static VALUE
622 rb_stat_dev_minor(VALUE self)
624 #if defined(minor)
625 return UINT2NUM(minor(get_stat(self)->st_dev));
626 #else
627 return Qnil;
628 #endif
632 * call-seq:
633 * stat.ino -> integer
635 * Returns the inode number for <i>stat</i>.
637 * File.stat("testfile").ino #=> 1083669
641 static VALUE
642 rb_stat_ino(VALUE self)
644 #ifdef HAVE_STRUCT_STAT_ST_INOHIGH
645 /* assume INTEGER_PACK_LSWORD_FIRST and st_inohigh is just next of st_ino */
646 return rb_integer_unpack(&get_stat(self)->st_ino, 2,
647 SIZEOF_STRUCT_STAT_ST_INO, 0,
648 INTEGER_PACK_LSWORD_FIRST|INTEGER_PACK_NATIVE_BYTE_ORDER|
649 INTEGER_PACK_2COMP);
650 #elif SIZEOF_STRUCT_STAT_ST_INO > SIZEOF_LONG
651 return ULL2NUM(get_stat(self)->st_ino);
652 #else
653 return ULONG2NUM(get_stat(self)->st_ino);
654 #endif
658 * call-seq:
659 * stat.mode -> integer
661 * Returns an integer representing the permission bits of
662 * <i>stat</i>. The meaning of the bits is platform dependent; on
663 * Unix systems, see <code>stat(2)</code>.
665 * File.chmod(0644, "testfile") #=> 1
666 * s = File.stat("testfile")
667 * sprintf("%o", s.mode) #=> "100644"
670 static VALUE
671 rb_stat_mode(VALUE self)
673 return UINT2NUM(ST2UINT(get_stat(self)->st_mode));
677 * call-seq:
678 * stat.nlink -> integer
680 * Returns the number of hard links to <i>stat</i>.
682 * File.stat("testfile").nlink #=> 1
683 * File.link("testfile", "testfile.bak") #=> 0
684 * File.stat("testfile").nlink #=> 2
688 static VALUE
689 rb_stat_nlink(VALUE self)
691 /* struct stat::st_nlink is nlink_t in POSIX. Not the case for Windows. */
692 const struct stat *ptr = get_stat(self);
694 if (sizeof(ptr->st_nlink) <= sizeof(int)) {
695 return UINT2NUM((unsigned)ptr->st_nlink);
697 else if (sizeof(ptr->st_nlink) == sizeof(long)) {
698 return ULONG2NUM((unsigned long)ptr->st_nlink);
700 else if (sizeof(ptr->st_nlink) == sizeof(LONG_LONG)) {
701 return ULL2NUM((unsigned LONG_LONG)ptr->st_nlink);
703 else {
704 rb_bug(":FIXME: don't know what to do");
709 * call-seq:
710 * stat.uid -> integer
712 * Returns the numeric user id of the owner of <i>stat</i>.
714 * File.stat("testfile").uid #=> 501
718 static VALUE
719 rb_stat_uid(VALUE self)
721 return UIDT2NUM(get_stat(self)->st_uid);
725 * call-seq:
726 * stat.gid -> integer
728 * Returns the numeric group id of the owner of <i>stat</i>.
730 * File.stat("testfile").gid #=> 500
734 static VALUE
735 rb_stat_gid(VALUE self)
737 return GIDT2NUM(get_stat(self)->st_gid);
741 * call-seq:
742 * stat.rdev -> integer or nil
744 * Returns an integer representing the device type on which
745 * <i>stat</i> resides. Returns <code>nil</code> if the operating
746 * system doesn't support this feature.
748 * File.stat("/dev/fd1").rdev #=> 513
749 * File.stat("/dev/tty").rdev #=> 1280
752 static VALUE
753 rb_stat_rdev(VALUE self)
755 #ifdef HAVE_STRUCT_STAT_ST_RDEV
756 # if SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_DEV_T
757 return DEVT2NUM(get_stat(self)->st_rdev);
758 # elif SIZEOF_STRUCT_STAT_ST_RDEV <= SIZEOF_LONG
759 return ULONG2NUM(get_stat(self)->st_rdev);
760 # else
761 return ULL2NUM(get_stat(self)->st_rdev);
762 # endif
763 #else
764 return Qnil;
765 #endif
769 * call-seq:
770 * stat.rdev_major -> integer
772 * Returns the major part of <code>File_Stat#rdev</code> or
773 * <code>nil</code>.
775 * File.stat("/dev/fd1").rdev_major #=> 2
776 * File.stat("/dev/tty").rdev_major #=> 5
779 static VALUE
780 rb_stat_rdev_major(VALUE self)
782 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(major)
783 return UINT2NUM(major(get_stat(self)->st_rdev));
784 #else
785 return Qnil;
786 #endif
790 * call-seq:
791 * stat.rdev_minor -> integer
793 * Returns the minor part of <code>File_Stat#rdev</code> or
794 * <code>nil</code>.
796 * File.stat("/dev/fd1").rdev_minor #=> 1
797 * File.stat("/dev/tty").rdev_minor #=> 0
800 static VALUE
801 rb_stat_rdev_minor(VALUE self)
803 #if defined(HAVE_STRUCT_STAT_ST_RDEV) && defined(minor)
804 return UINT2NUM(minor(get_stat(self)->st_rdev));
805 #else
806 return Qnil;
807 #endif
811 * call-seq:
812 * stat.size -> integer
814 * Returns the size of <i>stat</i> in bytes.
816 * File.stat("testfile").size #=> 66
819 static VALUE
820 rb_stat_size(VALUE self)
822 return OFFT2NUM(get_stat(self)->st_size);
826 * call-seq:
827 * stat.blksize -> integer or nil
829 * Returns the native file system's block size. Will return <code>nil</code>
830 * on platforms that don't support this information.
832 * File.stat("testfile").blksize #=> 4096
836 static VALUE
837 rb_stat_blksize(VALUE self)
839 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
840 return ULONG2NUM(get_stat(self)->st_blksize);
841 #else
842 return Qnil;
843 #endif
847 * call-seq:
848 * stat.blocks -> integer or nil
850 * Returns the number of native file system blocks allocated for this
851 * file, or <code>nil</code> if the operating system doesn't
852 * support this feature.
854 * File.stat("testfile").blocks #=> 2
857 static VALUE
858 rb_stat_blocks(VALUE self)
860 #ifdef HAVE_STRUCT_STAT_ST_BLOCKS
861 # if SIZEOF_STRUCT_STAT_ST_BLOCKS > SIZEOF_LONG
862 return ULL2NUM(get_stat(self)->st_blocks);
863 # else
864 return ULONG2NUM(get_stat(self)->st_blocks);
865 # endif
866 #else
867 return Qnil;
868 #endif
871 static struct timespec
872 stat_atimespec(const struct stat *st)
874 struct timespec ts;
875 ts.tv_sec = st->st_atime;
876 #if defined(HAVE_STRUCT_STAT_ST_ATIM)
877 ts.tv_nsec = st->st_atim.tv_nsec;
878 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
879 ts.tv_nsec = st->st_atimespec.tv_nsec;
880 #elif defined(HAVE_STRUCT_STAT_ST_ATIMENSEC)
881 ts.tv_nsec = (long)st->st_atimensec;
882 #else
883 ts.tv_nsec = 0;
884 #endif
885 return ts;
888 static VALUE
889 stat_time(const struct timespec ts)
891 return rb_time_nano_new(ts.tv_sec, ts.tv_nsec);
894 static VALUE
895 stat_atime(const struct stat *st)
897 return stat_time(stat_atimespec(st));
900 static struct timespec
901 stat_mtimespec(const struct stat *st)
903 struct timespec ts;
904 ts.tv_sec = st->st_mtime;
905 #if defined(HAVE_STRUCT_STAT_ST_MTIM)
906 ts.tv_nsec = st->st_mtim.tv_nsec;
907 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
908 ts.tv_nsec = st->st_mtimespec.tv_nsec;
909 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
910 ts.tv_nsec = (long)st->st_mtimensec;
911 #else
912 ts.tv_nsec = 0;
913 #endif
914 return ts;
917 static VALUE
918 stat_mtime(const struct stat *st)
920 return stat_time(stat_mtimespec(st));
923 static struct timespec
924 stat_ctimespec(const struct stat *st)
926 struct timespec ts;
927 ts.tv_sec = st->st_ctime;
928 #if defined(HAVE_STRUCT_STAT_ST_CTIM)
929 ts.tv_nsec = st->st_ctim.tv_nsec;
930 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
931 ts.tv_nsec = st->st_ctimespec.tv_nsec;
932 #elif defined(HAVE_STRUCT_STAT_ST_CTIMENSEC)
933 ts.tv_nsec = (long)st->st_ctimensec;
934 #else
935 ts.tv_nsec = 0;
936 #endif
937 return ts;
940 static VALUE
941 stat_ctime(const struct stat *st)
943 return stat_time(stat_ctimespec(st));
946 #define HAVE_STAT_BIRTHTIME
947 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
948 typedef struct stat statx_data;
949 static VALUE
950 stat_birthtime(const struct stat *st)
952 const struct timespec *ts = &st->st_birthtimespec;
953 return rb_time_nano_new(ts->tv_sec, ts->tv_nsec);
955 #elif defined(_WIN32)
956 typedef struct stat statx_data;
957 # define stat_birthtime stat_ctime
958 #else
959 # undef HAVE_STAT_BIRTHTIME
960 #endif
963 * call-seq:
964 * stat.atime -> time
966 * Returns the last access time for this file as an object of class
967 * Time.
969 * File.stat("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
973 static VALUE
974 rb_stat_atime(VALUE self)
976 return stat_atime(get_stat(self));
980 * call-seq:
981 * stat.mtime -> aTime
983 * Returns the modification time of <i>stat</i>.
985 * File.stat("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
989 static VALUE
990 rb_stat_mtime(VALUE self)
992 return stat_mtime(get_stat(self));
996 * call-seq:
997 * stat.ctime -> aTime
999 * Returns the change time for <i>stat</i> (that is, the time
1000 * directory information about the file was changed, not the file
1001 * itself).
1003 * Note that on Windows (NTFS), returns creation time (birth time).
1005 * File.stat("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
1009 static VALUE
1010 rb_stat_ctime(VALUE self)
1012 return stat_ctime(get_stat(self));
1015 #if defined(HAVE_STAT_BIRTHTIME)
1017 * call-seq:
1018 * stat.birthtime -> aTime
1020 * Returns the birth time for <i>stat</i>.
1022 * If the platform doesn't have birthtime, raises NotImplementedError.
1024 * File.write("testfile", "foo")
1025 * sleep 10
1026 * File.write("testfile", "bar")
1027 * sleep 10
1028 * File.chmod(0644, "testfile")
1029 * sleep 10
1030 * File.read("testfile")
1031 * File.stat("testfile").birthtime #=> 2014-02-24 11:19:17 +0900
1032 * File.stat("testfile").mtime #=> 2014-02-24 11:19:27 +0900
1033 * File.stat("testfile").ctime #=> 2014-02-24 11:19:37 +0900
1034 * File.stat("testfile").atime #=> 2014-02-24 11:19:47 +0900
1038 static VALUE
1039 rb_stat_birthtime(VALUE self)
1041 return stat_birthtime(get_stat(self));
1043 #else
1044 # define rb_stat_birthtime rb_f_notimplement
1045 #endif
1048 * call-seq:
1049 * stat.inspect -> string
1051 * Produce a nicely formatted description of <i>stat</i>.
1053 * File.stat("/etc/passwd").inspect
1054 * #=> "#<File::Stat dev=0xe000005, ino=1078078, mode=0100644,
1055 * # nlink=1, uid=0, gid=0, rdev=0x0, size=1374, blksize=4096,
1056 * # blocks=8, atime=Wed Dec 10 10:16:12 CST 2003,
1057 * # mtime=Fri Sep 12 15:41:41 CDT 2003,
1058 * # ctime=Mon Oct 27 11:20:27 CST 2003,
1059 * # birthtime=Mon Aug 04 08:13:49 CDT 2003>"
1062 static VALUE
1063 rb_stat_inspect(VALUE self)
1065 VALUE str;
1066 size_t i;
1067 static const struct {
1068 const char *name;
1069 VALUE (*func)(VALUE);
1070 } member[] = {
1071 {"dev", rb_stat_dev},
1072 {"ino", rb_stat_ino},
1073 {"mode", rb_stat_mode},
1074 {"nlink", rb_stat_nlink},
1075 {"uid", rb_stat_uid},
1076 {"gid", rb_stat_gid},
1077 {"rdev", rb_stat_rdev},
1078 {"size", rb_stat_size},
1079 {"blksize", rb_stat_blksize},
1080 {"blocks", rb_stat_blocks},
1081 {"atime", rb_stat_atime},
1082 {"mtime", rb_stat_mtime},
1083 {"ctime", rb_stat_ctime},
1084 #if defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1085 {"birthtime", rb_stat_birthtime},
1086 #endif
1089 struct stat* st;
1090 TypedData_Get_Struct(self, struct stat, &stat_data_type, st);
1091 if (!st) {
1092 return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
1095 str = rb_str_buf_new2("#<");
1096 rb_str_buf_cat2(str, rb_obj_classname(self));
1097 rb_str_buf_cat2(str, " ");
1099 for (i = 0; i < sizeof(member)/sizeof(member[0]); i++) {
1100 VALUE v;
1102 if (i > 0) {
1103 rb_str_buf_cat2(str, ", ");
1105 rb_str_buf_cat2(str, member[i].name);
1106 rb_str_buf_cat2(str, "=");
1107 v = (*member[i].func)(self);
1108 if (i == 2) { /* mode */
1109 rb_str_catf(str, "0%lo", (unsigned long)NUM2ULONG(v));
1111 else if (i == 0 || i == 6) { /* dev/rdev */
1112 rb_str_catf(str, "0x%"PRI_DEVT_PREFIX"x", NUM2DEVT(v));
1114 else {
1115 rb_str_append(str, rb_inspect(v));
1118 rb_str_buf_cat2(str, ">");
1120 return str;
1123 typedef struct no_gvl_stat_data {
1124 struct stat *st;
1125 union {
1126 const char *path;
1127 int fd;
1128 } file;
1129 } no_gvl_stat_data;
1131 static VALUE
1132 no_gvl_fstat(void *data)
1134 no_gvl_stat_data *arg = data;
1135 return (VALUE)fstat(arg->file.fd, arg->st);
1138 static int
1139 fstat_without_gvl(int fd, struct stat *st)
1141 no_gvl_stat_data data;
1143 data.file.fd = fd;
1144 data.st = st;
1146 return (int)(VALUE)rb_thread_io_blocking_region(no_gvl_fstat, &data, fd);
1149 static void *
1150 no_gvl_stat(void * data)
1152 no_gvl_stat_data *arg = data;
1153 return (void *)(VALUE)STAT(arg->file.path, arg->st);
1156 static int
1157 stat_without_gvl(const char *path, struct stat *st)
1159 no_gvl_stat_data data;
1161 data.file.path = path;
1162 data.st = st;
1164 return (int)(VALUE)rb_thread_call_without_gvl(no_gvl_stat, &data,
1165 RUBY_UBF_IO, NULL);
1168 #if !defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC) && \
1169 defined(HAVE_STRUCT_STATX_STX_BTIME)
1171 # ifndef HAVE_STATX
1172 # ifdef HAVE_SYSCALL_H
1173 # include <syscall.h>
1174 # elif defined HAVE_SYS_SYSCALL_H
1175 # include <sys/syscall.h>
1176 # endif
1177 # if defined __linux__
1178 # include <linux/stat.h>
1179 static inline int
1180 statx(int dirfd, const char *pathname, int flags,
1181 unsigned int mask, struct statx *statxbuf)
1183 return (int)syscall(__NR_statx, dirfd, pathname, flags, mask, statxbuf);
1185 # endif
1186 # endif
1188 typedef struct no_gvl_statx_data {
1189 struct statx *stx;
1190 int fd;
1191 const char *path;
1192 int flags;
1193 unsigned int mask;
1194 } no_gvl_statx_data;
1196 static VALUE
1197 io_blocking_statx(void *data)
1199 no_gvl_statx_data *arg = data;
1200 return (VALUE)statx(arg->fd, arg->path, arg->flags, arg->mask, arg->stx);
1203 static void *
1204 no_gvl_statx(void *data)
1206 return (void *)io_blocking_statx(data);
1209 static int
1210 statx_without_gvl(const char *path, struct statx *stx, unsigned int mask)
1212 no_gvl_statx_data data = {stx, AT_FDCWD, path, 0, mask};
1214 /* call statx(2) with pathname */
1215 return (int)(VALUE)rb_thread_call_without_gvl(no_gvl_statx, &data,
1216 RUBY_UBF_IO, NULL);
1219 static int
1220 fstatx_without_gvl(int fd, struct statx *stx, unsigned int mask)
1222 no_gvl_statx_data data = {stx, fd, "", AT_EMPTY_PATH, mask};
1224 /* call statx(2) with fd */
1225 return (int)rb_thread_io_blocking_region(io_blocking_statx, &data, fd);
1228 static int
1229 rb_statx(VALUE file, struct statx *stx, unsigned int mask)
1231 VALUE tmp;
1232 int result;
1234 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1235 if (!NIL_P(tmp)) {
1236 rb_io_t *fptr;
1237 GetOpenFile(tmp, fptr);
1238 result = fstatx_without_gvl(fptr->fd, stx, mask);
1239 file = tmp;
1241 else {
1242 FilePathValue(file);
1243 file = rb_str_encode_ospath(file);
1244 result = statx_without_gvl(RSTRING_PTR(file), stx, mask);
1246 RB_GC_GUARD(file);
1247 return result;
1250 # define statx_has_birthtime(st) ((st)->stx_mask & STATX_BTIME)
1252 NORETURN(static void statx_notimplement(const char *field_name));
1254 /* rb_notimplement() shows "function is unimplemented on this machine".
1255 It is not applicable to statx which behavior depends on the filesystem. */
1256 static void
1257 statx_notimplement(const char *field_name)
1259 rb_raise(rb_eNotImpError,
1260 "%s is unimplemented on this filesystem",
1261 field_name);
1264 static VALUE
1265 statx_birthtime(const struct statx *stx, VALUE fname)
1267 if (!statx_has_birthtime(stx)) {
1268 /* birthtime is not supported on the filesystem */
1269 statx_notimplement("birthtime");
1271 return rb_time_nano_new((time_t)stx->stx_btime.tv_sec, stx->stx_btime.tv_nsec);
1274 typedef struct statx statx_data;
1275 # define HAVE_STAT_BIRTHTIME
1277 #elif defined(HAVE_STAT_BIRTHTIME)
1278 # define statx_without_gvl(path, st, mask) stat_without_gvl(path, st)
1279 # define fstatx_without_gvl(fd, st, mask) fstat_without_gvl(fd, st)
1280 # define statx_birthtime(st, fname) stat_birthtime(st)
1281 # define statx_has_birthtime(st) 1
1282 # define rb_statx(file, st, mask) rb_stat(file, st)
1283 #else
1284 # define statx_has_birthtime(st) 0
1285 #endif
1287 static int
1288 rb_stat(VALUE file, struct stat *st)
1290 VALUE tmp;
1291 int result;
1293 tmp = rb_check_convert_type_with_id(file, T_FILE, "IO", idTo_io);
1294 if (!NIL_P(tmp)) {
1295 rb_io_t *fptr;
1297 GetOpenFile(tmp, fptr);
1298 result = fstat_without_gvl(fptr->fd, st);
1299 file = tmp;
1301 else {
1302 FilePathValue(file);
1303 file = rb_str_encode_ospath(file);
1304 result = stat_without_gvl(RSTRING_PTR(file), st);
1306 RB_GC_GUARD(file);
1307 return result;
1311 * call-seq:
1312 * File.stat(file_name) -> stat
1314 * Returns a File::Stat object for the named file (see File::Stat).
1316 * File.stat("testfile").mtime #=> Tue Apr 08 12:58:04 CDT 2003
1320 static VALUE
1321 rb_file_s_stat(VALUE klass, VALUE fname)
1323 struct stat st;
1325 FilePathValue(fname);
1326 fname = rb_str_encode_ospath(fname);
1327 if (stat_without_gvl(RSTRING_PTR(fname), &st) < 0) {
1328 rb_sys_fail_path(fname);
1330 return rb_stat_new(&st);
1334 * call-seq:
1335 * ios.stat -> stat
1337 * Returns status information for <em>ios</em> as an object of type
1338 * File::Stat.
1340 * f = File.new("testfile")
1341 * s = f.stat
1342 * "%o" % s.mode #=> "100644"
1343 * s.blksize #=> 4096
1344 * s.atime #=> Wed Apr 09 08:53:54 CDT 2003
1348 static VALUE
1349 rb_io_stat(VALUE obj)
1351 rb_io_t *fptr;
1352 struct stat st;
1354 GetOpenFile(obj, fptr);
1355 if (fstat(fptr->fd, &st) == -1) {
1356 rb_sys_fail_path(fptr->pathv);
1358 return rb_stat_new(&st);
1361 #ifdef HAVE_LSTAT
1362 static void *
1363 no_gvl_lstat(void *ptr)
1365 no_gvl_stat_data *arg = ptr;
1366 return (void *)(VALUE)lstat(arg->file.path, arg->st);
1369 static int
1370 lstat_without_gvl(const char *path, struct stat *st)
1372 no_gvl_stat_data data;
1374 data.file.path = path;
1375 data.st = st;
1377 return (int)(VALUE)rb_thread_call_without_gvl(no_gvl_lstat, &data,
1378 RUBY_UBF_IO, NULL);
1380 #endif /* HAVE_LSTAT */
1383 * call-seq:
1384 * File.lstat(file_name) -> stat
1386 * Same as File::stat, but does not follow the last symbolic link.
1387 * Instead, reports on the link itself.
1389 * File.symlink("testfile", "link2test") #=> 0
1390 * File.stat("testfile").size #=> 66
1391 * File.lstat("link2test").size #=> 8
1392 * File.stat("link2test").size #=> 66
1396 static VALUE
1397 rb_file_s_lstat(VALUE klass, VALUE fname)
1399 #ifdef HAVE_LSTAT
1400 struct stat st;
1402 FilePathValue(fname);
1403 fname = rb_str_encode_ospath(fname);
1404 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
1405 rb_sys_fail_path(fname);
1407 return rb_stat_new(&st);
1408 #else
1409 return rb_file_s_stat(klass, fname);
1410 #endif
1414 * call-seq:
1415 * file.lstat -> stat
1417 * Same as IO#stat, but does not follow the last symbolic link.
1418 * Instead, reports on the link itself.
1420 * File.symlink("testfile", "link2test") #=> 0
1421 * File.stat("testfile").size #=> 66
1422 * f = File.new("link2test")
1423 * f.lstat.size #=> 8
1424 * f.stat.size #=> 66
1427 static VALUE
1428 rb_file_lstat(VALUE obj)
1430 #ifdef HAVE_LSTAT
1431 rb_io_t *fptr;
1432 struct stat st;
1433 VALUE path;
1435 GetOpenFile(obj, fptr);
1436 if (NIL_P(fptr->pathv)) return Qnil;
1437 path = rb_str_encode_ospath(fptr->pathv);
1438 if (lstat_without_gvl(RSTRING_PTR(path), &st) == -1) {
1439 rb_sys_fail_path(fptr->pathv);
1441 return rb_stat_new(&st);
1442 #else
1443 return rb_io_stat(obj);
1444 #endif
1447 static int
1448 rb_group_member(GETGROUPS_T gid)
1450 #if defined(_WIN32) || !defined(HAVE_GETGROUPS)
1451 return FALSE;
1452 #else
1453 int rv = FALSE;
1454 int groups;
1455 VALUE v = 0;
1456 GETGROUPS_T *gary;
1457 int anum = -1;
1459 if (getgid() == gid || getegid() == gid)
1460 return TRUE;
1462 groups = getgroups(0, NULL);
1463 gary = ALLOCV_N(GETGROUPS_T, v, groups);
1464 anum = getgroups(groups, gary);
1465 while (--anum >= 0) {
1466 if (gary[anum] == gid) {
1467 rv = TRUE;
1468 break;
1471 if (v)
1472 ALLOCV_END(v);
1474 return rv;
1475 #endif
1478 #ifndef S_IXUGO
1479 # define S_IXUGO (S_IXUSR | S_IXGRP | S_IXOTH)
1480 #endif
1482 #if defined(S_IXGRP) && !defined(_WIN32) && !defined(__CYGWIN__)
1483 #define USE_GETEUID 1
1484 #endif
1486 #ifndef HAVE_EACCESS
1488 eaccess(const char *path, int mode)
1490 #ifdef USE_GETEUID
1491 struct stat st;
1492 rb_uid_t euid;
1494 euid = geteuid();
1496 /* no setuid nor setgid. run shortcut. */
1497 if (getuid() == euid && getgid() == getegid())
1498 return access(path, mode);
1500 if (STAT(path, &st) < 0)
1501 return -1;
1503 if (euid == 0) {
1504 /* Root can read or write any file. */
1505 if (!(mode & X_OK))
1506 return 0;
1508 /* Root can execute any file that has any one of the execute
1509 bits set. */
1510 if (st.st_mode & S_IXUGO)
1511 return 0;
1513 return -1;
1516 if (st.st_uid == euid) /* owner */
1517 mode <<= 6;
1518 else if (rb_group_member(st.st_gid))
1519 mode <<= 3;
1521 if ((int)(st.st_mode & mode) == mode) return 0;
1523 return -1;
1524 #else
1525 return access(path, mode);
1526 #endif
1528 #endif
1530 struct access_arg {
1531 const char *path;
1532 int mode;
1535 static void *
1536 nogvl_eaccess(void *ptr)
1538 struct access_arg *aa = ptr;
1540 return (void *)(VALUE)eaccess(aa->path, aa->mode);
1543 static int
1544 rb_eaccess(VALUE fname, int mode)
1546 struct access_arg aa;
1548 FilePathValue(fname);
1549 fname = rb_str_encode_ospath(fname);
1550 aa.path = StringValueCStr(fname);
1551 aa.mode = mode;
1553 return (int)(VALUE)rb_thread_call_without_gvl(nogvl_eaccess, &aa,
1554 RUBY_UBF_IO, 0);
1557 static void *
1558 nogvl_access(void *ptr)
1560 struct access_arg *aa = ptr;
1562 return (void *)(VALUE)access(aa->path, aa->mode);
1565 static int
1566 rb_access(VALUE fname, int mode)
1568 struct access_arg aa;
1570 FilePathValue(fname);
1571 fname = rb_str_encode_ospath(fname);
1572 aa.path = StringValueCStr(fname);
1573 aa.mode = mode;
1575 return (int)(VALUE)rb_thread_call_without_gvl(nogvl_access, &aa,
1576 RUBY_UBF_IO, 0);
1580 * Document-class: FileTest
1582 * FileTest implements file test operations similar to those used in
1583 * File::Stat. It exists as a standalone module, and its methods are
1584 * also insinuated into the File class. (Note that this is not done
1585 * by inclusion: the interpreter cheats).
1590 * Document-method: directory?
1592 * call-seq:
1593 * File.directory?(file_name) -> true or false
1595 * Returns <code>true</code> if the named file is a directory,
1596 * or a symlink that points at a directory, and <code>false</code>
1597 * otherwise.
1599 * _file_name_ can be an IO object.
1601 * File.directory?(".")
1604 VALUE
1605 rb_file_directory_p(VALUE obj, VALUE fname)
1607 #ifndef S_ISDIR
1608 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1609 #endif
1611 struct stat st;
1613 if (rb_stat(fname, &st) < 0) return Qfalse;
1614 if (S_ISDIR(st.st_mode)) return Qtrue;
1615 return Qfalse;
1619 * call-seq:
1620 * File.pipe?(file_name) -> true or false
1622 * Returns <code>true</code> if the named file is a pipe.
1624 * _file_name_ can be an IO object.
1627 static VALUE
1628 rb_file_pipe_p(VALUE obj, VALUE fname)
1630 #ifdef S_IFIFO
1631 # ifndef S_ISFIFO
1632 # define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
1633 # endif
1635 struct stat st;
1637 if (rb_stat(fname, &st) < 0) return Qfalse;
1638 if (S_ISFIFO(st.st_mode)) return Qtrue;
1640 #endif
1641 return Qfalse;
1645 * call-seq:
1646 * File.symlink?(file_name) -> true or false
1648 * Returns <code>true</code> if the named file is a symbolic link.
1651 static VALUE
1652 rb_file_symlink_p(VALUE obj, VALUE fname)
1654 #ifndef S_ISLNK
1655 # ifdef _S_ISLNK
1656 # define S_ISLNK(m) _S_ISLNK(m)
1657 # else
1658 # ifdef _S_IFLNK
1659 # define S_ISLNK(m) (((m) & S_IFMT) == _S_IFLNK)
1660 # else
1661 # ifdef S_IFLNK
1662 # define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
1663 # endif
1664 # endif
1665 # endif
1666 #endif
1668 #ifdef S_ISLNK
1669 struct stat st;
1671 FilePathValue(fname);
1672 fname = rb_str_encode_ospath(fname);
1673 if (lstat_without_gvl(StringValueCStr(fname), &st) < 0) return Qfalse;
1674 if (S_ISLNK(st.st_mode)) return Qtrue;
1675 #endif
1677 return Qfalse;
1681 * call-seq:
1682 * File.socket?(file_name) -> true or false
1684 * Returns <code>true</code> if the named file is a socket.
1686 * _file_name_ can be an IO object.
1689 static VALUE
1690 rb_file_socket_p(VALUE obj, VALUE fname)
1692 #ifndef S_ISSOCK
1693 # ifdef _S_ISSOCK
1694 # define S_ISSOCK(m) _S_ISSOCK(m)
1695 # else
1696 # ifdef _S_IFSOCK
1697 # define S_ISSOCK(m) (((m) & S_IFMT) == _S_IFSOCK)
1698 # else
1699 # ifdef S_IFSOCK
1700 # define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK)
1701 # endif
1702 # endif
1703 # endif
1704 #endif
1706 #ifdef S_ISSOCK
1707 struct stat st;
1709 if (rb_stat(fname, &st) < 0) return Qfalse;
1710 if (S_ISSOCK(st.st_mode)) return Qtrue;
1712 #endif
1713 return Qfalse;
1717 * call-seq:
1718 * File.blockdev?(file_name) -> true or false
1720 * Returns <code>true</code> if the named file is a block device.
1722 * _file_name_ can be an IO object.
1725 static VALUE
1726 rb_file_blockdev_p(VALUE obj, VALUE fname)
1728 #ifndef S_ISBLK
1729 # ifdef S_IFBLK
1730 # define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK)
1731 # else
1732 # define S_ISBLK(m) (0) /* anytime false */
1733 # endif
1734 #endif
1736 #ifdef S_ISBLK
1737 struct stat st;
1739 if (rb_stat(fname, &st) < 0) return Qfalse;
1740 if (S_ISBLK(st.st_mode)) return Qtrue;
1742 #endif
1743 return Qfalse;
1747 * call-seq:
1748 * File.chardev?(file_name) -> true or false
1750 * Returns <code>true</code> if the named file is a character device.
1752 * _file_name_ can be an IO object.
1754 static VALUE
1755 rb_file_chardev_p(VALUE obj, VALUE fname)
1757 #ifndef S_ISCHR
1758 # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
1759 #endif
1761 struct stat st;
1763 if (rb_stat(fname, &st) < 0) return Qfalse;
1764 if (S_ISCHR(st.st_mode)) return Qtrue;
1766 return Qfalse;
1770 * call-seq:
1771 * File.exist?(file_name) -> true or false
1773 * Return <code>true</code> if the named file exists.
1775 * _file_name_ can be an IO object.
1777 * "file exists" means that stat() or fstat() system call is successful.
1780 static VALUE
1781 rb_file_exist_p(VALUE obj, VALUE fname)
1783 struct stat st;
1785 if (rb_stat(fname, &st) < 0) return Qfalse;
1786 return Qtrue;
1789 /* :nodoc: */
1790 static VALUE
1791 rb_file_exists_p(VALUE obj, VALUE fname)
1793 const char *s = "FileTest#exist?";
1794 if (obj == rb_mFileTest) {
1795 s = "FileTest.exist?";
1797 else if (obj == rb_cFile ||
1798 (RB_TYPE_P(obj, T_CLASS) &&
1799 RTEST(rb_class_inherited_p(obj, rb_cFile)))) {
1800 s = "File.exist?";
1802 rb_warn_deprecated("%.*ss?", s, (int)(strlen(s)-1), s);
1803 return rb_file_exist_p(obj, fname);
1807 * call-seq:
1808 * File.readable?(file_name) -> true or false
1810 * Returns <code>true</code> if the named file is readable by the effective
1811 * user and group id of this process. See eaccess(3).
1813 * Note that some OS-level security features may cause this to return true
1814 * even though the file is not readable by the effective user/group.
1817 static VALUE
1818 rb_file_readable_p(VALUE obj, VALUE fname)
1820 return RBOOL(rb_eaccess(fname, R_OK) >= 0);
1824 * call-seq:
1825 * File.readable_real?(file_name) -> true or false
1827 * Returns <code>true</code> if the named file is readable by the real
1828 * user and group id of this process. See access(3).
1830 * Note that some OS-level security features may cause this to return true
1831 * even though the file is not readable by the real user/group.
1834 static VALUE
1835 rb_file_readable_real_p(VALUE obj, VALUE fname)
1837 return RBOOL(rb_access(fname, R_OK) >= 0);
1840 #ifndef S_IRUGO
1841 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1842 #endif
1844 #ifndef S_IWUGO
1845 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
1846 #endif
1849 * call-seq:
1850 * File.world_readable?(file_name) -> integer or nil
1852 * If <i>file_name</i> is readable by others, returns an integer
1853 * representing the file permission bits of <i>file_name</i>. Returns
1854 * <code>nil</code> otherwise. The meaning of the bits is platform
1855 * dependent; on Unix systems, see <code>stat(2)</code>.
1857 * _file_name_ can be an IO object.
1859 * File.world_readable?("/etc/passwd") #=> 420
1860 * m = File.world_readable?("/etc/passwd")
1861 * sprintf("%o", m) #=> "644"
1864 static VALUE
1865 rb_file_world_readable_p(VALUE obj, VALUE fname)
1867 #ifdef S_IROTH
1868 struct stat st;
1870 if (rb_stat(fname, &st) < 0) return Qnil;
1871 if ((st.st_mode & (S_IROTH)) == S_IROTH) {
1872 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1874 #endif
1875 return Qnil;
1879 * call-seq:
1880 * File.writable?(file_name) -> true or false
1882 * Returns <code>true</code> if the named file is writable by the effective
1883 * user and group id of this process. See eaccess(3).
1885 * Note that some OS-level security features may cause this to return true
1886 * even though the file is not writable by the effective user/group.
1889 static VALUE
1890 rb_file_writable_p(VALUE obj, VALUE fname)
1892 return RBOOL(rb_eaccess(fname, W_OK) >= 0);
1896 * call-seq:
1897 * File.writable_real?(file_name) -> true or false
1899 * Returns <code>true</code> if the named file is writable by the real
1900 * user and group id of this process. See access(3).
1902 * Note that some OS-level security features may cause this to return true
1903 * even though the file is not writable by the real user/group.
1906 static VALUE
1907 rb_file_writable_real_p(VALUE obj, VALUE fname)
1909 return RBOOL(rb_access(fname, W_OK) >= 0);
1913 * call-seq:
1914 * File.world_writable?(file_name) -> integer or nil
1916 * If <i>file_name</i> is writable by others, returns an integer
1917 * representing the file permission bits of <i>file_name</i>. Returns
1918 * <code>nil</code> otherwise. The meaning of the bits is platform
1919 * dependent; on Unix systems, see <code>stat(2)</code>.
1921 * _file_name_ can be an IO object.
1923 * File.world_writable?("/tmp") #=> 511
1924 * m = File.world_writable?("/tmp")
1925 * sprintf("%o", m) #=> "777"
1928 static VALUE
1929 rb_file_world_writable_p(VALUE obj, VALUE fname)
1931 #ifdef S_IWOTH
1932 struct stat st;
1934 if (rb_stat(fname, &st) < 0) return Qnil;
1935 if ((st.st_mode & (S_IWOTH)) == S_IWOTH) {
1936 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1938 #endif
1939 return Qnil;
1943 * call-seq:
1944 * File.executable?(file_name) -> true or false
1946 * Returns <code>true</code> if the named file is executable by the effective
1947 * user and group id of this process. See eaccess(3).
1949 * Windows does not support execute permissions separately from read
1950 * permissions. On Windows, a file is only considered executable if it ends in
1951 * .bat, .cmd, .com, or .exe.
1953 * Note that some OS-level security features may cause this to return true
1954 * even though the file is not executable by the effective user/group.
1957 static VALUE
1958 rb_file_executable_p(VALUE obj, VALUE fname)
1960 return RBOOL(rb_eaccess(fname, X_OK) >= 0);
1964 * call-seq:
1965 * File.executable_real?(file_name) -> true or false
1967 * Returns <code>true</code> if the named file is executable by the real
1968 * user and group id of this process. See access(3).
1970 * Windows does not support execute permissions separately from read
1971 * permissions. On Windows, a file is only considered executable if it ends in
1972 * .bat, .cmd, .com, or .exe.
1974 * Note that some OS-level security features may cause this to return true
1975 * even though the file is not executable by the real user/group.
1978 static VALUE
1979 rb_file_executable_real_p(VALUE obj, VALUE fname)
1981 return RBOOL(rb_access(fname, X_OK) >= 0);
1984 #ifndef S_ISREG
1985 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1986 #endif
1989 * call-seq:
1990 * File.file?(file) -> true or false
1992 * Returns +true+ if the named +file+ exists and is a regular file.
1994 * +file+ can be an IO object.
1996 * If the +file+ argument is a symbolic link, it will resolve the symbolic link
1997 * and use the file referenced by the link.
2000 static VALUE
2001 rb_file_file_p(VALUE obj, VALUE fname)
2003 struct stat st;
2005 if (rb_stat(fname, &st) < 0) return Qfalse;
2006 return RBOOL(S_ISREG(st.st_mode));
2010 * call-seq:
2011 * File.zero?(file_name) -> true or false
2013 * Returns <code>true</code> if the named file exists and has
2014 * a zero size.
2016 * _file_name_ can be an IO object.
2019 static VALUE
2020 rb_file_zero_p(VALUE obj, VALUE fname)
2022 struct stat st;
2024 if (rb_stat(fname, &st) < 0) return Qfalse;
2025 return RBOOL(st.st_size == 0);
2029 * call-seq:
2030 * File.size?(file_name) -> Integer or nil
2032 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
2033 * file otherwise.
2035 * _file_name_ can be an IO object.
2038 static VALUE
2039 rb_file_size_p(VALUE obj, VALUE fname)
2041 struct stat st;
2043 if (rb_stat(fname, &st) < 0) return Qnil;
2044 if (st.st_size == 0) return Qnil;
2045 return OFFT2NUM(st.st_size);
2049 * call-seq:
2050 * File.owned?(file_name) -> true or false
2052 * Returns <code>true</code> if the named file exists and the
2053 * effective used id of the calling process is the owner of
2054 * the file.
2056 * _file_name_ can be an IO object.
2059 static VALUE
2060 rb_file_owned_p(VALUE obj, VALUE fname)
2062 struct stat st;
2064 if (rb_stat(fname, &st) < 0) return Qfalse;
2065 return RBOOL(st.st_uid == geteuid());
2068 static VALUE
2069 rb_file_rowned_p(VALUE obj, VALUE fname)
2071 struct stat st;
2073 if (rb_stat(fname, &st) < 0) return Qfalse;
2074 return RBOOL(st.st_uid == getuid());
2078 * call-seq:
2079 * File.grpowned?(file_name) -> true or false
2081 * Returns <code>true</code> if the named file exists and the
2082 * effective group id of the calling process is the owner of
2083 * the file. Returns <code>false</code> on Windows.
2085 * _file_name_ can be an IO object.
2088 static VALUE
2089 rb_file_grpowned_p(VALUE obj, VALUE fname)
2091 #ifndef _WIN32
2092 struct stat st;
2094 if (rb_stat(fname, &st) < 0) return Qfalse;
2095 if (rb_group_member(st.st_gid)) return Qtrue;
2096 #endif
2097 return Qfalse;
2100 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2101 static VALUE
2102 check3rdbyte(VALUE fname, int mode)
2104 struct stat st;
2106 if (rb_stat(fname, &st) < 0) return Qfalse;
2107 return RBOOL(st.st_mode & mode);
2109 #endif
2112 * call-seq:
2113 * File.setuid?(file_name) -> true or false
2115 * Returns <code>true</code> if the named file has the setuid bit set.
2117 * _file_name_ can be an IO object.
2120 static VALUE
2121 rb_file_suid_p(VALUE obj, VALUE fname)
2123 #ifdef S_ISUID
2124 return check3rdbyte(fname, S_ISUID);
2125 #else
2126 return Qfalse;
2127 #endif
2131 * call-seq:
2132 * File.setgid?(file_name) -> true or false
2134 * Returns <code>true</code> if the named file has the setgid bit set.
2136 * _file_name_ can be an IO object.
2139 static VALUE
2140 rb_file_sgid_p(VALUE obj, VALUE fname)
2142 #ifdef S_ISGID
2143 return check3rdbyte(fname, S_ISGID);
2144 #else
2145 return Qfalse;
2146 #endif
2150 * call-seq:
2151 * File.sticky?(file_name) -> true or false
2153 * Returns <code>true</code> if the named file has the sticky bit set.
2155 * _file_name_ can be an IO object.
2158 static VALUE
2159 rb_file_sticky_p(VALUE obj, VALUE fname)
2161 #ifdef S_ISVTX
2162 return check3rdbyte(fname, S_ISVTX);
2163 #else
2164 return Qnil;
2165 #endif
2169 * call-seq:
2170 * File.identical?(file_1, file_2) -> true or false
2172 * Returns <code>true</code> if the named files are identical.
2174 * _file_1_ and _file_2_ can be an IO object.
2176 * open("a", "w") {}
2177 * p File.identical?("a", "a") #=> true
2178 * p File.identical?("a", "./a") #=> true
2179 * File.link("a", "b")
2180 * p File.identical?("a", "b") #=> true
2181 * File.symlink("a", "c")
2182 * p File.identical?("a", "c") #=> true
2183 * open("d", "w") {}
2184 * p File.identical?("a", "d") #=> false
2187 static VALUE
2188 rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2)
2190 #ifndef _WIN32
2191 struct stat st1, st2;
2193 if (rb_stat(fname1, &st1) < 0) return Qfalse;
2194 if (rb_stat(fname2, &st2) < 0) return Qfalse;
2195 if (st1.st_dev != st2.st_dev) return Qfalse;
2196 if (st1.st_ino != st2.st_ino) return Qfalse;
2197 return Qtrue;
2198 #else
2199 extern VALUE rb_w32_file_identical_p(VALUE, VALUE);
2200 return rb_w32_file_identical_p(fname1, fname2);
2201 #endif
2205 * call-seq:
2206 * File.size(file_name) -> integer
2208 * Returns the size of <code>file_name</code>.
2210 * _file_name_ can be an IO object.
2213 static VALUE
2214 rb_file_s_size(VALUE klass, VALUE fname)
2216 struct stat st;
2218 if (rb_stat(fname, &st) < 0) {
2219 int e = errno;
2220 FilePathValue(fname);
2221 rb_syserr_fail_path(e, fname);
2223 return OFFT2NUM(st.st_size);
2226 static VALUE
2227 rb_file_ftype(const struct stat *st)
2229 const char *t;
2231 if (S_ISREG(st->st_mode)) {
2232 t = "file";
2234 else if (S_ISDIR(st->st_mode)) {
2235 t = "directory";
2237 else if (S_ISCHR(st->st_mode)) {
2238 t = "characterSpecial";
2240 #ifdef S_ISBLK
2241 else if (S_ISBLK(st->st_mode)) {
2242 t = "blockSpecial";
2244 #endif
2245 #ifdef S_ISFIFO
2246 else if (S_ISFIFO(st->st_mode)) {
2247 t = "fifo";
2249 #endif
2250 #ifdef S_ISLNK
2251 else if (S_ISLNK(st->st_mode)) {
2252 t = "link";
2254 #endif
2255 #ifdef S_ISSOCK
2256 else if (S_ISSOCK(st->st_mode)) {
2257 t = "socket";
2259 #endif
2260 else {
2261 t = "unknown";
2264 return rb_usascii_str_new2(t);
2268 * call-seq:
2269 * File.ftype(file_name) -> string
2271 * Identifies the type of the named file; the return string is one of
2272 * ``<code>file</code>'', ``<code>directory</code>'',
2273 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
2274 * ``<code>fifo</code>'', ``<code>link</code>'',
2275 * ``<code>socket</code>'', or ``<code>unknown</code>''.
2277 * File.ftype("testfile") #=> "file"
2278 * File.ftype("/dev/tty") #=> "characterSpecial"
2279 * File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2282 static VALUE
2283 rb_file_s_ftype(VALUE klass, VALUE fname)
2285 struct stat st;
2287 FilePathValue(fname);
2288 fname = rb_str_encode_ospath(fname);
2289 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
2290 rb_sys_fail_path(fname);
2293 return rb_file_ftype(&st);
2297 * call-seq:
2298 * File.atime(file_name) -> time
2300 * Returns the last access time for the named file as a Time object.
2302 * _file_name_ can be an IO object.
2304 * File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2308 static VALUE
2309 rb_file_s_atime(VALUE klass, VALUE fname)
2311 struct stat st;
2313 if (rb_stat(fname, &st) < 0) {
2314 int e = errno;
2315 FilePathValue(fname);
2316 rb_syserr_fail_path(e, fname);
2318 return stat_atime(&st);
2322 * call-seq:
2323 * file.atime -> time
2325 * Returns the last access time (a Time object) for <i>file</i>, or
2326 * epoch if <i>file</i> has not been accessed.
2328 * File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2332 static VALUE
2333 rb_file_atime(VALUE obj)
2335 rb_io_t *fptr;
2336 struct stat st;
2338 GetOpenFile(obj, fptr);
2339 if (fstat(fptr->fd, &st) == -1) {
2340 rb_sys_fail_path(fptr->pathv);
2342 return stat_atime(&st);
2346 * call-seq:
2347 * File.mtime(file_name) -> time
2349 * Returns the modification time for the named file as a Time object.
2351 * _file_name_ can be an IO object.
2353 * File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2357 static VALUE
2358 rb_file_s_mtime(VALUE klass, VALUE fname)
2360 struct stat st;
2362 if (rb_stat(fname, &st) < 0) {
2363 int e = errno;
2364 FilePathValue(fname);
2365 rb_syserr_fail_path(e, fname);
2367 return stat_mtime(&st);
2371 * call-seq:
2372 * file.mtime -> time
2374 * Returns the modification time for <i>file</i>.
2376 * File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2380 static VALUE
2381 rb_file_mtime(VALUE obj)
2383 rb_io_t *fptr;
2384 struct stat st;
2386 GetOpenFile(obj, fptr);
2387 if (fstat(fptr->fd, &st) == -1) {
2388 rb_sys_fail_path(fptr->pathv);
2390 return stat_mtime(&st);
2394 * call-seq:
2395 * File.ctime(file_name) -> time
2397 * Returns the change time for the named file (the time at which
2398 * directory information about the file was changed, not the file
2399 * itself).
2401 * _file_name_ can be an IO object.
2403 * Note that on Windows (NTFS), returns creation time (birth time).
2405 * File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2409 static VALUE
2410 rb_file_s_ctime(VALUE klass, VALUE fname)
2412 struct stat st;
2414 if (rb_stat(fname, &st) < 0) {
2415 int e = errno;
2416 FilePathValue(fname);
2417 rb_syserr_fail_path(e, fname);
2419 return stat_ctime(&st);
2423 * call-seq:
2424 * file.ctime -> time
2426 * Returns the change time for <i>file</i> (that is, the time directory
2427 * information about the file was changed, not the file itself).
2429 * Note that on Windows (NTFS), returns creation time (birth time).
2431 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2435 static VALUE
2436 rb_file_ctime(VALUE obj)
2438 rb_io_t *fptr;
2439 struct stat st;
2441 GetOpenFile(obj, fptr);
2442 if (fstat(fptr->fd, &st) == -1) {
2443 rb_sys_fail_path(fptr->pathv);
2445 return stat_ctime(&st);
2449 * call-seq:
2450 * File.birthtime(file_name) -> time
2452 * Returns the birth time for the named file.
2454 * _file_name_ can be an IO object.
2456 * File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2458 * If the platform doesn't have birthtime, raises NotImplementedError.
2462 #if defined(HAVE_STAT_BIRTHTIME)
2463 RUBY_FUNC_EXPORTED VALUE
2464 rb_file_s_birthtime(VALUE klass, VALUE fname)
2466 statx_data st;
2468 if (rb_statx(fname, &st, STATX_BTIME) < 0) {
2469 int e = errno;
2470 FilePathValue(fname);
2471 rb_syserr_fail_path(e, fname);
2473 return statx_birthtime(&st, fname);
2475 #else
2476 # define rb_file_s_birthtime rb_f_notimplement
2477 #endif
2479 #if defined(HAVE_STAT_BIRTHTIME)
2481 * call-seq:
2482 * file.birthtime -> time
2484 * Returns the birth time for <i>file</i>.
2486 * File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
2488 * If the platform doesn't have birthtime, raises NotImplementedError.
2492 static VALUE
2493 rb_file_birthtime(VALUE obj)
2495 rb_io_t *fptr;
2496 statx_data st;
2498 GetOpenFile(obj, fptr);
2499 if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) {
2500 rb_sys_fail_path(fptr->pathv);
2502 return statx_birthtime(&st, fptr->pathv);
2504 #else
2505 # define rb_file_birthtime rb_f_notimplement
2506 #endif
2509 * call-seq:
2510 * file.size -> integer
2512 * Returns the size of <i>file</i> in bytes.
2514 * File.new("testfile").size #=> 66
2518 off_t
2519 rb_file_size(VALUE file)
2521 if (RB_TYPE_P(file, T_FILE)) {
2522 rb_io_t *fptr;
2523 struct stat st;
2525 RB_IO_POINTER(file, fptr);
2526 if (fptr->mode & FMODE_WRITABLE) {
2527 rb_io_flush_raw(file, 0);
2530 if (fstat(fptr->fd, &st) == -1) {
2531 rb_sys_fail_path(fptr->pathv);
2534 return st.st_size;
2536 else {
2537 return NUM2OFFT(rb_funcall(file, idSize, 0));
2541 static VALUE
2542 file_size(VALUE self)
2544 return OFFT2NUM(rb_file_size(self));
2547 static int
2548 chmod_internal(const char *path, void *mode)
2550 return chmod(path, *(mode_t *)mode);
2554 * call-seq:
2555 * File.chmod(mode_int, file_name, ... ) -> integer
2557 * Changes permission bits on the named file(s) to the bit pattern
2558 * represented by <i>mode_int</i>. Actual effects are operating system
2559 * dependent (see the beginning of this section). On Unix systems, see
2560 * <code>chmod(2)</code> for details. Returns the number of files
2561 * processed.
2563 * File.chmod(0644, "testfile", "out") #=> 2
2566 static VALUE
2567 rb_file_s_chmod(int argc, VALUE *argv, VALUE _)
2569 mode_t mode;
2571 apply2args(1);
2572 mode = NUM2MODET(*argv++);
2574 return apply2files(chmod_internal, argc, argv, &mode);
2578 * call-seq:
2579 * file.chmod(mode_int) -> 0
2581 * Changes permission bits on <i>file</i> to the bit pattern
2582 * represented by <i>mode_int</i>. Actual effects are platform
2583 * dependent; on Unix systems, see <code>chmod(2)</code> for details.
2584 * Follows symbolic links. Also see File#lchmod.
2586 * f = File.new("out", "w");
2587 * f.chmod(0644) #=> 0
2590 static VALUE
2591 rb_file_chmod(VALUE obj, VALUE vmode)
2593 rb_io_t *fptr;
2594 mode_t mode;
2595 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2596 VALUE path;
2597 #endif
2599 mode = NUM2MODET(vmode);
2601 GetOpenFile(obj, fptr);
2602 #ifdef HAVE_FCHMOD
2603 if (fchmod(fptr->fd, mode) == -1) {
2604 if (HAVE_FCHMOD || errno != ENOSYS)
2605 rb_sys_fail_path(fptr->pathv);
2607 else {
2608 if (!HAVE_FCHMOD) return INT2FIX(0);
2610 #endif
2611 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2612 if (NIL_P(fptr->pathv)) return Qnil;
2613 path = rb_str_encode_ospath(fptr->pathv);
2614 if (chmod(RSTRING_PTR(path), mode) == -1)
2615 rb_sys_fail_path(fptr->pathv);
2616 #endif
2618 return INT2FIX(0);
2621 #if defined(HAVE_LCHMOD)
2622 static int
2623 lchmod_internal(const char *path, void *mode)
2625 return lchmod(path, *(mode_t *)mode);
2629 * call-seq:
2630 * File.lchmod(mode_int, file_name, ...) -> integer
2632 * Equivalent to File::chmod, but does not follow symbolic links (so
2633 * it will change the permissions associated with the link, not the
2634 * file referenced by the link). Often not available.
2638 static VALUE
2639 rb_file_s_lchmod(int argc, VALUE *argv, VALUE _)
2641 mode_t mode;
2643 apply2args(1);
2644 mode = NUM2MODET(*argv++);
2646 return apply2files(lchmod_internal, argc, argv, &mode);
2648 #else
2649 #define rb_file_s_lchmod rb_f_notimplement
2650 #endif
2652 static inline rb_uid_t
2653 to_uid(VALUE u)
2655 if (NIL_P(u)) {
2656 return (rb_uid_t)-1;
2658 return NUM2UIDT(u);
2661 static inline rb_gid_t
2662 to_gid(VALUE g)
2664 if (NIL_P(g)) {
2665 return (rb_gid_t)-1;
2667 return NUM2GIDT(g);
2670 struct chown_args {
2671 rb_uid_t owner;
2672 rb_gid_t group;
2675 static int
2676 chown_internal(const char *path, void *arg)
2678 struct chown_args *args = arg;
2679 return chown(path, args->owner, args->group);
2683 * call-seq:
2684 * File.chown(owner_int, group_int, file_name, ...) -> integer
2686 * Changes the owner and group of the named file(s) to the given
2687 * numeric owner and group id's. Only a process with superuser
2688 * privileges may change the owner of a file. The current owner of a
2689 * file may change the file's group to any group to which the owner
2690 * belongs. A <code>nil</code> or -1 owner or group id is ignored.
2691 * Returns the number of files processed.
2693 * File.chown(nil, 100, "testfile")
2697 static VALUE
2698 rb_file_s_chown(int argc, VALUE *argv, VALUE _)
2700 struct chown_args arg;
2702 apply2args(2);
2703 arg.owner = to_uid(*argv++);
2704 arg.group = to_gid(*argv++);
2706 return apply2files(chown_internal, argc, argv, &arg);
2710 * call-seq:
2711 * file.chown(owner_int, group_int ) -> 0
2713 * Changes the owner and group of <i>file</i> to the given numeric
2714 * owner and group id's. Only a process with superuser privileges may
2715 * change the owner of a file. The current owner of a file may change
2716 * the file's group to any group to which the owner belongs. A
2717 * <code>nil</code> or -1 owner or group id is ignored. Follows
2718 * symbolic links. See also File#lchown.
2720 * File.new("testfile").chown(502, 1000)
2724 static VALUE
2725 rb_file_chown(VALUE obj, VALUE owner, VALUE group)
2727 rb_io_t *fptr;
2728 rb_uid_t o;
2729 rb_gid_t g;
2730 #ifndef HAVE_FCHOWN
2731 VALUE path;
2732 #endif
2734 o = to_uid(owner);
2735 g = to_gid(group);
2736 GetOpenFile(obj, fptr);
2737 #ifndef HAVE_FCHOWN
2738 if (NIL_P(fptr->pathv)) return Qnil;
2739 path = rb_str_encode_ospath(fptr->pathv);
2740 if (chown(RSTRING_PTR(path), o, g) == -1)
2741 rb_sys_fail_path(fptr->pathv);
2742 #else
2743 if (fchown(fptr->fd, o, g) == -1)
2744 rb_sys_fail_path(fptr->pathv);
2745 #endif
2747 return INT2FIX(0);
2750 #if defined(HAVE_LCHOWN)
2751 static int
2752 lchown_internal(const char *path, void *arg)
2754 struct chown_args *args = arg;
2755 return lchown(path, args->owner, args->group);
2759 * call-seq:
2760 * File.lchown(owner_int, group_int, file_name,..) -> integer
2762 * Equivalent to File::chown, but does not follow symbolic
2763 * links (so it will change the owner associated with the link, not the
2764 * file referenced by the link). Often not available. Returns number
2765 * of files in the argument list.
2769 static VALUE
2770 rb_file_s_lchown(int argc, VALUE *argv, VALUE _)
2772 struct chown_args arg;
2774 apply2args(2);
2775 arg.owner = to_uid(*argv++);
2776 arg.group = to_gid(*argv++);
2778 return apply2files(lchown_internal, argc, argv, &arg);
2780 #else
2781 #define rb_file_s_lchown rb_f_notimplement
2782 #endif
2784 struct utime_args {
2785 const struct timespec* tsp;
2786 VALUE atime, mtime;
2787 int follow; /* Whether to act on symlinks (1) or their referent (0) */
2790 #ifdef UTIME_EINVAL
2791 NORETURN(static void utime_failed(struct apply_arg *));
2793 static void
2794 utime_failed(struct apply_arg *aa)
2796 int e = aa->errnum;
2797 VALUE path = aa->fn[aa->i].path;
2798 struct utime_args *ua = aa->arg;
2800 if (ua->tsp && e == EINVAL) {
2801 VALUE e[2], a = Qnil, m = Qnil;
2802 int d = 0;
2803 VALUE atime = ua->atime;
2804 VALUE mtime = ua->mtime;
2806 if (!NIL_P(atime)) {
2807 a = rb_inspect(atime);
2809 if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) {
2810 m = rb_inspect(mtime);
2812 if (NIL_P(a)) e[0] = m;
2813 else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a;
2814 else {
2815 e[0] = rb_str_plus(a, rb_str_new_cstr(" or "));
2816 rb_str_append(e[0], m);
2817 d = 1;
2819 if (!NIL_P(e[0])) {
2820 if (path) {
2821 if (!d) e[0] = rb_str_dup(e[0]);
2822 rb_str_append(rb_str_cat2(e[0], " for "), path);
2824 e[1] = INT2FIX(EINVAL);
2825 rb_exc_raise(rb_class_new_instance(2, e, rb_eSystemCallError));
2828 rb_syserr_fail_path(e, path);
2830 #endif
2832 #if defined(HAVE_UTIMES)
2834 static int
2835 utime_internal(const char *path, void *arg)
2837 struct utime_args *v = arg;
2838 const struct timespec *tsp = v->tsp;
2839 struct timeval tvbuf[2], *tvp = NULL;
2841 #if defined(HAVE_UTIMENSAT)
2842 static int try_utimensat = 1;
2843 # ifdef AT_SYMLINK_NOFOLLOW
2844 static int try_utimensat_follow = 1;
2845 # else
2846 const int try_utimensat_follow = 0;
2847 # endif
2848 int flags = 0;
2850 if (v->follow ? try_utimensat_follow : try_utimensat) {
2851 # ifdef AT_SYMLINK_NOFOLLOW
2852 if (v->follow) {
2853 flags = AT_SYMLINK_NOFOLLOW;
2855 # endif
2857 if (utimensat(AT_FDCWD, path, tsp, flags) < 0) {
2858 if (errno == ENOSYS) {
2859 # ifdef AT_SYMLINK_NOFOLLOW
2860 try_utimensat_follow = 0;
2861 # endif
2862 if (!v->follow)
2863 try_utimensat = 0;
2864 goto no_utimensat;
2866 return -1; /* calls utime_failed */
2868 return 0;
2870 no_utimensat:
2871 #endif
2873 if (tsp) {
2874 tvbuf[0].tv_sec = tsp[0].tv_sec;
2875 tvbuf[0].tv_usec = (int)(tsp[0].tv_nsec / 1000);
2876 tvbuf[1].tv_sec = tsp[1].tv_sec;
2877 tvbuf[1].tv_usec = (int)(tsp[1].tv_nsec / 1000);
2878 tvp = tvbuf;
2880 #ifdef HAVE_LUTIMES
2881 if (v->follow) return lutimes(path, tvp);
2882 #endif
2883 return utimes(path, tvp);
2886 #else
2888 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
2889 struct utimbuf {
2890 long actime;
2891 long modtime;
2893 #endif
2895 static int
2896 utime_internal(const char *path, void *arg)
2898 struct utime_args *v = arg;
2899 const struct timespec *tsp = v->tsp;
2900 struct utimbuf utbuf, *utp = NULL;
2901 if (tsp) {
2902 utbuf.actime = tsp[0].tv_sec;
2903 utbuf.modtime = tsp[1].tv_sec;
2904 utp = &utbuf;
2906 return utime(path, utp);
2909 #endif
2911 static VALUE
2912 utime_internal_i(int argc, VALUE *argv, int follow)
2914 struct utime_args args;
2915 struct timespec tss[2], *tsp = NULL;
2917 apply2args(2);
2918 args.atime = *argv++;
2919 args.mtime = *argv++;
2921 args.follow = follow;
2923 if (!NIL_P(args.atime) || !NIL_P(args.mtime)) {
2924 tsp = tss;
2925 tsp[0] = rb_time_timespec(args.atime);
2926 if (args.atime == args.mtime)
2927 tsp[1] = tsp[0];
2928 else
2929 tsp[1] = rb_time_timespec(args.mtime);
2931 args.tsp = tsp;
2933 return apply2files(utime_internal, argc, argv, &args);
2937 * call-seq:
2938 * File.utime(atime, mtime, file_name, ...) -> integer
2940 * Sets the access and modification times of each named file to the
2941 * first two arguments. If a file is a symlink, this method acts upon
2942 * its referent rather than the link itself; for the inverse
2943 * behavior see File.lutime. Returns the number of file
2944 * names in the argument list.
2947 static VALUE
2948 rb_file_s_utime(int argc, VALUE *argv, VALUE _)
2950 return utime_internal_i(argc, argv, FALSE);
2953 #if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
2956 * call-seq:
2957 * File.lutime(atime, mtime, file_name, ...) -> integer
2959 * Sets the access and modification times of each named file to the
2960 * first two arguments. If a file is a symlink, this method acts upon
2961 * the link itself as opposed to its referent; for the inverse
2962 * behavior, see File.utime. Returns the number of file
2963 * names in the argument list.
2966 static VALUE
2967 rb_file_s_lutime(int argc, VALUE *argv, VALUE _)
2969 return utime_internal_i(argc, argv, TRUE);
2971 #else
2972 #define rb_file_s_lutime rb_f_notimplement
2973 #endif
2975 #ifdef RUBY_FUNCTION_NAME_STRING
2976 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
2977 #else
2978 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
2979 #endif
2980 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
2981 NORETURN(static void syserr_fail2_in(const char *,int,VALUE,VALUE));
2982 static void
2983 syserr_fail2_in(const char *func, int e, VALUE s1, VALUE s2)
2985 VALUE str;
2986 #ifdef MAX_PATH
2987 const int max_pathlen = MAX_PATH;
2988 #else
2989 const int max_pathlen = MAXPATHLEN;
2990 #endif
2992 if (e == EEXIST) {
2993 rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen));
2995 str = rb_str_new_cstr("(");
2996 rb_str_append(str, rb_str_ellipsize(s1, max_pathlen));
2997 rb_str_cat2(str, ", ");
2998 rb_str_append(str, rb_str_ellipsize(s2, max_pathlen));
2999 rb_str_cat2(str, ")");
3000 #ifdef RUBY_FUNCTION_NAME_STRING
3001 rb_syserr_fail_path_in(func, e, str);
3002 #else
3003 rb_syserr_fail_path(e, str);
3004 #endif
3007 #ifdef HAVE_LINK
3009 * call-seq:
3010 * File.link(old_name, new_name) -> 0
3012 * Creates a new name for an existing file using a hard link. Will not
3013 * overwrite <i>new_name</i> if it already exists (raising a subclass
3014 * of SystemCallError). Not available on all platforms.
3016 * File.link("testfile", ".testfile") #=> 0
3017 * IO.readlines(".testfile")[0] #=> "This is line one\n"
3020 static VALUE
3021 rb_file_s_link(VALUE klass, VALUE from, VALUE to)
3023 FilePathValue(from);
3024 FilePathValue(to);
3025 from = rb_str_encode_ospath(from);
3026 to = rb_str_encode_ospath(to);
3028 if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
3029 sys_fail2(from, to);
3031 return INT2FIX(0);
3033 #else
3034 #define rb_file_s_link rb_f_notimplement
3035 #endif
3037 #ifdef HAVE_SYMLINK
3039 * call-seq:
3040 * File.symlink(old_name, new_name) -> 0
3042 * Creates a symbolic link called <i>new_name</i> for the existing file
3043 * <i>old_name</i>. Raises a NotImplemented exception on
3044 * platforms that do not support symbolic links.
3046 * File.symlink("testfile", "link2test") #=> 0
3050 static VALUE
3051 rb_file_s_symlink(VALUE klass, VALUE from, VALUE to)
3053 FilePathValue(from);
3054 FilePathValue(to);
3055 from = rb_str_encode_ospath(from);
3056 to = rb_str_encode_ospath(to);
3058 if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
3059 sys_fail2(from, to);
3061 return INT2FIX(0);
3063 #else
3064 #define rb_file_s_symlink rb_f_notimplement
3065 #endif
3067 #ifdef HAVE_READLINK
3069 * call-seq:
3070 * File.readlink(link_name) -> file_name
3072 * Returns the name of the file referenced by the given link.
3073 * Not available on all platforms.
3075 * File.symlink("testfile", "link2test") #=> 0
3076 * File.readlink("link2test") #=> "testfile"
3079 static VALUE
3080 rb_file_s_readlink(VALUE klass, VALUE path)
3082 return rb_readlink(path, rb_filesystem_encoding());
3085 #ifndef _WIN32
3086 struct readlink_arg {
3087 const char *path;
3088 char *buf;
3089 size_t size;
3092 static void *
3093 nogvl_readlink(void *ptr)
3095 struct readlink_arg *ra = ptr;
3097 return (void *)(VALUE)readlink(ra->path, ra->buf, ra->size);
3100 static ssize_t
3101 readlink_without_gvl(VALUE path, VALUE buf, size_t size)
3103 struct readlink_arg ra;
3105 ra.path = RSTRING_PTR(path);
3106 ra.buf = RSTRING_PTR(buf);
3107 ra.size = size;
3109 return (ssize_t)rb_thread_call_without_gvl(nogvl_readlink, &ra,
3110 RUBY_UBF_IO, 0);
3113 VALUE
3114 rb_readlink(VALUE path, rb_encoding *enc)
3116 int size = 100;
3117 ssize_t rv;
3118 VALUE v;
3120 FilePathValue(path);
3121 path = rb_str_encode_ospath(path);
3122 v = rb_enc_str_new(0, size, enc);
3123 while ((rv = readlink_without_gvl(path, v, size)) == size
3124 #ifdef _AIX
3125 || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
3126 #endif
3128 rb_str_modify_expand(v, size);
3129 size *= 2;
3130 rb_str_set_len(v, size);
3132 if (rv < 0) {
3133 int e = errno;
3134 rb_str_resize(v, 0);
3135 rb_syserr_fail_path(e, path);
3137 rb_str_resize(v, rv);
3139 return v;
3141 #endif
3142 #else
3143 #define rb_file_s_readlink rb_f_notimplement
3144 #endif
3146 static int
3147 unlink_internal(const char *path, void *arg)
3149 return unlink(path);
3153 * call-seq:
3154 * File.delete(file_name, ...) -> integer
3155 * File.unlink(file_name, ...) -> integer
3157 * Deletes the named files, returning the number of names
3158 * passed as arguments. Raises an exception on any error.
3159 * Since the underlying implementation relies on the
3160 * <code>unlink(2)</code> system call, the type of
3161 * exception raised depends on its error type (see
3162 * https://linux.die.net/man/2/unlink) and has the form of
3163 * e.g. Errno::ENOENT.
3165 * See also Dir::rmdir.
3168 static VALUE
3169 rb_file_s_unlink(int argc, VALUE *argv, VALUE klass)
3171 return apply2files(unlink_internal, argc, argv, 0);
3174 struct rename_args {
3175 const char *src;
3176 const char *dst;
3179 static void *
3180 no_gvl_rename(void *ptr)
3182 struct rename_args *ra = ptr;
3184 return (void *)(VALUE)rename(ra->src, ra->dst);
3188 * call-seq:
3189 * File.rename(old_name, new_name) -> 0
3191 * Renames the given file to the new name. Raises a SystemCallError
3192 * if the file cannot be renamed.
3194 * File.rename("afile", "afile.bak") #=> 0
3197 static VALUE
3198 rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
3200 struct rename_args ra;
3201 VALUE f, t;
3203 FilePathValue(from);
3204 FilePathValue(to);
3205 f = rb_str_encode_ospath(from);
3206 t = rb_str_encode_ospath(to);
3207 ra.src = StringValueCStr(f);
3208 ra.dst = StringValueCStr(t);
3209 #if defined __CYGWIN__
3210 errno = 0;
3211 #endif
3212 if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra,
3213 RUBY_UBF_IO, 0) < 0) {
3214 int e = errno;
3215 #if defined DOSISH
3216 switch (e) {
3217 case EEXIST:
3218 if (chmod(ra.dst, 0666) == 0 &&
3219 unlink(ra.dst) == 0 &&
3220 rename(ra.src, ra.dst) == 0)
3221 return INT2FIX(0);
3223 #endif
3224 syserr_fail2(e, from, to);
3227 return INT2FIX(0);
3231 * call-seq:
3232 * File.umask() -> integer
3233 * File.umask(integer) -> integer
3235 * Returns the current umask value for this process. If the optional
3236 * argument is given, set the umask to that value and return the
3237 * previous value. Umask values are <em>subtracted</em> from the
3238 * default permissions, so a umask of <code>0222</code> would make a
3239 * file read-only for everyone.
3241 * File.umask(0006) #=> 18
3242 * File.umask #=> 6
3245 static VALUE
3246 rb_file_s_umask(int argc, VALUE *argv, VALUE _)
3248 mode_t omask = 0;
3250 switch (argc) {
3251 case 0:
3252 omask = umask(0);
3253 umask(omask);
3254 break;
3255 case 1:
3256 omask = umask(NUM2MODET(argv[0]));
3257 break;
3258 default:
3259 rb_error_arity(argc, 0, 1);
3261 return MODET2NUM(omask);
3264 #ifdef __CYGWIN__
3265 #undef DOSISH
3266 #endif
3267 #if defined __CYGWIN__ || defined DOSISH
3268 #define DOSISH_UNC
3269 #define DOSISH_DRIVE_LETTER
3270 #define FILE_ALT_SEPARATOR '\\'
3271 #endif
3272 #ifdef FILE_ALT_SEPARATOR
3273 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3274 # ifdef DOSISH
3275 static const char file_alt_separator[] = {FILE_ALT_SEPARATOR, '\0'};
3276 # endif
3277 #else
3278 #define isdirsep(x) ((x) == '/')
3279 #endif
3281 #ifndef USE_NTFS
3282 #if defined _WIN32
3283 #define USE_NTFS 1
3284 #else
3285 #define USE_NTFS 0
3286 #endif
3287 #endif
3288 #ifndef USE_NTFS_ADS
3289 # if USE_NTFS
3290 # define USE_NTFS_ADS 1
3291 # else
3292 # define USE_NTFS_ADS 0
3293 # endif
3294 #endif
3296 #if USE_NTFS
3297 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3298 #else
3299 #define istrailinggarbage(x) 0
3300 #endif
3301 #if USE_NTFS_ADS
3302 # define isADS(x) ((x) == ':')
3303 #else
3304 # define isADS(x) 0
3305 #endif
3307 #define Next(p, e, enc) ((p) + rb_enc_mbclen((p), (e), (enc)))
3308 #define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
3310 #if defined(DOSISH_UNC)
3311 #define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
3312 #else
3313 #define has_unc(buf) 0
3314 #endif
3316 #ifdef DOSISH_DRIVE_LETTER
3317 static inline int
3318 has_drive_letter(const char *buf)
3320 if (ISALPHA(buf[0]) && buf[1] == ':') {
3321 return 1;
3323 else {
3324 return 0;
3328 #ifndef _WIN32
3329 static char*
3330 getcwdofdrv(int drv)
3332 char drive[4];
3333 char *drvcwd, *oldcwd;
3335 drive[0] = drv;
3336 drive[1] = ':';
3337 drive[2] = '\0';
3339 /* the only way that I know to get the current directory
3340 of a particular drive is to change chdir() to that drive,
3341 so save the old cwd before chdir()
3343 oldcwd = ruby_getcwd();
3344 if (chdir(drive) == 0) {
3345 drvcwd = ruby_getcwd();
3346 chdir(oldcwd);
3347 xfree(oldcwd);
3349 else {
3350 /* perhaps the drive is not exist. we return only drive letter */
3351 drvcwd = strdup(drive);
3353 return drvcwd;
3356 static inline int
3357 not_same_drive(VALUE path, int drive)
3359 const char *p = RSTRING_PTR(path);
3360 if (RSTRING_LEN(path) < 2) return 0;
3361 if (has_drive_letter(p)) {
3362 return TOLOWER(p[0]) != TOLOWER(drive);
3364 else {
3365 return has_unc(p);
3368 #endif
3369 #endif
3371 static inline char *
3372 skiproot(const char *path, const char *end, rb_encoding *enc)
3374 #ifdef DOSISH_DRIVE_LETTER
3375 if (path + 2 <= end && has_drive_letter(path)) path += 2;
3376 #endif
3377 while (path < end && isdirsep(*path)) path++;
3378 return (char *)path;
3381 #define nextdirsep rb_enc_path_next
3382 char *
3383 rb_enc_path_next(const char *s, const char *e, rb_encoding *enc)
3385 while (s < e && !isdirsep(*s)) {
3386 Inc(s, e, enc);
3388 return (char *)s;
3391 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3392 #define skipprefix rb_enc_path_skip_prefix
3393 #else
3394 #define skipprefix(path, end, enc) (path)
3395 #endif
3396 char *
3397 rb_enc_path_skip_prefix(const char *path, const char *end, rb_encoding *enc)
3399 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3400 #ifdef DOSISH_UNC
3401 if (path + 2 <= end && isdirsep(path[0]) && isdirsep(path[1])) {
3402 path += 2;
3403 while (path < end && isdirsep(*path)) path++;
3404 if ((path = rb_enc_path_next(path, end, enc)) < end && path[0] && path[1] && !isdirsep(path[1]))
3405 path = rb_enc_path_next(path + 1, end, enc);
3406 return (char *)path;
3408 #endif
3409 #ifdef DOSISH_DRIVE_LETTER
3410 if (has_drive_letter(path))
3411 return (char *)(path + 2);
3412 #endif
3413 #endif
3414 return (char *)path;
3417 static inline char *
3418 skipprefixroot(const char *path, const char *end, rb_encoding *enc)
3420 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3421 char *p = skipprefix(path, end, enc);
3422 while (isdirsep(*p)) p++;
3423 return p;
3424 #else
3425 return skiproot(path, end, enc);
3426 #endif
3429 #define strrdirsep rb_enc_path_last_separator
3430 char *
3431 rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
3433 char *last = NULL;
3434 while (path < end) {
3435 if (isdirsep(*path)) {
3436 const char *tmp = path++;
3437 while (path < end && isdirsep(*path)) path++;
3438 if (path >= end) break;
3439 last = (char *)tmp;
3441 else {
3442 Inc(path, end, enc);
3445 return last;
3448 static char *
3449 chompdirsep(const char *path, const char *end, rb_encoding *enc)
3451 while (path < end) {
3452 if (isdirsep(*path)) {
3453 const char *last = path++;
3454 while (path < end && isdirsep(*path)) path++;
3455 if (path >= end) return (char *)last;
3457 else {
3458 Inc(path, end, enc);
3461 return (char *)path;
3464 char *
3465 rb_enc_path_end(const char *path, const char *end, rb_encoding *enc)
3467 if (path < end && isdirsep(*path)) path++;
3468 return chompdirsep(path, end, enc);
3471 static rb_encoding *
3472 fs_enc_check(VALUE path1, VALUE path2)
3474 rb_encoding *enc = rb_enc_check(path1, path2);
3475 int encidx = rb_enc_to_index(enc);
3476 if (encidx == ENCINDEX_US_ASCII) {
3477 encidx = rb_enc_get_index(path1);
3478 if (encidx == ENCINDEX_US_ASCII)
3479 encidx = rb_enc_get_index(path2);
3480 enc = rb_enc_from_index(encidx);
3482 return enc;
3485 #if USE_NTFS
3486 static char *
3487 ntfs_tail(const char *path, const char *end, rb_encoding *enc)
3489 while (path < end && *path == '.') path++;
3490 while (path < end && !isADS(*path)) {
3491 if (istrailinggarbage(*path)) {
3492 const char *last = path++;
3493 while (path < end && istrailinggarbage(*path)) path++;
3494 if (path >= end || isADS(*path)) return (char *)last;
3496 else if (isdirsep(*path)) {
3497 const char *last = path++;
3498 while (path < end && isdirsep(*path)) path++;
3499 if (path >= end) return (char *)last;
3500 if (isADS(*path)) path++;
3502 else {
3503 Inc(path, end, enc);
3506 return (char *)path;
3508 #endif
3510 #define BUFCHECK(cond) do {\
3511 bdiff = p - buf;\
3512 if (cond) {\
3513 do {buflen *= 2;} while (cond);\
3514 rb_str_resize(result, buflen);\
3515 buf = RSTRING_PTR(result);\
3516 p = buf + bdiff;\
3517 pend = buf + buflen;\
3519 } while (0)
3521 #define BUFINIT() (\
3522 p = buf = RSTRING_PTR(result),\
3523 buflen = RSTRING_LEN(result),\
3524 pend = p + buflen)
3526 #ifdef __APPLE__
3527 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3528 #else
3529 # define SKIPPATHSEP(p) 1
3530 #endif
3532 #define BUFCOPY(srcptr, srclen) do { \
3533 const int skip = SKIPPATHSEP(p); \
3534 rb_str_set_len(result, p-buf+skip); \
3535 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
3536 p += skip; \
3537 memcpy(p, (srcptr), (srclen)); \
3538 p += (srclen); \
3539 } while (0)
3541 #define WITH_ROOTDIFF(stmt) do { \
3542 long rootdiff = root - buf; \
3543 stmt; \
3544 root = buf + rootdiff; \
3545 } while (0)
3547 static VALUE
3548 copy_home_path(VALUE result, const char *dir)
3550 char *buf;
3551 #if defined DOSISH || defined __CYGWIN__
3552 char *p, *bend;
3553 rb_encoding *enc;
3554 #endif
3555 long dirlen;
3556 int encidx;
3558 dirlen = strlen(dir);
3559 rb_str_resize(result, dirlen);
3560 memcpy(buf = RSTRING_PTR(result), dir, dirlen);
3561 encidx = rb_filesystem_encindex();
3562 rb_enc_associate_index(result, encidx);
3563 #if defined DOSISH || defined __CYGWIN__
3564 enc = rb_enc_from_index(encidx);
3565 for (bend = (p = buf) + dirlen; p < bend; Inc(p, bend, enc)) {
3566 if (*p == '\\') {
3567 *p = '/';
3570 #endif
3571 return result;
3574 VALUE
3575 rb_home_dir_of(VALUE user, VALUE result)
3577 #ifdef HAVE_PWD_H
3578 struct passwd *pwPtr;
3579 #else
3580 extern char *getlogin(void);
3581 const char *pwPtr = 0;
3582 # define endpwent() ((void)0)
3583 #endif
3584 const char *dir, *username = RSTRING_PTR(user);
3585 rb_encoding *enc = rb_enc_get(user);
3586 #if defined _WIN32
3587 rb_encoding *fsenc = rb_utf8_encoding();
3588 #else
3589 rb_encoding *fsenc = rb_filesystem_encoding();
3590 #endif
3591 if (enc != fsenc) {
3592 dir = username = RSTRING_PTR(rb_str_conv_enc(user, enc, fsenc));
3595 #ifdef HAVE_PWD_H
3596 pwPtr = getpwnam(username);
3597 #else
3598 if (strcasecmp(username, getlogin()) == 0)
3599 dir = pwPtr = getenv("HOME");
3600 #endif
3601 if (!pwPtr) {
3602 endpwent();
3603 rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user);
3605 #ifdef HAVE_PWD_H
3606 dir = pwPtr->pw_dir;
3607 #endif
3608 copy_home_path(result, dir);
3609 endpwent();
3610 return result;
3613 #ifndef _WIN32
3614 VALUE
3615 rb_default_home_dir(VALUE result)
3617 const char *dir = getenv("HOME");
3619 #if defined HAVE_PWD_H
3620 if (!dir) {
3621 /* We'll look up the user's default home dir in the password db by
3622 * login name, if possible, and failing that will fall back to looking
3623 * the information up by uid (as would be needed for processes that
3624 * are not a descendant of login(1) or a work-alike).
3626 * While the lookup by uid is more likely to succeed (since we always
3627 * have a uid, but may or may not have a login name), we prefer first
3628 * looking up by name to accommodate the possibility of multiple login
3629 * names (each with its own record in the password database, so each
3630 * with a potentially different home directory) being mapped to the
3631 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
3633 VALUE login_name = rb_getlogin();
3635 # if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
3636 /* This is a corner case, but for backward compatibility reasons we
3637 * want to emit this error if neither the lookup by login name nor
3638 * lookup by getuid() has a chance of succeeding.
3640 if (NIL_P(login_name)) {
3641 rb_raise(rb_eArgError, "couldn't find login name -- expanding `~'");
3643 # endif
3645 VALUE pw_dir = rb_getpwdirnam_for_login(login_name);
3646 if (NIL_P(pw_dir)) {
3647 pw_dir = rb_getpwdiruid();
3648 if (NIL_P(pw_dir)) {
3649 rb_raise(rb_eArgError, "couldn't find home for uid `%ld'", (long)getuid());
3653 /* found it */
3654 copy_home_path(result, RSTRING_PTR(pw_dir));
3655 rb_str_resize(pw_dir, 0);
3656 return result;
3658 #endif
3659 if (!dir) {
3660 rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'");
3662 return copy_home_path(result, dir);
3665 static VALUE
3666 ospath_new(const char *ptr, long len, rb_encoding *fsenc)
3668 #if NORMALIZE_UTF8PATH
3669 VALUE path = rb_str_normalize_ospath(ptr, len);
3670 rb_enc_associate(path, fsenc);
3671 return path;
3672 #else
3673 return rb_enc_str_new(ptr, len, fsenc);
3674 #endif
3677 static char *
3678 append_fspath(VALUE result, VALUE fname, char *dir, rb_encoding **enc, rb_encoding *fsenc)
3680 char *buf, *cwdp = dir;
3681 VALUE dirname = Qnil;
3682 size_t dirlen = strlen(dir), buflen = rb_str_capacity(result);
3684 if (NORMALIZE_UTF8PATH || *enc != fsenc) {
3685 rb_encoding *direnc = fs_enc_check(fname, dirname = ospath_new(dir, dirlen, fsenc));
3686 if (direnc != fsenc) {
3687 dirname = rb_str_conv_enc(dirname, fsenc, direnc);
3688 RSTRING_GETMEM(dirname, cwdp, dirlen);
3690 else if (NORMALIZE_UTF8PATH) {
3691 RSTRING_GETMEM(dirname, cwdp, dirlen);
3693 *enc = direnc;
3695 do {buflen *= 2;} while (dirlen > buflen);
3696 rb_str_resize(result, buflen);
3697 buf = RSTRING_PTR(result);
3698 memcpy(buf, cwdp, dirlen);
3699 xfree(dir);
3700 if (!NIL_P(dirname)) rb_str_resize(dirname, 0);
3701 rb_enc_associate(result, *enc);
3702 return buf + dirlen;
3705 VALUE
3706 rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_name, VALUE result)
3708 const char *s, *b, *fend;
3709 char *buf, *p, *pend, *root;
3710 size_t buflen, bdiff;
3711 rb_encoding *enc, *fsenc = rb_filesystem_encoding();
3713 s = StringValuePtr(fname);
3714 fend = s + RSTRING_LEN(fname);
3715 enc = rb_enc_get(fname);
3716 BUFINIT();
3718 if (s[0] == '~' && abs_mode == 0) { /* execute only if NOT absolute_path() */
3719 long userlen = 0;
3720 if (isdirsep(s[1]) || s[1] == '\0') {
3721 buf = 0;
3722 b = 0;
3723 rb_str_set_len(result, 0);
3724 if (*++s) ++s;
3725 rb_default_home_dir(result);
3727 else {
3728 s = nextdirsep(b = s, fend, enc);
3729 b++; /* b[0] is '~' */
3730 userlen = s - b;
3731 BUFCHECK(bdiff + userlen >= buflen);
3732 memcpy(p, b, userlen);
3733 ENC_CODERANGE_CLEAR(result);
3734 rb_str_set_len(result, userlen);
3735 rb_enc_associate(result, enc);
3736 rb_home_dir_of(result, result);
3737 buf = p + 1;
3738 p += userlen;
3740 if (!rb_is_absolute_path(RSTRING_PTR(result))) {
3741 if (userlen) {
3742 rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE,
3743 (int)userlen, b, fname);
3745 else {
3746 rb_raise(rb_eArgError, "non-absolute home");
3749 BUFINIT();
3750 p = pend;
3752 #ifdef DOSISH_DRIVE_LETTER
3753 /* skip drive letter */
3754 else if (has_drive_letter(s)) {
3755 if (isdirsep(s[2])) {
3756 /* specified drive letter, and full path */
3757 /* skip drive letter */
3758 BUFCHECK(bdiff + 2 >= buflen);
3759 memcpy(p, s, 2);
3760 p += 2;
3761 s += 2;
3762 rb_enc_copy(result, fname);
3764 else {
3765 /* specified drive, but not full path */
3766 int same = 0;
3767 if (!NIL_P(dname) && !not_same_drive(dname, s[0])) {
3768 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3769 BUFINIT();
3770 if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) {
3771 /* ok, same drive */
3772 same = 1;
3775 if (!same) {
3776 char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc);
3777 BUFINIT();
3778 p = e;
3780 else {
3781 rb_enc_associate(result, enc = fs_enc_check(result, fname));
3782 p = pend;
3784 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3785 s += 2;
3788 #endif
3789 else if (!rb_is_absolute_path(s)) {
3790 if (!NIL_P(dname)) {
3791 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3792 rb_enc_associate(result, fs_enc_check(result, fname));
3793 BUFINIT();
3794 p = pend;
3796 else {
3797 char *e = append_fspath(result, fname, ruby_getcwd(), &enc, fsenc);
3798 BUFINIT();
3799 p = e;
3801 #if defined DOSISH || defined __CYGWIN__
3802 if (isdirsep(*s)) {
3803 /* specified full path, but not drive letter nor UNC */
3804 /* we need to get the drive letter or UNC share name */
3805 p = skipprefix(buf, p, enc);
3807 else
3808 #endif
3809 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3811 else {
3812 size_t len;
3813 b = s;
3814 do s++; while (isdirsep(*s));
3815 len = s - b;
3816 p = buf + len;
3817 BUFCHECK(bdiff >= buflen);
3818 memset(buf, '/', len);
3819 rb_str_set_len(result, len);
3820 rb_enc_associate(result, fs_enc_check(result, fname));
3822 if (p > buf && p[-1] == '/')
3823 --p;
3824 else {
3825 rb_str_set_len(result, p-buf);
3826 BUFCHECK(bdiff + 1 >= buflen);
3827 *p = '/';
3830 rb_str_set_len(result, p-buf+1);
3831 BUFCHECK(bdiff + 1 >= buflen);
3832 p[1] = 0;
3833 root = skipprefix(buf, p+1, enc);
3835 b = s;
3836 while (*s) {
3837 switch (*s) {
3838 case '.':
3839 if (b == s++) { /* beginning of path element */
3840 switch (*s) {
3841 case '\0':
3842 b = s;
3843 break;
3844 case '.':
3845 if (*(s+1) == '\0' || isdirsep(*(s+1))) {
3846 /* We must go back to the parent */
3847 char *n;
3848 *p = '\0';
3849 if (!(n = strrdirsep(root, p, enc))) {
3850 *p = '/';
3852 else {
3853 p = n;
3855 b = ++s;
3857 #if USE_NTFS
3858 else {
3859 do ++s; while (istrailinggarbage(*s));
3861 #endif
3862 break;
3863 case '/':
3864 #if defined DOSISH || defined __CYGWIN__
3865 case '\\':
3866 #endif
3867 b = ++s;
3868 break;
3869 default:
3870 /* ordinary path element, beginning don't move */
3871 break;
3874 #if USE_NTFS
3875 else {
3876 --s;
3877 case ' ': {
3878 const char *e = s;
3879 while (s < fend && istrailinggarbage(*s)) s++;
3880 if (s >= fend) {
3881 s = e;
3882 goto endpath;
3886 #endif
3887 break;
3888 case '/':
3889 #if defined DOSISH || defined __CYGWIN__
3890 case '\\':
3891 #endif
3892 if (s > b) {
3893 WITH_ROOTDIFF(BUFCOPY(b, s-b));
3894 *p = '/';
3896 b = ++s;
3897 break;
3898 default:
3899 #ifdef __APPLE__
3901 int n = ignored_char_p(s, fend, enc);
3902 if (n) {
3903 if (s > b) {
3904 WITH_ROOTDIFF(BUFCOPY(b, s-b));
3905 *p = '\0';
3907 b = s += n;
3908 break;
3911 #endif
3912 Inc(s, fend, enc);
3913 break;
3917 if (s > b) {
3918 #if USE_NTFS
3919 # if USE_NTFS_ADS
3920 static const char prime[] = ":$DATA";
3921 enum {prime_len = sizeof(prime) -1};
3922 # endif
3923 endpath:
3924 # if USE_NTFS_ADS
3925 if (s > b + prime_len && strncasecmp(s - prime_len, prime, prime_len) == 0) {
3926 /* alias of stream */
3927 /* get rid of a bug of x64 VC++ */
3928 if (isADS(*(s - (prime_len+1)))) {
3929 s -= prime_len + 1; /* prime */
3931 else if (memchr(b, ':', s - prime_len - b)) {
3932 s -= prime_len; /* alternative */
3935 # endif
3936 #endif
3937 BUFCOPY(b, s-b);
3938 rb_str_set_len(result, p-buf);
3940 if (p == skiproot(buf, p + !!*p, enc) - 1) p++;
3942 #if USE_NTFS
3943 *p = '\0';
3944 if ((s = strrdirsep(b = buf, p, enc)) != 0 && !strpbrk(s, "*?")) {
3945 VALUE tmp, v;
3946 size_t len;
3947 int encidx;
3948 WCHAR *wstr;
3949 WIN32_FIND_DATAW wfd;
3950 HANDLE h;
3951 #ifdef __CYGWIN__
3952 #ifdef HAVE_CYGWIN_CONV_PATH
3953 char *w32buf = NULL;
3954 const int flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE;
3955 #else
3956 char w32buf[MAXPATHLEN];
3957 #endif
3958 const char *path;
3959 ssize_t bufsize;
3960 int lnk_added = 0, is_symlink = 0;
3961 struct stat st;
3962 p = (char *)s;
3963 len = strlen(p);
3964 if (lstat_without_gvl(buf, &st) == 0 && S_ISLNK(st.st_mode)) {
3965 is_symlink = 1;
3966 if (len > 4 && STRCASECMP(p + len - 4, ".lnk") != 0) {
3967 lnk_added = 1;
3970 path = *buf ? buf : "/";
3971 #ifdef HAVE_CYGWIN_CONV_PATH
3972 bufsize = cygwin_conv_path(flags, path, NULL, 0);
3973 if (bufsize > 0) {
3974 bufsize += len;
3975 if (lnk_added) bufsize += 4;
3976 w32buf = ALLOCA_N(char, bufsize);
3977 if (cygwin_conv_path(flags, path, w32buf, bufsize) == 0) {
3978 b = w32buf;
3981 #else
3982 bufsize = MAXPATHLEN;
3983 if (cygwin_conv_to_win32_path(path, w32buf) == 0) {
3984 b = w32buf;
3986 #endif
3987 if (is_symlink && b == w32buf) {
3988 *p = '\\';
3989 strlcat(w32buf, p, bufsize);
3990 if (lnk_added) {
3991 strlcat(w32buf, ".lnk", bufsize);
3994 else {
3995 lnk_added = 0;
3997 *p = '/';
3998 #endif
3999 rb_str_set_len(result, p - buf + strlen(p));
4000 encidx = ENCODING_GET(result);
4001 tmp = result;
4002 if (encidx != ENCINDEX_UTF_8 && rb_enc_str_coderange(result) != ENC_CODERANGE_7BIT) {
4003 tmp = rb_str_encode_ospath(result);
4005 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
4006 wstr = ALLOCV_N(WCHAR, v, len);
4007 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, wstr, len);
4008 if (tmp != result) rb_str_set_len(tmp, 0);
4009 h = FindFirstFileW(wstr, &wfd);
4010 ALLOCV_END(v);
4011 if (h != INVALID_HANDLE_VALUE) {
4012 size_t wlen;
4013 FindClose(h);
4014 len = lstrlenW(wfd.cFileName);
4015 #ifdef __CYGWIN__
4016 if (lnk_added && len > 4 &&
4017 wcscasecmp(wfd.cFileName + len - 4, L".lnk") == 0) {
4018 wfd.cFileName[len -= 4] = L'\0';
4020 #else
4021 p = (char *)s;
4022 #endif
4023 ++p;
4024 wlen = (int)len;
4025 len = WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, NULL, 0, NULL, NULL);
4026 if (tmp == result) {
4027 BUFCHECK(bdiff + len >= buflen);
4028 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, p, len + 1, NULL, NULL);
4030 else {
4031 rb_str_modify_expand(tmp, len);
4032 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, RSTRING_PTR(tmp), len + 1, NULL, NULL);
4033 rb_str_cat_conv_enc_opts(result, bdiff, RSTRING_PTR(tmp), len,
4034 rb_utf8_encoding(), 0, Qnil);
4035 BUFINIT();
4036 rb_str_resize(tmp, 0);
4038 p += len;
4040 #ifdef __CYGWIN__
4041 else {
4042 p += strlen(p);
4044 #endif
4046 #endif
4048 rb_str_set_len(result, p - buf);
4049 rb_enc_check(fname, result);
4050 ENC_CODERANGE_CLEAR(result);
4051 return result;
4053 #endif /* _WIN32 */
4055 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, MAXPATHLEN + 2)
4057 static VALUE
4058 str_shrink(VALUE str)
4060 rb_str_resize(str, RSTRING_LEN(str));
4061 return str;
4064 #define expand_path(fname, dname, abs_mode, long_name, result) \
4065 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
4067 #define check_expand_path_args(fname, dname) \
4068 (((fname) = rb_get_path(fname)), \
4069 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
4071 static VALUE
4072 file_expand_path_1(VALUE fname)
4074 return rb_file_expand_path_internal(fname, Qnil, 0, 0, EXPAND_PATH_BUFFER());
4077 VALUE
4078 rb_file_expand_path(VALUE fname, VALUE dname)
4080 check_expand_path_args(fname, dname);
4081 return expand_path(fname, dname, 0, 1, EXPAND_PATH_BUFFER());
4084 VALUE
4085 rb_file_expand_path_fast(VALUE fname, VALUE dname)
4087 return expand_path(fname, dname, 0, 0, EXPAND_PATH_BUFFER());
4090 VALUE
4091 rb_file_s_expand_path(int argc, const VALUE *argv)
4093 rb_check_arity(argc, 1, 2);
4094 return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil);
4098 * call-seq:
4099 * File.expand_path(file_name [, dir_string] ) -> abs_file_name
4101 * Converts a pathname to an absolute pathname. Relative paths are
4102 * referenced from the current working directory of the process unless
4103 * +dir_string+ is given, in which case it will be used as the
4104 * starting point. The given pathname may start with a
4105 * ``<code>~</code>'', which expands to the process owner's home
4106 * directory (the environment variable +HOME+ must be set
4107 * correctly). ``<code>~</code><i>user</i>'' expands to the named
4108 * user's home directory.
4110 * File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
4112 * A simple example of using +dir_string+ is as follows.
4113 * File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
4115 * A more complex example which also resolves parent directory is as follows.
4116 * Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
4118 * File.expand_path("../../lib/mygem.rb", __FILE__)
4119 * #=> ".../path/to/project/lib/mygem.rb"
4121 * So first it resolves the parent of __FILE__, that is bin/, then go to the
4122 * parent, the root of the project and appends +lib/mygem.rb+.
4125 static VALUE
4126 s_expand_path(int c, const VALUE * v, VALUE _)
4128 return rb_file_s_expand_path(c, v);
4131 VALUE
4132 rb_file_absolute_path(VALUE fname, VALUE dname)
4134 check_expand_path_args(fname, dname);
4135 return expand_path(fname, dname, 1, 1, EXPAND_PATH_BUFFER());
4138 VALUE
4139 rb_file_s_absolute_path(int argc, const VALUE *argv)
4141 rb_check_arity(argc, 1, 2);
4142 return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil);
4146 * call-seq:
4147 * File.absolute_path(file_name [, dir_string] ) -> abs_file_name
4149 * Converts a pathname to an absolute pathname. Relative paths are
4150 * referenced from the current working directory of the process unless
4151 * <i>dir_string</i> is given, in which case it will be used as the
4152 * starting point. If the given pathname starts with a ``<code>~</code>''
4153 * it is NOT expanded, it is treated as a normal directory name.
4155 * File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4158 static VALUE
4159 s_absolute_path(int c, const VALUE * v, VALUE _)
4161 return rb_file_s_absolute_path(c, v);
4165 * call-seq:
4166 * File.absolute_path?(file_name) -> true or false
4168 * Returns <code>true</code> if +file_name+ is an absolute path, and
4169 * <code>false</code> otherwise.
4171 * File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4174 static VALUE
4175 s_absolute_path_p(VALUE klass, VALUE fname)
4177 VALUE path = rb_get_path(fname);
4179 if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse;
4180 return Qtrue;
4183 enum rb_realpath_mode {
4184 RB_REALPATH_CHECK,
4185 RB_REALPATH_DIR,
4186 RB_REALPATH_STRICT,
4187 RB_REALPATH_MODE_MAX
4190 static int
4191 realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE fallback,
4192 VALUE loopcheck, enum rb_realpath_mode mode, int last)
4194 const char *pend = unresolved + strlen(unresolved);
4195 rb_encoding *enc = rb_enc_get(*resolvedp);
4196 ID resolving;
4197 CONST_ID(resolving, "resolving");
4198 while (unresolved < pend) {
4199 const char *testname = unresolved;
4200 const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc);
4201 long testnamelen = unresolved_firstsep - unresolved;
4202 const char *unresolved_nextname = unresolved_firstsep;
4203 while (unresolved_nextname < pend && isdirsep(*unresolved_nextname))
4204 unresolved_nextname++;
4205 unresolved = unresolved_nextname;
4206 if (testnamelen == 1 && testname[0] == '.') {
4208 else if (testnamelen == 2 && testname[0] == '.' && testname[1] == '.') {
4209 if (*prefixlenp < RSTRING_LEN(*resolvedp)) {
4210 const char *resolved_str = RSTRING_PTR(*resolvedp);
4211 const char *resolved_names = resolved_str + *prefixlenp;
4212 const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), enc);
4213 long len = lastsep ? lastsep - resolved_names : 0;
4214 rb_str_resize(*resolvedp, *prefixlenp + len);
4217 else {
4218 VALUE checkval;
4219 VALUE testpath = rb_str_dup(*resolvedp);
4220 if (*prefixlenp < RSTRING_LEN(testpath))
4221 rb_str_cat2(testpath, "/");
4222 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4223 if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) {
4224 const char *prefix = RSTRING_PTR(testpath);
4225 const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc);
4226 if (!isdirsep(*last)) rb_str_cat2(testpath, "/");
4228 #endif
4229 rb_str_cat(testpath, testname, testnamelen);
4230 checkval = rb_hash_aref(loopcheck, testpath);
4231 if (!NIL_P(checkval)) {
4232 if (checkval == ID2SYM(resolving)) {
4233 if (mode == RB_REALPATH_CHECK) {
4234 errno = ELOOP;
4235 return -1;
4237 rb_syserr_fail_path(ELOOP, testpath);
4239 else {
4240 *resolvedp = rb_str_dup(checkval);
4243 else {
4244 struct stat sbuf;
4245 int ret;
4246 ret = lstat_without_gvl(RSTRING_PTR(testpath), &sbuf);
4247 if (ret == -1) {
4248 int e = errno;
4249 if (e == ENOENT && !NIL_P(fallback)) {
4250 if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) {
4251 rb_str_replace(*resolvedp, fallback);
4252 return 0;
4255 if (mode == RB_REALPATH_CHECK) return -1;
4256 if (e == ENOENT) {
4257 if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep)
4258 rb_syserr_fail_path(e, testpath);
4259 *resolvedp = testpath;
4260 break;
4262 else {
4263 rb_syserr_fail_path(e, testpath);
4266 #ifdef HAVE_READLINK
4267 if (S_ISLNK(sbuf.st_mode)) {
4268 VALUE link;
4269 VALUE link_orig = Qnil;
4270 const char *link_prefix, *link_names;
4271 long link_prefixlen;
4272 rb_hash_aset(loopcheck, testpath, ID2SYM(resolving));
4273 link = rb_readlink(testpath, enc);
4274 link_prefix = RSTRING_PTR(link);
4275 link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link));
4276 link_prefixlen = link_names - link_prefix;
4277 if (link_prefixlen > 0) {
4278 rb_encoding *tmpenc, *linkenc = rb_enc_get(link);
4279 link_orig = link;
4280 link = rb_str_subseq(link, 0, link_prefixlen);
4281 tmpenc = fs_enc_check(*resolvedp, link);
4282 if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc);
4283 *resolvedp = link;
4284 *prefixlenp = link_prefixlen;
4286 if (realpath_rec(prefixlenp, resolvedp, link_names, testpath,
4287 loopcheck, mode, !*unresolved_firstsep))
4288 return -1;
4289 RB_GC_GUARD(link_orig);
4290 rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp));
4292 else
4293 #endif
4295 VALUE s = rb_str_dup_frozen(testpath);
4296 rb_hash_aset(loopcheck, s, s);
4297 *resolvedp = testpath;
4302 return 0;
4305 static VALUE
4306 rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4308 long prefixlen;
4309 VALUE resolved;
4310 VALUE unresolved_path;
4311 VALUE loopcheck;
4312 VALUE curdir = Qnil;
4314 rb_encoding *enc;
4315 char *path_names = NULL, *basedir_names = NULL, *curdir_names = NULL;
4316 char *ptr, *prefixptr = NULL, *pend;
4317 long len;
4319 unresolved_path = rb_str_dup_frozen(path);
4321 if (!NIL_P(basedir)) {
4322 FilePathValue(basedir);
4323 basedir = TO_OSPATH(rb_str_dup_frozen(basedir));
4326 enc = rb_enc_get(unresolved_path);
4327 unresolved_path = TO_OSPATH(unresolved_path);
4328 RSTRING_GETMEM(unresolved_path, ptr, len);
4329 path_names = skipprefixroot(ptr, ptr + len, rb_enc_get(unresolved_path));
4330 if (ptr != path_names) {
4331 resolved = rb_str_subseq(unresolved_path, 0, path_names - ptr);
4332 goto root_found;
4335 if (!NIL_P(basedir)) {
4336 RSTRING_GETMEM(basedir, ptr, len);
4337 basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir));
4338 if (ptr != basedir_names) {
4339 resolved = rb_str_subseq(basedir, 0, basedir_names - ptr);
4340 goto root_found;
4344 curdir = rb_dir_getwd_ospath();
4345 RSTRING_GETMEM(curdir, ptr, len);
4346 curdir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(curdir));
4347 resolved = rb_str_subseq(curdir, 0, curdir_names - ptr);
4349 root_found:
4350 RSTRING_GETMEM(resolved, prefixptr, prefixlen);
4351 pend = prefixptr + prefixlen;
4352 ptr = chompdirsep(prefixptr, pend, enc);
4353 if (ptr < pend) {
4354 prefixlen = ++ptr - prefixptr;
4355 rb_str_set_len(resolved, prefixlen);
4357 #ifdef FILE_ALT_SEPARATOR
4358 while (prefixptr < ptr) {
4359 if (*prefixptr == FILE_ALT_SEPARATOR) {
4360 *prefixptr = '/';
4362 Inc(prefixptr, pend, enc);
4364 #endif
4366 switch (rb_enc_to_index(enc)) {
4367 case ENCINDEX_ASCII:
4368 case ENCINDEX_US_ASCII:
4369 rb_enc_associate_index(resolved, rb_filesystem_encindex());
4372 loopcheck = rb_hash_new();
4373 if (curdir_names) {
4374 if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0))
4375 return Qnil;
4377 if (basedir_names) {
4378 if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0))
4379 return Qnil;
4381 if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1))
4382 return Qnil;
4384 if (origenc && origenc != rb_enc_get(resolved)) {
4385 if (rb_enc_str_asciionly_p(resolved)) {
4386 rb_enc_associate(resolved, origenc);
4388 else {
4389 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4393 RB_GC_GUARD(unresolved_path);
4394 RB_GC_GUARD(curdir);
4395 return resolved;
4398 static VALUE rb_file_join(VALUE ary);
4400 #ifndef HAVE_REALPATH
4401 static VALUE
4402 rb_check_realpath_emulate_try(VALUE arg)
4404 VALUE *args = (VALUE *)arg;
4405 return rb_check_realpath_emulate(args[0], args[1], (rb_encoding *)args[2], RB_REALPATH_CHECK);
4408 static VALUE
4409 rb_check_realpath_emulate_rescue(VALUE arg, VALUE exc)
4411 return Qnil;
4413 #endif /* HAVE_REALPATH */
4415 static VALUE
4416 rb_check_realpath_internal(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4418 #ifdef HAVE_REALPATH
4419 VALUE unresolved_path;
4420 char *resolved_ptr = NULL;
4421 VALUE resolved;
4423 if (mode == RB_REALPATH_DIR) {
4424 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4427 unresolved_path = rb_str_dup_frozen(path);
4428 if (*RSTRING_PTR(unresolved_path) != '/' && !NIL_P(basedir)) {
4429 unresolved_path = rb_file_join(rb_assoc_new(basedir, unresolved_path));
4431 if (origenc) unresolved_path = TO_OSPATH(unresolved_path);
4433 if ((resolved_ptr = realpath(RSTRING_PTR(unresolved_path), NULL)) == NULL) {
4434 /* glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4435 returning ENOTDIR in that case.
4436 glibc realpath(3) can also return ENOENT for paths that exist,
4437 such as /dev/fd/5.
4438 Fallback to the emulated approach in either of those cases. */
4439 if (errno == ENOTDIR ||
4440 (errno == ENOENT && rb_file_exist_p(0, unresolved_path))) {
4441 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4444 if (mode == RB_REALPATH_CHECK) {
4445 return Qnil;
4447 rb_sys_fail_path(unresolved_path);
4449 resolved = ospath_new(resolved_ptr, strlen(resolved_ptr), rb_filesystem_encoding());
4450 free(resolved_ptr);
4452 # if !defined(__LINUX__) && !defined(__APPLE__)
4453 /* As `resolved` is a String in the filesystem encoding, no
4454 * conversion is needed */
4455 struct stat st;
4456 if (stat_without_gvl(RSTRING_PTR(resolved), &st) < 0) {
4457 if (mode == RB_REALPATH_CHECK) {
4458 return Qnil;
4460 rb_sys_fail_path(unresolved_path);
4462 # endif
4464 if (origenc && origenc != rb_enc_get(resolved)) {
4465 if (!rb_enc_str_asciionly_p(resolved)) {
4466 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4468 rb_enc_associate(resolved, origenc);
4471 if (rb_enc_str_coderange(resolved) == ENC_CODERANGE_BROKEN) {
4472 rb_enc_associate(resolved, rb_filesystem_encoding());
4473 if (rb_enc_str_coderange(resolved) == ENC_CODERANGE_BROKEN) {
4474 rb_enc_associate(resolved, rb_ascii8bit_encoding());
4478 RB_GC_GUARD(unresolved_path);
4479 return resolved;
4480 #else
4481 if (mode == RB_REALPATH_CHECK) {
4482 VALUE arg[3];
4483 arg[0] = basedir;
4484 arg[1] = path;
4485 arg[2] = (VALUE)origenc;
4487 return rb_rescue(rb_check_realpath_emulate_try, (VALUE)arg,
4488 rb_check_realpath_emulate_rescue, Qnil);
4490 else {
4491 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4493 #endif /* HAVE_REALPATH */
4496 VALUE
4497 rb_realpath_internal(VALUE basedir, VALUE path, int strict)
4499 const enum rb_realpath_mode mode =
4500 strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR;
4501 return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode);
4504 VALUE
4505 rb_check_realpath(VALUE basedir, VALUE path, rb_encoding *enc)
4507 return rb_check_realpath_internal(basedir, path, enc, RB_REALPATH_CHECK);
4511 * call-seq:
4512 * File.realpath(pathname [, dir_string]) -> real_pathname
4514 * Returns the real (absolute) pathname of _pathname_ in the actual
4515 * filesystem not containing symlinks or useless dots.
4517 * If _dir_string_ is given, it is used as a base directory
4518 * for interpreting relative pathname instead of the current directory.
4520 * All components of the pathname must exist when this method is
4521 * called.
4523 static VALUE
4524 rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
4526 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4527 VALUE path = argv[0];
4528 FilePathValue(path);
4529 return rb_realpath_internal(basedir, path, 1);
4533 * call-seq:
4534 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4536 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4537 * The real pathname doesn't contain symlinks or useless dots.
4539 * If _dir_string_ is given, it is used as a base directory
4540 * for interpreting relative pathname instead of the current directory.
4542 * The last component of the real pathname can be nonexistent.
4544 static VALUE
4545 rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
4547 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4548 VALUE path = argv[0];
4549 FilePathValue(path);
4550 return rb_realpath_internal(basedir, path, 0);
4553 static size_t
4554 rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc)
4556 int len1, len2;
4557 unsigned int c;
4558 const char *s, *last;
4560 if (!e || !l2) return 0;
4562 c = rb_enc_codepoint_len(e, e + l2, &len1, enc);
4563 if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) {
4564 if (c == '.') return l0;
4565 s = p;
4566 e = p + l1;
4567 last = e;
4568 while (s < e) {
4569 if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s;
4570 s += len1;
4572 return last - p;
4574 if (l1 < l2) return l1;
4576 s = p+l1-l2;
4577 if (rb_enc_left_char_head(p, s, p+l1, enc) != s) return 0;
4578 #if CASEFOLD_FILESYSTEM
4579 #define fncomp strncasecmp
4580 #else
4581 #define fncomp strncmp
4582 #endif
4583 if (fncomp(s, e, l2) == 0) {
4584 return l1-l2;
4586 return 0;
4589 const char *
4590 ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encoding *enc)
4592 const char *p, *q, *e, *end;
4593 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4594 const char *root;
4595 #endif
4596 long f = 0, n = -1;
4598 end = name + (alllen ? (size_t)*alllen : strlen(name));
4599 name = skipprefix(name, end, enc);
4600 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4601 root = name;
4602 #endif
4603 while (isdirsep(*name))
4604 name++;
4605 if (!*name) {
4606 p = name - 1;
4607 f = 1;
4608 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4609 if (name != root) {
4610 /* has slashes */
4612 #ifdef DOSISH_DRIVE_LETTER
4613 else if (*p == ':') {
4614 p++;
4615 f = 0;
4617 #endif
4618 #ifdef DOSISH_UNC
4619 else {
4620 p = "/";
4622 #endif
4623 #endif
4625 else {
4626 if (!(p = strrdirsep(name, end, enc))) {
4627 p = name;
4629 else {
4630 while (isdirsep(*p)) p++; /* skip last / */
4632 #if USE_NTFS
4633 n = ntfs_tail(p, end, enc) - p;
4634 #else
4635 n = chompdirsep(p, end, enc) - p;
4636 #endif
4637 for (q = p; q - p < n && *q == '.'; q++);
4638 for (e = 0; q - p < n; Inc(q, end, enc)) {
4639 if (*q == '.') e = q;
4641 if (e) f = e - p;
4642 else f = n;
4645 if (baselen)
4646 *baselen = f;
4647 if (alllen)
4648 *alllen = n;
4649 return p;
4653 * call-seq:
4654 * File.basename(file_name [, suffix] ) -> base_name
4656 * Returns the last component of the filename given in
4657 * <i>file_name</i> (after first stripping trailing separators),
4658 * which can be formed using both File::SEPARATOR and
4659 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4660 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4661 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4662 * any extension will be removed.
4664 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4665 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4666 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4669 static VALUE
4670 rb_file_s_basename(int argc, VALUE *argv, VALUE _)
4672 VALUE fname, fext, basename;
4673 const char *name, *p;
4674 long f, n;
4675 rb_encoding *enc;
4677 fext = Qnil;
4678 if (rb_check_arity(argc, 1, 2) == 2) {
4679 fext = argv[1];
4680 StringValue(fext);
4681 enc = check_path_encoding(fext);
4683 fname = argv[0];
4684 FilePathStringValue(fname);
4685 if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
4686 enc = rb_enc_get(fname);
4687 fext = Qnil;
4689 if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
4690 return rb_str_new_shared(fname);
4692 p = ruby_enc_find_basename(name, &f, &n, enc);
4693 if (n >= 0) {
4694 if (NIL_P(fext)) {
4695 f = n;
4697 else {
4698 const char *fp;
4699 fp = StringValueCStr(fext);
4700 if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
4701 f = n;
4703 RB_GC_GUARD(fext);
4705 if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
4708 basename = rb_str_new(p, f);
4709 rb_enc_copy(basename, fname);
4710 return basename;
4713 static VALUE rb_file_dirname_n(VALUE fname, int n);
4716 * call-seq:
4717 * File.dirname(file_name, level = 1) -> dir_name
4719 * Returns all components of the filename given in <i>file_name</i>
4720 * except the last one (after first stripping trailing separators).
4721 * The filename can be formed using both File::SEPARATOR and
4722 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4723 * not <code>nil</code>.
4725 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4727 * If +level+ is given, removes the last +level+ components, not only
4728 * one.
4730 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4731 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4734 static VALUE
4735 rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
4737 int n = 1;
4738 if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
4739 n = NUM2INT(argv[1]);
4741 return rb_file_dirname_n(argv[0], n);
4744 VALUE
4745 rb_file_dirname(VALUE fname)
4747 return rb_file_dirname_n(fname, 1);
4750 static VALUE
4751 rb_file_dirname_n(VALUE fname, int n)
4753 const char *name, *root, *p, *end;
4754 VALUE dirname;
4755 rb_encoding *enc;
4756 VALUE sepsv = 0;
4757 const char **seps;
4759 if (n < 0) rb_raise(rb_eArgError, "negative level: %d", n);
4760 FilePathStringValue(fname);
4761 name = StringValueCStr(fname);
4762 end = name + RSTRING_LEN(fname);
4763 enc = rb_enc_get(fname);
4764 root = skiproot(name, end, enc);
4765 #ifdef DOSISH_UNC
4766 if (root > name + 1 && isdirsep(*name))
4767 root = skipprefix(name = root - 2, end, enc);
4768 #else
4769 if (root > name + 1)
4770 name = root - 1;
4771 #endif
4772 if (n > (end - root + 1) / 2) {
4773 p = root;
4775 else {
4776 int i;
4777 switch (n) {
4778 case 0:
4779 p = end;
4780 break;
4781 case 1:
4782 if (!(p = strrdirsep(root, end, enc))) p = root;
4783 break;
4784 default:
4785 seps = ALLOCV_N(const char *, sepsv, n);
4786 for (i = 0; i < n; ++i) seps[i] = root;
4787 i = 0;
4788 for (p = root; p < end; ) {
4789 if (isdirsep(*p)) {
4790 const char *tmp = p++;
4791 while (p < end && isdirsep(*p)) p++;
4792 if (p >= end) break;
4793 seps[i++] = tmp;
4794 if (i == n) i = 0;
4796 else {
4797 Inc(p, end, enc);
4800 p = seps[i];
4801 ALLOCV_END(sepsv);
4802 break;
4805 if (p == name)
4806 return rb_usascii_str_new2(".");
4807 #ifdef DOSISH_DRIVE_LETTER
4808 if (has_drive_letter(name) && isdirsep(*(name + 2))) {
4809 const char *top = skiproot(name + 2, end, enc);
4810 dirname = rb_str_new(name, 3);
4811 rb_str_cat(dirname, top, p - top);
4813 else
4814 #endif
4815 dirname = rb_str_new(name, p - name);
4816 #ifdef DOSISH_DRIVE_LETTER
4817 if (has_drive_letter(name) && root == name + 2 && p - name == 2)
4818 rb_str_cat(dirname, ".", 1);
4819 #endif
4820 rb_enc_copy(dirname, fname);
4821 return dirname;
4825 * accept a String, and return the pointer of the extension.
4826 * if len is passed, set the length of extension to it.
4827 * returned pointer is in ``name'' or NULL.
4828 * returns *len
4829 * no dot NULL 0
4830 * dotfile top 0
4831 * end with dot dot 1
4832 * .ext dot len of .ext
4833 * .ext:stream dot len of .ext without :stream (NT only)
4836 const char *
4837 ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc)
4839 const char *p, *e, *end = name + (len ? *len : (long)strlen(name));
4841 p = strrdirsep(name, end, enc); /* get the last path component */
4842 if (!p)
4843 p = name;
4844 else
4845 do name = ++p; while (isdirsep(*p));
4847 e = 0;
4848 while (*p && *p == '.') p++;
4849 while (*p) {
4850 if (*p == '.' || istrailinggarbage(*p)) {
4851 #if USE_NTFS
4852 const char *last = p++, *dot = last;
4853 while (istrailinggarbage(*p)) {
4854 if (*p == '.') dot = p;
4855 p++;
4857 if (!*p || isADS(*p)) {
4858 p = last;
4859 break;
4861 if (*last == '.' || dot > last) e = dot;
4862 continue;
4863 #else
4864 e = p; /* get the last dot of the last component */
4865 #endif
4867 #if USE_NTFS
4868 else if (isADS(*p)) {
4869 break;
4871 #endif
4872 else if (isdirsep(*p))
4873 break;
4874 Inc(p, end, enc);
4877 if (len) {
4878 /* no dot, or the only dot is first or end? */
4879 if (!e || e == name)
4880 *len = 0;
4881 else if (e+1 == p)
4882 *len = 1;
4883 else
4884 *len = p - e;
4886 return e;
4890 * call-seq:
4891 * File.extname(path) -> string
4893 * Returns the extension (the portion of file name in +path+
4894 * starting from the last period).
4896 * If +path+ is a dotfile, or starts with a period, then the starting
4897 * dot is not dealt with the start of the extension.
4899 * An empty string will also be returned when the period is the last character
4900 * in +path+.
4902 * On Windows, trailing dots are truncated.
4904 * File.extname("test.rb") #=> ".rb"
4905 * File.extname("a/b/d/test.rb") #=> ".rb"
4906 * File.extname(".a/b/d/test.rb") #=> ".rb"
4907 * File.extname("foo.") #=> "" on Windows
4908 * File.extname("foo.") #=> "." on non-Windows
4909 * File.extname("test") #=> ""
4910 * File.extname(".profile") #=> ""
4911 * File.extname(".profile.sh") #=> ".sh"
4915 static VALUE
4916 rb_file_s_extname(VALUE klass, VALUE fname)
4918 const char *name, *e;
4919 long len;
4920 VALUE extname;
4922 FilePathStringValue(fname);
4923 name = StringValueCStr(fname);
4924 len = RSTRING_LEN(fname);
4925 e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
4926 if (len < 1)
4927 return rb_str_new(0, 0);
4928 extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
4929 return extname;
4933 * call-seq:
4934 * File.path(path) -> string
4936 * Returns the string representation of the path
4938 * File.path("/dev/null") #=> "/dev/null"
4939 * File.path(Pathname.new("/tmp")) #=> "/tmp"
4943 static VALUE
4944 rb_file_s_path(VALUE klass, VALUE fname)
4946 return rb_get_path(fname);
4950 * call-seq:
4951 * File.split(file_name) -> array
4953 * Splits the given string into a directory and a file component and
4954 * returns them in a two-element array. See also File::dirname and
4955 * File::basename.
4957 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
4960 static VALUE
4961 rb_file_s_split(VALUE klass, VALUE path)
4963 FilePathStringValue(path); /* get rid of converting twice */
4964 return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));
4967 static VALUE
4968 file_inspect_join(VALUE ary, VALUE arg, int recur)
4970 if (recur || ary == arg) rb_raise(rb_eArgError, "recursive array");
4971 return rb_file_join(arg);
4974 static VALUE
4975 rb_file_join(VALUE ary)
4977 long len, i;
4978 VALUE result, tmp;
4979 const char *name, *tail;
4980 int checked = TRUE;
4981 rb_encoding *enc;
4983 if (RARRAY_LEN(ary) == 0) return rb_str_new(0, 0);
4985 len = 1;
4986 for (i=0; i<RARRAY_LEN(ary); i++) {
4987 tmp = RARRAY_AREF(ary, i);
4988 if (RB_TYPE_P(tmp, T_STRING)) {
4989 check_path_encoding(tmp);
4990 len += RSTRING_LEN(tmp);
4992 else {
4993 len += 10;
4996 len += RARRAY_LEN(ary) - 1;
4997 result = rb_str_buf_new(len);
4998 RBASIC_CLEAR_CLASS(result);
4999 for (i=0; i<RARRAY_LEN(ary); i++) {
5000 tmp = RARRAY_AREF(ary, i);
5001 switch (OBJ_BUILTIN_TYPE(tmp)) {
5002 case T_STRING:
5003 if (!checked) check_path_encoding(tmp);
5004 StringValueCStr(tmp);
5005 break;
5006 case T_ARRAY:
5007 if (ary == tmp) {
5008 rb_raise(rb_eArgError, "recursive array");
5010 else {
5011 tmp = rb_exec_recursive(file_inspect_join, ary, tmp);
5013 break;
5014 default:
5015 FilePathStringValue(tmp);
5016 checked = FALSE;
5018 RSTRING_GETMEM(result, name, len);
5019 if (i == 0) {
5020 rb_enc_copy(result, tmp);
5022 else {
5023 tail = chompdirsep(name, name + len, rb_enc_get(result));
5024 if (RSTRING_PTR(tmp) && isdirsep(RSTRING_PTR(tmp)[0])) {
5025 rb_str_set_len(result, tail - name);
5027 else if (!*tail) {
5028 rb_str_cat(result, "/", 1);
5031 enc = fs_enc_check(result, tmp);
5032 rb_str_buf_append(result, tmp);
5033 rb_enc_associate(result, enc);
5035 RBASIC_SET_CLASS_RAW(result, rb_cString);
5037 return result;
5041 * call-seq:
5042 * File.join(string, ...) -> string
5044 * Returns a new string formed by joining the strings using
5045 * <code>"/"</code>.
5047 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5051 static VALUE
5052 rb_file_s_join(VALUE klass, VALUE args)
5054 return rb_file_join(args);
5057 #if defined(HAVE_TRUNCATE) || defined(HAVE_CHSIZE)
5058 struct truncate_arg {
5059 const char *path;
5060 #if defined(HAVE_TRUNCATE)
5061 #define NUM2POS(n) NUM2OFFT(n)
5062 off_t pos;
5063 #else
5064 #define NUM2POS(n) NUM2LONG(n)
5065 long pos;
5066 #endif
5069 static void *
5070 nogvl_truncate(void *ptr)
5072 struct truncate_arg *ta = ptr;
5073 #ifdef HAVE_TRUNCATE
5074 return (void *)(VALUE)truncate(ta->path, ta->pos);
5075 #else /* defined(HAVE_CHSIZE) */
5077 int tmpfd = rb_cloexec_open(ta->path, 0, 0);
5079 if (tmpfd < 0)
5080 return (void *)-1;
5081 rb_update_max_fd(tmpfd);
5082 if (chsize(tmpfd, ta->pos) < 0) {
5083 int e = errno;
5084 close(tmpfd);
5085 errno = e;
5086 return (void *)-1;
5088 close(tmpfd);
5089 return 0;
5091 #endif
5095 * call-seq:
5096 * File.truncate(file_name, integer) -> 0
5098 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5099 * bytes long. Not available on all platforms.
5101 * f = File.new("out", "w")
5102 * f.write("1234567890") #=> 10
5103 * f.close #=> nil
5104 * File.truncate("out", 5) #=> 0
5105 * File.size("out") #=> 5
5109 static VALUE
5110 rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
5112 struct truncate_arg ta;
5113 int r;
5115 ta.pos = NUM2POS(len);
5116 FilePathValue(path);
5117 path = rb_str_encode_ospath(path);
5118 ta.path = StringValueCStr(path);
5120 r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta,
5121 RUBY_UBF_IO, NULL);
5122 if (r < 0)
5123 rb_sys_fail_path(path);
5124 return INT2FIX(0);
5125 #undef NUM2POS
5127 #else
5128 #define rb_file_s_truncate rb_f_notimplement
5129 #endif
5131 #if defined(HAVE_FTRUNCATE) || defined(HAVE_CHSIZE)
5132 struct ftruncate_arg {
5133 int fd;
5134 #if defined(HAVE_FTRUNCATE)
5135 #define NUM2POS(n) NUM2OFFT(n)
5136 off_t pos;
5137 #else
5138 #define NUM2POS(n) NUM2LONG(n)
5139 long pos;
5140 #endif
5143 static VALUE
5144 nogvl_ftruncate(void *ptr)
5146 struct ftruncate_arg *fa = ptr;
5148 #ifdef HAVE_FTRUNCATE
5149 return (VALUE)ftruncate(fa->fd, fa->pos);
5150 #else /* defined(HAVE_CHSIZE) */
5151 return (VALUE)chsize(fa->fd, fa->pos);
5152 #endif
5156 * call-seq:
5157 * file.truncate(integer) -> 0
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.
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
5169 static VALUE
5170 rb_file_truncate(VALUE obj, VALUE len)
5172 rb_io_t *fptr;
5173 struct ftruncate_arg fa;
5175 fa.pos = NUM2POS(len);
5176 GetOpenFile(obj, fptr);
5177 if (!(fptr->mode & FMODE_WRITABLE)) {
5178 rb_raise(rb_eIOError, "not opened for writing");
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);
5185 return INT2FIX(0);
5186 #undef NUM2POS
5188 #else
5189 #define rb_file_truncate rb_f_notimplement
5190 #endif
5192 # ifndef LOCK_SH
5193 # define LOCK_SH 1
5194 # endif
5195 # ifndef LOCK_EX
5196 # define LOCK_EX 2
5197 # endif
5198 # ifndef LOCK_NB
5199 # define LOCK_NB 4
5200 # endif
5201 # ifndef LOCK_UN
5202 # define LOCK_UN 8
5203 # endif
5205 #ifdef __CYGWIN__
5206 #include <winerror.h>
5207 #endif
5209 static VALUE
5210 rb_thread_flock(void *data)
5212 #ifdef __CYGWIN__
5213 int old_errno = errno;
5214 #endif
5215 int *op = data, ret = flock(op[0], op[1]);
5217 #ifdef __CYGWIN__
5218 if (GetLastError() == ERROR_NOT_LOCKED) {
5219 ret = 0;
5220 errno = old_errno;
5222 #endif
5223 return (VALUE)ret;
5227 * call-seq:
5228 * file.flock(locking_constant) -> 0 or false
5230 * Locks or unlocks a file according to <i>locking_constant</i> (a
5231 * logical <em>or</em> of the values in the table below).
5232 * Returns <code>false</code> if File::LOCK_NB is specified and the
5233 * operation would otherwise have blocked. Not available on all
5234 * platforms.
5236 * Locking constants (in class File):
5238 * LOCK_EX | Exclusive lock. Only one process may hold an
5239 * | exclusive lock for a given file at a time.
5240 * ----------+------------------------------------------------
5241 * LOCK_NB | Don't block when locking. May be combined
5242 * | with other lock options using logical or.
5243 * ----------+------------------------------------------------
5244 * LOCK_SH | Shared lock. Multiple processes may each hold a
5245 * | shared lock for a given file at the same time.
5246 * ----------+------------------------------------------------
5247 * LOCK_UN | Unlock.
5249 * Example:
5251 * # update a counter using write lock
5252 * # don't use "w" because it truncates the file before lock.
5253 * File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
5254 * f.flock(File::LOCK_EX)
5255 * value = f.read.to_i + 1
5256 * f.rewind
5257 * f.write("#{value}\n")
5258 * f.flush
5259 * f.truncate(f.pos)
5262 * # read the counter using read lock
5263 * File.open("counter", "r") {|f|
5264 * f.flock(File::LOCK_SH)
5265 * p f.read
5270 static VALUE
5271 rb_file_flock(VALUE obj, VALUE operation)
5273 rb_io_t *fptr;
5274 int op[2], op1;
5275 struct timeval time;
5277 op[1] = op1 = NUM2INT(operation);
5278 GetOpenFile(obj, fptr);
5279 op[0] = fptr->fd;
5281 if (fptr->mode & FMODE_WRITABLE) {
5282 rb_io_flush_raw(obj, 0);
5284 while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) {
5285 int e = errno;
5286 switch (e) {
5287 case EAGAIN:
5288 case EACCES:
5289 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5290 case EWOULDBLOCK:
5291 #endif
5292 if (op1 & LOCK_NB) return Qfalse;
5294 time.tv_sec = 0;
5295 time.tv_usec = 100 * 1000; /* 0.1 sec */
5296 rb_thread_wait_for(time);
5297 rb_io_check_closed(fptr);
5298 continue;
5300 case EINTR:
5301 #if defined(ERESTART)
5302 case ERESTART:
5303 #endif
5304 break;
5306 default:
5307 rb_syserr_fail_path(e, fptr->pathv);
5310 return INT2FIX(0);
5313 static void
5314 test_check(int n, int argc, VALUE *argv)
5316 int i;
5318 n+=1;
5319 rb_check_arity(argc, n, n);
5320 for (i=1; i<n; i++) {
5321 if (!RB_TYPE_P(argv[i], T_FILE)) {
5322 FilePathValue(argv[i]);
5327 #define CHECK(n) test_check((n), argc, argv)
5330 * call-seq:
5331 * test(cmd, file1 [, file2] ) -> obj
5333 * Uses the character +cmd+ to perform various tests on +file1+ (first
5334 * table below) or on +file1+ and +file2+ (second table).
5336 * File tests on a single file:
5338 * Cmd Returns Meaning
5339 * "A" | Time | Last access time for file1
5340 * "b" | boolean | True if file1 is a block device
5341 * "c" | boolean | True if file1 is a character device
5342 * "C" | Time | Last change time for file1
5343 * "d" | boolean | True if file1 exists and is a directory
5344 * "e" | boolean | True if file1 exists
5345 * "f" | boolean | True if file1 exists and is a regular file
5346 * "g" | boolean | True if file1 has the \CF{setgid} bit
5347 * | | set (false under NT)
5348 * "G" | boolean | True if file1 exists and has a group
5349 * | | ownership equal to the caller's group
5350 * "k" | boolean | True if file1 exists and has the sticky bit set
5351 * "l" | boolean | True if file1 exists and is a symbolic link
5352 * "M" | Time | Last modification time for file1
5353 * "o" | boolean | True if file1 exists and is owned by
5354 * | | the caller's effective uid
5355 * "O" | boolean | True if file1 exists and is owned by
5356 * | | the caller's real uid
5357 * "p" | boolean | True if file1 exists and is a fifo
5358 * "r" | boolean | True if file1 is readable by the effective
5359 * | | uid/gid of the caller
5360 * "R" | boolean | True if file is readable by the real
5361 * | | uid/gid of the caller
5362 * "s" | int/nil | If file1 has nonzero size, return the size,
5363 * | | otherwise return nil
5364 * "S" | boolean | True if file1 exists and is a socket
5365 * "u" | boolean | True if file1 has the setuid bit set
5366 * "w" | boolean | True if file1 exists and is writable by
5367 * | | the effective uid/gid
5368 * "W" | boolean | True if file1 exists and is writable by
5369 * | | the real uid/gid
5370 * "x" | boolean | True if file1 exists and is executable by
5371 * | | the effective uid/gid
5372 * "X" | boolean | True if file1 exists and is executable by
5373 * | | the real uid/gid
5374 * "z" | boolean | True if file1 exists and has a zero length
5376 * Tests that take two files:
5378 * "-" | boolean | True if file1 and file2 are identical
5379 * "=" | boolean | True if the modification times of file1
5380 * | | and file2 are equal
5381 * "<" | boolean | True if the modification time of file1
5382 * | | is prior to that of file2
5383 * ">" | boolean | True if the modification time of file1
5384 * | | is after that of file2
5387 static VALUE
5388 rb_f_test(int argc, VALUE *argv, VALUE _)
5390 int cmd;
5392 if (argc == 0) rb_check_arity(argc, 2, 3);
5393 cmd = NUM2CHR(argv[0]);
5394 if (cmd == 0) {
5395 goto unknown;
5397 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
5398 CHECK(1);
5399 switch (cmd) {
5400 case 'b':
5401 return rb_file_blockdev_p(0, argv[1]);
5403 case 'c':
5404 return rb_file_chardev_p(0, argv[1]);
5406 case 'd':
5407 return rb_file_directory_p(0, argv[1]);
5409 case 'e':
5410 return rb_file_exist_p(0, argv[1]);
5412 case 'f':
5413 return rb_file_file_p(0, argv[1]);
5415 case 'g':
5416 return rb_file_sgid_p(0, argv[1]);
5418 case 'G':
5419 return rb_file_grpowned_p(0, argv[1]);
5421 case 'k':
5422 return rb_file_sticky_p(0, argv[1]);
5424 case 'l':
5425 return rb_file_symlink_p(0, argv[1]);
5427 case 'o':
5428 return rb_file_owned_p(0, argv[1]);
5430 case 'O':
5431 return rb_file_rowned_p(0, argv[1]);
5433 case 'p':
5434 return rb_file_pipe_p(0, argv[1]);
5436 case 'r':
5437 return rb_file_readable_p(0, argv[1]);
5439 case 'R':
5440 return rb_file_readable_real_p(0, argv[1]);
5442 case 's':
5443 return rb_file_size_p(0, argv[1]);
5445 case 'S':
5446 return rb_file_socket_p(0, argv[1]);
5448 case 'u':
5449 return rb_file_suid_p(0, argv[1]);
5451 case 'w':
5452 return rb_file_writable_p(0, argv[1]);
5454 case 'W':
5455 return rb_file_writable_real_p(0, argv[1]);
5457 case 'x':
5458 return rb_file_executable_p(0, argv[1]);
5460 case 'X':
5461 return rb_file_executable_real_p(0, argv[1]);
5463 case 'z':
5464 return rb_file_zero_p(0, argv[1]);
5468 if (strchr("MAC", cmd)) {
5469 struct stat st;
5470 VALUE fname = argv[1];
5472 CHECK(1);
5473 if (rb_stat(fname, &st) == -1) {
5474 int e = errno;
5475 FilePathValue(fname);
5476 rb_syserr_fail_path(e, fname);
5479 switch (cmd) {
5480 case 'A':
5481 return stat_atime(&st);
5482 case 'M':
5483 return stat_mtime(&st);
5484 case 'C':
5485 return stat_ctime(&st);
5489 if (cmd == '-') {
5490 CHECK(2);
5491 return rb_file_identical_p(0, argv[1], argv[2]);
5494 if (strchr("=<>", cmd)) {
5495 struct stat st1, st2;
5496 struct timespec t1, t2;
5498 CHECK(2);
5499 if (rb_stat(argv[1], &st1) < 0) return Qfalse;
5500 if (rb_stat(argv[2], &st2) < 0) return Qfalse;
5502 t1 = stat_mtimespec(&st1);
5503 t2 = stat_mtimespec(&st2);
5505 switch (cmd) {
5506 case '=':
5507 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
5508 return Qfalse;
5510 case '>':
5511 if (t1.tv_sec > t2.tv_sec) return Qtrue;
5512 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
5513 return Qfalse;
5515 case '<':
5516 if (t1.tv_sec < t2.tv_sec) return Qtrue;
5517 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
5518 return Qfalse;
5521 unknown:
5522 /* unknown command */
5523 if (ISPRINT(cmd)) {
5524 rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
5526 else {
5527 rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
5529 UNREACHABLE_RETURN(Qundef);
5534 * Document-class: File::Stat
5536 * Objects of class File::Stat encapsulate common status information
5537 * for File objects. The information is recorded at the moment the
5538 * File::Stat object is created; changes made to the file after that
5539 * point will not be reflected. File::Stat objects are returned by
5540 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5541 * methods return platform-specific values, and not all values are
5542 * meaningful on all systems. See also Kernel#test.
5545 static VALUE
5546 rb_stat_s_alloc(VALUE klass)
5548 return stat_new_0(klass, 0);
5552 * call-seq:
5554 * File::Stat.new(file_name) -> stat
5556 * Create a File::Stat object for the given file name (raising an
5557 * exception if the file doesn't exist).
5560 static VALUE
5561 rb_stat_init(VALUE obj, VALUE fname)
5563 struct stat st, *nst;
5565 FilePathValue(fname);
5566 fname = rb_str_encode_ospath(fname);
5567 if (STAT(StringValueCStr(fname), &st) == -1) {
5568 rb_sys_fail_path(fname);
5570 if (DATA_PTR(obj)) {
5571 xfree(DATA_PTR(obj));
5572 DATA_PTR(obj) = NULL;
5574 nst = ALLOC(struct stat);
5575 *nst = st;
5576 DATA_PTR(obj) = nst;
5578 return Qnil;
5581 /* :nodoc: */
5582 static VALUE
5583 rb_stat_init_copy(VALUE copy, VALUE orig)
5585 struct stat *nst;
5587 if (!OBJ_INIT_COPY(copy, orig)) return copy;
5588 if (DATA_PTR(copy)) {
5589 xfree(DATA_PTR(copy));
5590 DATA_PTR(copy) = 0;
5592 if (DATA_PTR(orig)) {
5593 nst = ALLOC(struct stat);
5594 *nst = *(struct stat*)DATA_PTR(orig);
5595 DATA_PTR(copy) = nst;
5598 return copy;
5602 * call-seq:
5603 * stat.ftype -> string
5605 * Identifies the type of <i>stat</i>. The return string is one of:
5606 * ``<code>file</code>'', ``<code>directory</code>'',
5607 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5608 * ``<code>fifo</code>'', ``<code>link</code>'',
5609 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5611 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5615 static VALUE
5616 rb_stat_ftype(VALUE obj)
5618 return rb_file_ftype(get_stat(obj));
5622 * call-seq:
5623 * stat.directory? -> true or false
5625 * Returns <code>true</code> if <i>stat</i> is a directory,
5626 * <code>false</code> otherwise.
5628 * File.stat("testfile").directory? #=> false
5629 * File.stat(".").directory? #=> true
5632 static VALUE
5633 rb_stat_d(VALUE obj)
5635 if (S_ISDIR(get_stat(obj)->st_mode)) return Qtrue;
5636 return Qfalse;
5640 * call-seq:
5641 * stat.pipe? -> true or false
5643 * Returns <code>true</code> if the operating system supports pipes and
5644 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5647 static VALUE
5648 rb_stat_p(VALUE obj)
5650 #ifdef S_IFIFO
5651 if (S_ISFIFO(get_stat(obj)->st_mode)) return Qtrue;
5653 #endif
5654 return Qfalse;
5658 * call-seq:
5659 * stat.symlink? -> true or false
5661 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5662 * <code>false</code> if it isn't or if the operating system doesn't
5663 * support this feature. As File::stat automatically follows symbolic
5664 * links, #symlink? will always be <code>false</code> for an object
5665 * returned by File::stat.
5667 * File.symlink("testfile", "alink") #=> 0
5668 * File.stat("alink").symlink? #=> false
5669 * File.lstat("alink").symlink? #=> true
5673 static VALUE
5674 rb_stat_l(VALUE obj)
5676 #ifdef S_ISLNK
5677 if (S_ISLNK(get_stat(obj)->st_mode)) return Qtrue;
5678 #endif
5679 return Qfalse;
5683 * call-seq:
5684 * stat.socket? -> true or false
5686 * Returns <code>true</code> if <i>stat</i> is a socket,
5687 * <code>false</code> if it isn't or if the operating system doesn't
5688 * support this feature.
5690 * File.stat("testfile").socket? #=> false
5694 static VALUE
5695 rb_stat_S(VALUE obj)
5697 #ifdef S_ISSOCK
5698 if (S_ISSOCK(get_stat(obj)->st_mode)) return Qtrue;
5700 #endif
5701 return Qfalse;
5705 * call-seq:
5706 * stat.blockdev? -> true or false
5708 * Returns <code>true</code> if the file is a block device,
5709 * <code>false</code> if it isn't or if the operating system doesn't
5710 * support this feature.
5712 * File.stat("testfile").blockdev? #=> false
5713 * File.stat("/dev/hda1").blockdev? #=> true
5717 static VALUE
5718 rb_stat_b(VALUE obj)
5720 #ifdef S_ISBLK
5721 if (S_ISBLK(get_stat(obj)->st_mode)) return Qtrue;
5723 #endif
5724 return Qfalse;
5728 * call-seq:
5729 * stat.chardev? -> true or false
5731 * Returns <code>true</code> if the file is a character device,
5732 * <code>false</code> if it isn't or if the operating system doesn't
5733 * support this feature.
5735 * File.stat("/dev/tty").chardev? #=> true
5739 static VALUE
5740 rb_stat_c(VALUE obj)
5742 if (S_ISCHR(get_stat(obj)->st_mode)) return Qtrue;
5744 return Qfalse;
5748 * call-seq:
5749 * stat.owned? -> true or false
5751 * Returns <code>true</code> if the effective user id of the process is
5752 * the same as the owner of <i>stat</i>.
5754 * File.stat("testfile").owned? #=> true
5755 * File.stat("/etc/passwd").owned? #=> false
5759 static VALUE
5760 rb_stat_owned(VALUE obj)
5762 if (get_stat(obj)->st_uid == geteuid()) return Qtrue;
5763 return Qfalse;
5766 static VALUE
5767 rb_stat_rowned(VALUE obj)
5769 if (get_stat(obj)->st_uid == getuid()) return Qtrue;
5770 return Qfalse;
5774 * call-seq:
5775 * stat.grpowned? -> true or false
5777 * Returns true if the effective group id of the process is the same as
5778 * the group id of <i>stat</i>. On Windows NT, returns <code>false</code>.
5780 * File.stat("testfile").grpowned? #=> true
5781 * File.stat("/etc/passwd").grpowned? #=> false
5785 static VALUE
5786 rb_stat_grpowned(VALUE obj)
5788 #ifndef _WIN32
5789 if (rb_group_member(get_stat(obj)->st_gid)) return Qtrue;
5790 #endif
5791 return Qfalse;
5795 * call-seq:
5796 * stat.readable? -> true or false
5798 * Returns <code>true</code> if <i>stat</i> is readable by the
5799 * effective user id of this process.
5801 * File.stat("testfile").readable? #=> true
5805 static VALUE
5806 rb_stat_r(VALUE obj)
5808 struct stat *st = get_stat(obj);
5810 #ifdef USE_GETEUID
5811 if (geteuid() == 0) return Qtrue;
5812 #endif
5813 #ifdef S_IRUSR
5814 if (rb_stat_owned(obj))
5815 return RBOOL(st->st_mode & S_IRUSR);
5816 #endif
5817 #ifdef S_IRGRP
5818 if (rb_stat_grpowned(obj))
5819 return RBOOL(st->st_mode & S_IRGRP);
5820 #endif
5821 #ifdef S_IROTH
5822 if (!(st->st_mode & S_IROTH)) return Qfalse;
5823 #endif
5824 return Qtrue;
5828 * call-seq:
5829 * stat.readable_real? -> true or false
5831 * Returns <code>true</code> if <i>stat</i> is readable by the real
5832 * user id of this process.
5834 * File.stat("testfile").readable_real? #=> true
5838 static VALUE
5839 rb_stat_R(VALUE obj)
5841 struct stat *st = get_stat(obj);
5843 #ifdef USE_GETEUID
5844 if (getuid() == 0) return Qtrue;
5845 #endif
5846 #ifdef S_IRUSR
5847 if (rb_stat_rowned(obj))
5848 return RBOOL(st->st_mode & S_IRUSR);
5849 #endif
5850 #ifdef S_IRGRP
5851 if (rb_group_member(get_stat(obj)->st_gid))
5852 return RBOOL(st->st_mode & S_IRGRP);
5853 #endif
5854 #ifdef S_IROTH
5855 if (!(st->st_mode & S_IROTH)) return Qfalse;
5856 #endif
5857 return Qtrue;
5861 * call-seq:
5862 * stat.world_readable? -> integer or nil
5864 * If <i>stat</i> is readable by others, returns an integer
5865 * representing the file permission bits of <i>stat</i>. Returns
5866 * <code>nil</code> otherwise. The meaning of the bits is platform
5867 * dependent; on Unix systems, see <code>stat(2)</code>.
5869 * m = File.stat("/etc/passwd").world_readable? #=> 420
5870 * sprintf("%o", m) #=> "644"
5873 static VALUE
5874 rb_stat_wr(VALUE obj)
5876 #ifdef S_IROTH
5877 struct stat *st = get_stat(obj);
5878 if ((st->st_mode & (S_IROTH)) == S_IROTH) {
5879 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
5881 else {
5882 return Qnil;
5884 #endif
5888 * call-seq:
5889 * stat.writable? -> true or false
5891 * Returns <code>true</code> if <i>stat</i> is writable by the
5892 * effective user id of this process.
5894 * File.stat("testfile").writable? #=> true
5898 static VALUE
5899 rb_stat_w(VALUE obj)
5901 struct stat *st = get_stat(obj);
5903 #ifdef USE_GETEUID
5904 if (geteuid() == 0) return Qtrue;
5905 #endif
5906 #ifdef S_IWUSR
5907 if (rb_stat_owned(obj))
5908 return RBOOL(st->st_mode & S_IWUSR);
5909 #endif
5910 #ifdef S_IWGRP
5911 if (rb_stat_grpowned(obj))
5912 return RBOOL(st->st_mode & S_IWGRP);
5913 #endif
5914 #ifdef S_IWOTH
5915 if (!(st->st_mode & S_IWOTH)) return Qfalse;
5916 #endif
5917 return Qtrue;
5921 * call-seq:
5922 * stat.writable_real? -> true or false
5924 * Returns <code>true</code> if <i>stat</i> is writable by the real
5925 * user id of this process.
5927 * File.stat("testfile").writable_real? #=> true
5931 static VALUE
5932 rb_stat_W(VALUE obj)
5934 struct stat *st = get_stat(obj);
5936 #ifdef USE_GETEUID
5937 if (getuid() == 0) return Qtrue;
5938 #endif
5939 #ifdef S_IWUSR
5940 if (rb_stat_rowned(obj))
5941 return RBOOL(st->st_mode & S_IWUSR);
5942 #endif
5943 #ifdef S_IWGRP
5944 if (rb_group_member(get_stat(obj)->st_gid))
5945 return RBOOL(st->st_mode & S_IWGRP);
5946 #endif
5947 #ifdef S_IWOTH
5948 if (!(st->st_mode & S_IWOTH)) return Qfalse;
5949 #endif
5950 return Qtrue;
5954 * call-seq:
5955 * stat.world_writable? -> integer or nil
5957 * If <i>stat</i> is writable by others, returns an integer
5958 * representing the file permission bits of <i>stat</i>. Returns
5959 * <code>nil</code> otherwise. The meaning of the bits is platform
5960 * dependent; on Unix systems, see <code>stat(2)</code>.
5962 * m = File.stat("/tmp").world_writable? #=> 511
5963 * sprintf("%o", m) #=> "777"
5966 static VALUE
5967 rb_stat_ww(VALUE obj)
5969 #ifdef S_IROTH
5970 struct stat *st = get_stat(obj);
5971 if ((st->st_mode & (S_IWOTH)) == S_IWOTH) {
5972 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
5974 else {
5975 return Qnil;
5977 #endif
5981 * call-seq:
5982 * stat.executable? -> true or false
5984 * Returns <code>true</code> if <i>stat</i> is executable or if the
5985 * operating system doesn't distinguish executable files from
5986 * nonexecutable files. The tests are made using the effective owner of
5987 * the process.
5989 * File.stat("testfile").executable? #=> false
5993 static VALUE
5994 rb_stat_x(VALUE obj)
5996 struct stat *st = get_stat(obj);
5998 #ifdef USE_GETEUID
5999 if (geteuid() == 0) {
6000 return RBOOL(st->st_mode & S_IXUGO);
6002 #endif
6003 #ifdef S_IXUSR
6004 if (rb_stat_owned(obj))
6005 return RBOOL(st->st_mode & S_IXUSR);
6006 #endif
6007 #ifdef S_IXGRP
6008 if (rb_stat_grpowned(obj))
6009 return RBOOL(st->st_mode & S_IXGRP);
6010 #endif
6011 #ifdef S_IXOTH
6012 if (!(st->st_mode & S_IXOTH)) return Qfalse;
6013 #endif
6014 return Qtrue;
6018 * call-seq:
6019 * stat.executable_real? -> true or false
6021 * Same as <code>executable?</code>, but tests using the real owner of
6022 * the process.
6025 static VALUE
6026 rb_stat_X(VALUE obj)
6028 struct stat *st = get_stat(obj);
6030 #ifdef USE_GETEUID
6031 if (getuid() == 0) {
6032 return RBOOL(st->st_mode & S_IXUGO);
6034 #endif
6035 #ifdef S_IXUSR
6036 if (rb_stat_rowned(obj))
6037 return RBOOL(st->st_mode & S_IXUSR);
6038 #endif
6039 #ifdef S_IXGRP
6040 if (rb_group_member(get_stat(obj)->st_gid))
6041 return RBOOL(st->st_mode & S_IXGRP);
6042 #endif
6043 #ifdef S_IXOTH
6044 if (!(st->st_mode & S_IXOTH)) return Qfalse;
6045 #endif
6046 return Qtrue;
6050 * call-seq:
6051 * stat.file? -> true or false
6053 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6054 * a device file, pipe, socket, etc.).
6056 * File.stat("testfile").file? #=> true
6060 static VALUE
6061 rb_stat_f(VALUE obj)
6063 if (S_ISREG(get_stat(obj)->st_mode)) return Qtrue;
6064 return Qfalse;
6068 * call-seq:
6069 * stat.zero? -> true or false
6071 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6072 * <code>false</code> otherwise.
6074 * File.stat("testfile").zero? #=> false
6078 static VALUE
6079 rb_stat_z(VALUE obj)
6081 if (get_stat(obj)->st_size == 0) return Qtrue;
6082 return Qfalse;
6086 * call-seq:
6087 * stat.size? -> Integer or nil
6089 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6090 * the file otherwise.
6092 * File.stat("testfile").size? #=> 66
6093 * File.stat("/dev/null").size? #=> nil
6097 static VALUE
6098 rb_stat_s(VALUE obj)
6100 off_t size = get_stat(obj)->st_size;
6102 if (size == 0) return Qnil;
6103 return OFFT2NUM(size);
6107 * call-seq:
6108 * stat.setuid? -> true or false
6110 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6111 * permission bit set, <code>false</code> if it doesn't or if the
6112 * operating system doesn't support this feature.
6114 * File.stat("/bin/su").setuid? #=> true
6117 static VALUE
6118 rb_stat_suid(VALUE obj)
6120 #ifdef S_ISUID
6121 if (get_stat(obj)->st_mode & S_ISUID) return Qtrue;
6122 #endif
6123 return Qfalse;
6127 * call-seq:
6128 * stat.setgid? -> true or false
6130 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6131 * permission bit set, <code>false</code> if it doesn't or if the
6132 * operating system doesn't support this feature.
6134 * File.stat("/usr/sbin/lpc").setgid? #=> true
6138 static VALUE
6139 rb_stat_sgid(VALUE obj)
6141 #ifdef S_ISGID
6142 if (get_stat(obj)->st_mode & S_ISGID) return Qtrue;
6143 #endif
6144 return Qfalse;
6148 * call-seq:
6149 * stat.sticky? -> true or false
6151 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6152 * <code>false</code> if it doesn't or if the operating system doesn't
6153 * support this feature.
6155 * File.stat("testfile").sticky? #=> false
6159 static VALUE
6160 rb_stat_sticky(VALUE obj)
6162 #ifdef S_ISVTX
6163 if (get_stat(obj)->st_mode & S_ISVTX) return Qtrue;
6164 #endif
6165 return Qfalse;
6168 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6169 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6170 #define HAVE_MKFIFO
6171 #endif
6173 #ifdef HAVE_MKFIFO
6174 struct mkfifo_arg {
6175 const char *path;
6176 mode_t mode;
6179 static void *
6180 nogvl_mkfifo(void *ptr)
6182 struct mkfifo_arg *ma = ptr;
6184 return (void *)(VALUE)mkfifo(ma->path, ma->mode);
6188 * call-seq:
6189 * File.mkfifo(file_name, mode=0666) => 0
6191 * Creates a FIFO special file with name _file_name_. _mode_
6192 * specifies the FIFO's permissions. It is modified by the process's
6193 * umask in the usual way: the permissions of the created file are
6194 * (mode & ~umask).
6197 static VALUE
6198 rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _)
6200 VALUE path;
6201 struct mkfifo_arg ma;
6203 ma.mode = 0666;
6204 rb_check_arity(argc, 1, 2);
6205 if (argc > 1) {
6206 ma.mode = NUM2MODET(argv[1]);
6208 path = argv[0];
6209 FilePathValue(path);
6210 path = rb_str_encode_ospath(path);
6211 ma.path = RSTRING_PTR(path);
6212 if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) {
6213 rb_sys_fail_path(path);
6215 return INT2FIX(0);
6217 #else
6218 #define rb_file_s_mkfifo rb_f_notimplement
6219 #endif
6221 static VALUE rb_mFConst;
6223 void
6224 rb_file_const(const char *name, VALUE value)
6226 rb_define_const(rb_mFConst, name, value);
6230 rb_is_absolute_path(const char *path)
6232 #ifdef DOSISH_DRIVE_LETTER
6233 if (has_drive_letter(path) && isdirsep(path[2])) return 1;
6234 #endif
6235 #ifdef DOSISH_UNC
6236 if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
6237 #endif
6238 #ifndef DOSISH
6239 if (path[0] == '/') return 1;
6240 #endif
6241 return 0;
6244 #ifndef ENABLE_PATH_CHECK
6245 # if defined DOSISH || defined __CYGWIN__
6246 # define ENABLE_PATH_CHECK 0
6247 # else
6248 # define ENABLE_PATH_CHECK 1
6249 # endif
6250 #endif
6252 #if ENABLE_PATH_CHECK
6253 static int
6254 path_check_0(VALUE path)
6256 struct stat st;
6257 const char *p0 = StringValueCStr(path);
6258 const char *e0;
6259 rb_encoding *enc;
6260 char *p = 0, *s;
6262 if (!rb_is_absolute_path(p0)) {
6263 char *buf = ruby_getcwd();
6264 VALUE newpath;
6266 newpath = rb_str_new2(buf);
6267 xfree(buf);
6269 rb_str_cat2(newpath, "/");
6270 rb_str_cat2(newpath, p0);
6271 path = newpath;
6272 p0 = RSTRING_PTR(path);
6274 e0 = p0 + RSTRING_LEN(path);
6275 enc = rb_enc_get(path);
6276 for (;;) {
6277 #ifndef S_IWOTH
6278 # define S_IWOTH 002
6279 #endif
6280 if (STAT(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH)
6281 #ifdef S_ISVTX
6282 && !(p && (st.st_mode & S_ISVTX))
6283 #endif
6284 && !access(p0, W_OK)) {
6285 rb_enc_warn(enc, "Insecure world writable dir %s in PATH, mode 0%"
6286 #if SIZEOF_DEV_T > SIZEOF_INT
6287 PRI_MODET_PREFIX"o",
6288 #else
6289 "o",
6290 #endif
6291 p0, st.st_mode);
6292 if (p) *p = '/';
6293 RB_GC_GUARD(path);
6294 return 0;
6296 s = strrdirsep(p0, e0, enc);
6297 if (p) *p = '/';
6298 if (!s || s == p0) return 1;
6299 p = s;
6300 e0 = p;
6301 *p = '\0';
6304 #endif
6307 rb_path_check(const char *path)
6309 #if ENABLE_PATH_CHECK
6310 const char *p0, *p, *pend;
6311 const char sep = PATH_SEP_CHAR;
6313 if (!path) return 1;
6315 pend = path + strlen(path);
6316 p0 = path;
6317 p = strchr(path, sep);
6318 if (!p) p = pend;
6320 for (;;) {
6321 if (!path_check_0(rb_str_new(p0, p - p0))) {
6322 return 0; /* not safe */
6324 p0 = p + 1;
6325 if (p0 > pend) break;
6326 p = strchr(p0, sep);
6327 if (!p) p = pend;
6329 #endif
6330 return 1;
6334 ruby_is_fd_loadable(int fd)
6336 #ifdef _WIN32
6337 return 1;
6338 #else
6339 struct stat st;
6341 if (fstat(fd, &st) < 0)
6342 return 0;
6344 if (S_ISREG(st.st_mode))
6345 return 1;
6347 if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
6348 return -1;
6350 if (S_ISDIR(st.st_mode))
6351 errno = EISDIR;
6352 else
6353 errno = ENXIO;
6355 return 0;
6356 #endif
6359 #ifndef _WIN32
6361 rb_file_load_ok(const char *path)
6363 int ret = 1;
6365 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6366 FIXME: Why O_NDELAY is checked?
6368 int mode = (O_RDONLY |
6369 #if defined O_NONBLOCK
6370 O_NONBLOCK |
6371 #elif defined O_NDELAY
6372 O_NDELAY |
6373 #endif
6375 int fd = rb_cloexec_open(path, mode, 0);
6376 if (fd == -1) return 0;
6377 rb_update_max_fd(fd);
6378 ret = ruby_is_fd_loadable(fd);
6379 (void)close(fd);
6380 return ret;
6382 #endif
6384 static int
6385 is_explicit_relative(const char *path)
6387 if (*path++ != '.') return 0;
6388 if (*path == '.') path++;
6389 return isdirsep(*path);
6392 static VALUE
6393 copy_path_class(VALUE path, VALUE orig)
6395 int encidx = rb_enc_get_index(orig);
6396 if (encidx == ENCINDEX_ASCII || encidx == ENCINDEX_US_ASCII)
6397 encidx = rb_filesystem_encindex();
6398 rb_enc_associate_index(path, encidx);
6399 str_shrink(path);
6400 RBASIC_SET_CLASS(path, rb_obj_class(orig));
6401 OBJ_FREEZE(path);
6402 return path;
6406 rb_find_file_ext(VALUE *filep, const char *const *ext)
6408 const char *f = StringValueCStr(*filep);
6409 VALUE fname = *filep, load_path, tmp;
6410 long i, j, fnlen;
6411 int expanded = 0;
6413 if (!ext[0]) return 0;
6415 if (f[0] == '~') {
6416 fname = file_expand_path_1(fname);
6417 f = RSTRING_PTR(fname);
6418 *filep = fname;
6419 expanded = 1;
6422 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6423 if (!expanded) fname = file_expand_path_1(fname);
6424 fnlen = RSTRING_LEN(fname);
6425 for (i=0; ext[i]; i++) {
6426 rb_str_cat2(fname, ext[i]);
6427 if (rb_file_load_ok(RSTRING_PTR(fname))) {
6428 *filep = copy_path_class(fname, *filep);
6429 return (int)(i+1);
6431 rb_str_set_len(fname, fnlen);
6433 return 0;
6436 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6437 if (!load_path) return 0;
6439 fname = rb_str_dup(*filep);
6440 RBASIC_CLEAR_CLASS(fname);
6441 fnlen = RSTRING_LEN(fname);
6442 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6443 rb_enc_associate_index(tmp, rb_usascii_encindex());
6444 for (j=0; ext[j]; j++) {
6445 rb_str_cat2(fname, ext[j]);
6446 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6447 VALUE str = RARRAY_AREF(load_path, i);
6449 RB_GC_GUARD(str) = rb_get_path(str);
6450 if (RSTRING_LEN(str) == 0) continue;
6451 rb_file_expand_path_internal(fname, str, 0, 0, tmp);
6452 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
6453 *filep = copy_path_class(tmp, *filep);
6454 return (int)(j+1);
6457 rb_str_set_len(fname, fnlen);
6459 rb_str_resize(tmp, 0);
6460 RB_GC_GUARD(load_path);
6461 return 0;
6464 VALUE
6465 rb_find_file(VALUE path)
6467 VALUE tmp, load_path;
6468 const char *f = StringValueCStr(path);
6469 int expanded = 0;
6471 if (f[0] == '~') {
6472 tmp = file_expand_path_1(path);
6473 path = copy_path_class(tmp, path);
6474 f = RSTRING_PTR(path);
6475 expanded = 1;
6478 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6479 if (!rb_file_load_ok(f)) return 0;
6480 if (!expanded)
6481 path = copy_path_class(file_expand_path_1(path), path);
6482 return path;
6485 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6486 if (load_path) {
6487 long i;
6489 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6490 rb_enc_associate_index(tmp, rb_usascii_encindex());
6491 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6492 VALUE str = RARRAY_AREF(load_path, i);
6493 RB_GC_GUARD(str) = rb_get_path(str);
6494 if (RSTRING_LEN(str) > 0) {
6495 rb_file_expand_path_internal(path, str, 0, 0, tmp);
6496 f = RSTRING_PTR(tmp);
6497 if (rb_file_load_ok(f)) goto found;
6500 rb_str_resize(tmp, 0);
6501 return 0;
6503 else {
6504 return 0; /* no path, no load */
6507 found:
6508 return copy_path_class(tmp, path);
6511 static void
6512 define_filetest_function(const char *name, VALUE (*func)(ANYARGS), int argc)
6514 rb_define_module_function(rb_mFileTest, name, func, argc);
6515 rb_define_singleton_method(rb_cFile, name, func, argc);
6518 const char ruby_null_device[] =
6519 #if defined DOSISH
6520 "NUL"
6521 #elif defined AMIGA || defined __amigaos__
6522 "NIL"
6523 #elif defined __VMS
6524 "NL:"
6525 #else
6526 "/dev/null"
6527 #endif
6531 * A File is an abstraction of any file object accessible by the
6532 * program and is closely associated with class IO. File includes
6533 * the methods of module FileTest as class methods, allowing you to
6534 * write (for example) <code>File.exist?("foo")</code>.
6536 * In the description of File methods,
6537 * <em>permission bits</em> are a platform-specific
6538 * set of bits that indicate permissions of a file. On Unix-based
6539 * systems, permissions are viewed as a set of three octets, for the
6540 * owner, the group, and the rest of the world. For each of these
6541 * entities, permissions may be set to read, write, or execute the
6542 * file:
6544 * The permission bits <code>0644</code> (in octal) would thus be
6545 * interpreted as read/write for owner, and read-only for group and
6546 * other. Higher-order bits may also be used to indicate the type of
6547 * file (plain, directory, pipe, socket, and so on) and various other
6548 * special features. If the permissions are for a directory, the
6549 * meaning of the execute bit changes; when set the directory can be
6550 * searched.
6552 * On non-Posix operating systems, there may be only the ability to
6553 * make a file read-only or read-write. In this case, the remaining
6554 * permission bits will be synthesized to resemble typical values. For
6555 * instance, on Windows NT the default permission bits are
6556 * <code>0644</code>, which means read/write for owner, read-only for
6557 * all others. The only change that can be made is to make the file
6558 * read-only, which is reported as <code>0444</code>.
6560 * Various constants for the methods in File can be found in File::Constants.
6562 * == What's Here
6564 * First, what's elsewhere. \Class \File:
6566 * - Inherits from {class IO}[IO.html#class-IO-label-What-27s+Here],
6567 * in particular, methods for creating, reading, and writing files
6568 * - Includes {module FileTest}[FileTest.html#module-FileTest-label-What-27s+Here].
6569 * which provides dozens of additional methods.
6571 * Here, class \File provides methods that are useful for:
6573 * - {Creating}[#class-File-label-Creating]
6574 * - {Querying}[#class-File-label-Querying]
6575 * - {Settings}[#class-File-label-Settings]
6576 * - {Other}[#class-File-label-Other]
6578 * === Creating
6580 * - ::new:: Opens the file at the given path; returns the file.
6581 * - ::open:: Same as ::new, but when given a block will yield the file to the block,
6582 * and close the file upon exiting the block.
6583 * - ::link:: Creates a new name for an existing file using a hard link.
6584 * - ::mkfifo:: Returns the FIFO file created at the given path.
6585 * - ::symlink:: Creates a symbolic link for the given file path.
6587 * === Querying
6589 * _Paths_
6591 * - ::absolute_path:: Returns the absolute file path for the given path.
6592 * - ::absolute_path?:: Returns whether the given path is the absolute file path.
6593 * - ::basename:: Returns the last component of the given file path.
6594 * - ::dirname:: Returns all but the last component of the given file path.
6595 * - ::expand_path:: Returns the absolute file path for the given path,
6596 * expanding <tt>~</tt> for a home directory.
6597 * - ::extname:: Returns the file extension for the given file path.
6598 * - ::fnmatch? (aliased as ::fnmatch):: Returns whether the given file path
6599 * matches the given pattern.
6600 * - ::join:: Joins path components into a single path string.
6601 * - ::path:: Returns the string representation of the given path.
6602 * - ::readlink:: Returns the path to the file at the given symbolic link.
6603 * - ::realdirpath:: Returns the real path for the given file path,
6604 * where the last component need not exist.
6605 * - ::realpath:: Returns the real path for the given file path,
6606 * where all components must exist.
6607 * - ::split:: Returns an array of two strings: the directory name and basename
6608 * of the file at the given path.
6609 * - #path (aliased as #to_path):: Returns the string representation of the given path.
6611 * _Times_
6613 * - ::atime:: Returns a \Time for the most recent access to the given file.
6614 * - ::birthtime:: Returns a \Time for the creation of the given file.
6615 * - ::ctime:: Returns a \Time for the metadata change of the given file.
6616 * - ::mtime:: Returns a \Time for the most recent data modification to
6617 * the content of the given file.
6618 * - #atime:: Returns a \Time for the most recent access to +self+.
6619 * - #birthtime:: Returns a \Time the creation for +self+.
6620 * - #ctime:: Returns a \Time for the metadata change of +self+.
6621 * - #mtime:: Returns a \Time for the most recent data modification
6622 * to the content of +self+.
6624 * _Types_
6626 * - ::blockdev?:: Returns whether the file at the given path is a block device.
6627 * - ::chardev?:: Returns whether the file at the given path is a character device.
6628 * - ::directory?:: Returns whether the file at the given path is a diretory.
6629 * - ::executable?:: Returns whether the file at the given path is executable
6630 * by the effective user and group of the current process.
6631 * - ::executable_real?:: Returns whether the file at the given path is executable
6632 * by the real user and group of the current process.
6633 * - ::exist?:: Returns whether the file at the given path exists.
6634 * - ::file?:: Returns whether the file at the given path is a regular file.
6635 * - ::ftype:: Returns a string giving the type of the file at the given path.
6636 * - ::grpowned?:: Returns whether the effective group of the current process
6637 * owns the file at the given path.
6638 * - ::identical?:: Returns whether the files at two given paths are identical.
6639 * - ::lstat:: Returns the File::Stat object for the last symbolic link
6640 * in the given path.
6641 * - ::owned?:: Returns whether the effective user of the current process
6642 * owns the file at the given path.
6643 * - ::pipe?:: Returns whether the file at the given path is a pipe.
6644 * - ::readable?:: Returns whether the file at the given path is readable
6645 * by the effective user and group of the current process.
6646 * - ::readable_real?:: Returns whether the file at the given path is readable
6647 * by the real user and group of the current process.
6648 * - ::setgid?:: Returns whether the setgid bit is set for the file at the given path.
6649 * - ::setuid?:: Returns whether the setuid bit is set for the file at the given path.
6650 * - ::socket?:: Returns whether the file at the given path is a socket.
6651 * - ::stat:: Returns the File::Stat object for the file at the given path.
6652 * - ::sticky?:: Returns whether the file at the given path has its sticky bit set.
6653 * - ::symlink?:: Returns whether the file at the given path is a symbolic link.
6654 * - ::umask:: Returns the umask value for the current process.
6655 * - ::world_readable?:: Returns whether the file at the given path is readable
6656 * by others.
6657 * - ::world_writable?:: Returns whether the file at the given path is writable
6658 * by others.
6659 * - ::writable?:: Returns whether the file at the given path is writable
6660 * by the effective user and group of the current process.
6661 * - ::writable_real?:: Returns whether the file at the given path is writable
6662 * by the real user and group of the current process.
6663 * - #lstat:: Returns the File::Stat object for the last symbolic link
6664 * in the path for +self+.
6666 * _Contents_
6668 * - ::empty? (aliased as ::zero?):: Returns whether the file at the given path
6669 * exists and is empty.
6670 * - ::size:: Returns the size (bytes) of the file at the given path.
6671 * - ::size?:: Returns +nil+ if there is no file at the given path,
6672 * or if that file is empty; otherwise returns the file size (bytes).
6673 * - #size:: Returns the size (bytes) of +self+.
6675 * === Settings
6677 * - ::chmod:: Changes permissions of the file at the given path.
6678 * - ::chown:: Change ownership of the file at the given path.
6679 * - ::lchmod:: Changes permissions of the last symbolic link in the given path.
6680 * - ::lchown:: Change ownership of the last symbolic in the given path.
6681 * - ::lutime:: For each given file path, sets the access time and modification time
6682 * of the last symbolic link in the path.
6683 * - ::rename:: Moves the file at one given path to another given path.
6684 * - ::utime:: Sets the access time and modification time of each file
6685 * at the given paths.
6686 * - #flock:: Locks or unlocks +self+.
6688 * === Other
6690 * - ::truncate:: Truncates the file at the given file path to the given size.
6691 * - ::unlink (aliased as ::delete):: Deletes the file for each given file path.
6692 * - #truncate:: Truncates +self+ to the given size.
6696 void
6697 Init_File(void)
6699 VALUE separator;
6701 rb_mFileTest = rb_define_module("FileTest");
6702 rb_cFile = rb_define_class("File", rb_cIO);
6704 define_filetest_function("directory?", rb_file_directory_p, 1);
6705 define_filetest_function("exist?", rb_file_exist_p, 1);
6706 define_filetest_function("exists?", rb_file_exists_p, 1);
6707 define_filetest_function("readable?", rb_file_readable_p, 1);
6708 define_filetest_function("readable_real?", rb_file_readable_real_p, 1);
6709 define_filetest_function("world_readable?", rb_file_world_readable_p, 1);
6710 define_filetest_function("writable?", rb_file_writable_p, 1);
6711 define_filetest_function("writable_real?", rb_file_writable_real_p, 1);
6712 define_filetest_function("world_writable?", rb_file_world_writable_p, 1);
6713 define_filetest_function("executable?", rb_file_executable_p, 1);
6714 define_filetest_function("executable_real?", rb_file_executable_real_p, 1);
6715 define_filetest_function("file?", rb_file_file_p, 1);
6716 define_filetest_function("zero?", rb_file_zero_p, 1);
6717 define_filetest_function("empty?", rb_file_zero_p, 1);
6718 define_filetest_function("size?", rb_file_size_p, 1);
6719 define_filetest_function("size", rb_file_s_size, 1);
6720 define_filetest_function("owned?", rb_file_owned_p, 1);
6721 define_filetest_function("grpowned?", rb_file_grpowned_p, 1);
6723 define_filetest_function("pipe?", rb_file_pipe_p, 1);
6724 define_filetest_function("symlink?", rb_file_symlink_p, 1);
6725 define_filetest_function("socket?", rb_file_socket_p, 1);
6727 define_filetest_function("blockdev?", rb_file_blockdev_p, 1);
6728 define_filetest_function("chardev?", rb_file_chardev_p, 1);
6730 define_filetest_function("setuid?", rb_file_suid_p, 1);
6731 define_filetest_function("setgid?", rb_file_sgid_p, 1);
6732 define_filetest_function("sticky?", rb_file_sticky_p, 1);
6734 define_filetest_function("identical?", rb_file_identical_p, 2);
6736 rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
6737 rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
6738 rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
6740 rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
6741 rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
6742 rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
6743 rb_define_singleton_method(rb_cFile, "birthtime", rb_file_s_birthtime, 1);
6745 rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
6746 rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
6747 rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
6748 rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
6749 rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
6750 rb_define_singleton_method(rb_cFile, "lutime", rb_file_s_lutime, -1);
6752 rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
6753 rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
6754 rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
6756 rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -1);
6757 rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -1);
6758 rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
6759 rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
6760 rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
6761 rb_define_singleton_method(rb_cFile, "mkfifo", rb_file_s_mkfifo, -1);
6762 rb_define_singleton_method(rb_cFile, "expand_path", s_expand_path, -1);
6763 rb_define_singleton_method(rb_cFile, "absolute_path", s_absolute_path, -1);
6764 rb_define_singleton_method(rb_cFile, "absolute_path?", s_absolute_path_p, 1);
6765 rb_define_singleton_method(rb_cFile, "realpath", rb_file_s_realpath, -1);
6766 rb_define_singleton_method(rb_cFile, "realdirpath", rb_file_s_realdirpath, -1);
6767 rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
6768 rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, -1);
6769 rb_define_singleton_method(rb_cFile, "extname", rb_file_s_extname, 1);
6770 rb_define_singleton_method(rb_cFile, "path", rb_file_s_path, 1);
6772 separator = rb_fstring_lit("/");
6773 /* separates directory parts in path */
6774 rb_define_const(rb_cFile, "Separator", separator);
6775 /* separates directory parts in path */
6776 rb_define_const(rb_cFile, "SEPARATOR", separator);
6777 rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
6778 rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -2);
6780 #ifdef DOSISH
6781 /* platform specific alternative separator */
6782 rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator)));
6783 #else
6784 rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
6785 #endif
6786 /* path list separator */
6787 rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP));
6789 rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
6790 rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
6792 rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
6793 rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
6794 rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
6795 rb_define_method(rb_cFile, "birthtime", rb_file_birthtime, 0);
6796 rb_define_method(rb_cFile, "size", file_size, 0);
6798 rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
6799 rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
6800 rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
6802 rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
6805 * Document-module: File::Constants
6807 * File::Constants provides file-related constants. All possible
6808 * file constants are listed in the documentation but they may not all
6809 * be present on your platform.
6811 * If the underlying platform doesn't define a constant the corresponding
6812 * Ruby constant is not defined.
6814 * Your platform documentations (e.g. man open(2)) may describe more
6815 * detailed information.
6817 rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
6818 rb_include_module(rb_cIO, rb_mFConst);
6820 /* open for reading only */
6821 rb_define_const(rb_mFConst, "RDONLY", INT2FIX(O_RDONLY));
6822 /* open for writing only */
6823 rb_define_const(rb_mFConst, "WRONLY", INT2FIX(O_WRONLY));
6824 /* open for reading and writing */
6825 rb_define_const(rb_mFConst, "RDWR", INT2FIX(O_RDWR));
6826 /* append on each write */
6827 rb_define_const(rb_mFConst, "APPEND", INT2FIX(O_APPEND));
6828 /* create file if it does not exist */
6829 rb_define_const(rb_mFConst, "CREAT", INT2FIX(O_CREAT));
6830 /* error if CREAT and the file exists */
6831 rb_define_const(rb_mFConst, "EXCL", INT2FIX(O_EXCL));
6832 #if defined(O_NDELAY) || defined(O_NONBLOCK)
6833 # ifndef O_NONBLOCK
6834 # define O_NONBLOCK O_NDELAY
6835 # endif
6836 /* do not block on open or for data to become available */
6837 rb_define_const(rb_mFConst, "NONBLOCK", INT2FIX(O_NONBLOCK));
6838 #endif
6839 /* truncate size to 0 */
6840 rb_define_const(rb_mFConst, "TRUNC", INT2FIX(O_TRUNC));
6841 #ifdef O_NOCTTY
6842 /* not to make opened IO the controlling terminal device */
6843 rb_define_const(rb_mFConst, "NOCTTY", INT2FIX(O_NOCTTY));
6844 #endif
6845 #ifndef O_BINARY
6846 # define O_BINARY 0
6847 #endif
6848 /* disable line code conversion */
6849 rb_define_const(rb_mFConst, "BINARY", INT2FIX(O_BINARY));
6850 #ifndef O_SHARE_DELETE
6851 # define O_SHARE_DELETE 0
6852 #endif
6853 /* can delete opened file */
6854 rb_define_const(rb_mFConst, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE));
6855 #ifdef O_SYNC
6856 /* any write operation perform synchronously */
6857 rb_define_const(rb_mFConst, "SYNC", INT2FIX(O_SYNC));
6858 #endif
6859 #ifdef O_DSYNC
6860 /* any write operation perform synchronously except some meta data */
6861 rb_define_const(rb_mFConst, "DSYNC", INT2FIX(O_DSYNC));
6862 #endif
6863 #ifdef O_RSYNC
6864 /* any read operation perform synchronously. used with SYNC or DSYNC. */
6865 rb_define_const(rb_mFConst, "RSYNC", INT2FIX(O_RSYNC));
6866 #endif
6867 #ifdef O_NOFOLLOW
6868 /* do not follow symlinks */
6869 rb_define_const(rb_mFConst, "NOFOLLOW", INT2FIX(O_NOFOLLOW)); /* FreeBSD, Linux */
6870 #endif
6871 #ifdef O_NOATIME
6872 /* do not change atime */
6873 rb_define_const(rb_mFConst, "NOATIME", INT2FIX(O_NOATIME)); /* Linux */
6874 #endif
6875 #ifdef O_DIRECT
6876 /* Try to minimize cache effects of the I/O to and from this file. */
6877 rb_define_const(rb_mFConst, "DIRECT", INT2FIX(O_DIRECT));
6878 #endif
6879 #ifdef O_TMPFILE
6880 /* Create an unnamed temporary file */
6881 rb_define_const(rb_mFConst, "TMPFILE", INT2FIX(O_TMPFILE));
6882 #endif
6884 /* shared lock. see File#flock */
6885 rb_define_const(rb_mFConst, "LOCK_SH", INT2FIX(LOCK_SH));
6886 /* exclusive lock. see File#flock */
6887 rb_define_const(rb_mFConst, "LOCK_EX", INT2FIX(LOCK_EX));
6888 /* unlock. see File#flock */
6889 rb_define_const(rb_mFConst, "LOCK_UN", INT2FIX(LOCK_UN));
6890 /* non-blocking lock. used with LOCK_SH or LOCK_EX. see File#flock */
6891 rb_define_const(rb_mFConst, "LOCK_NB", INT2FIX(LOCK_NB));
6893 /* Name of the null device */
6894 rb_define_const(rb_mFConst, "NULL", rb_fstring_cstr(ruby_null_device));
6896 rb_define_method(rb_cFile, "path", rb_file_path, 0);
6897 rb_define_method(rb_cFile, "to_path", rb_file_path, 0);
6898 rb_define_global_function("test", rb_f_test, -1);
6900 rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
6901 rb_define_alloc_func(rb_cStat, rb_stat_s_alloc);
6902 rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
6903 rb_define_method(rb_cStat, "initialize_copy", rb_stat_init_copy, 1);
6905 rb_include_module(rb_cStat, rb_mComparable);
6907 rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
6909 rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
6910 rb_define_method(rb_cStat, "dev_major", rb_stat_dev_major, 0);
6911 rb_define_method(rb_cStat, "dev_minor", rb_stat_dev_minor, 0);
6912 rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
6913 rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
6914 rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
6915 rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
6916 rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
6917 rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
6918 rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
6919 rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
6920 rb_define_method(rb_cStat, "size", rb_stat_size, 0);
6921 rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
6922 rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
6923 rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
6924 rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
6925 rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
6926 rb_define_method(rb_cStat, "birthtime", rb_stat_birthtime, 0);
6928 rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
6930 rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
6932 rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
6933 rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
6934 rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
6935 rb_define_method(rb_cStat, "world_readable?", rb_stat_wr, 0);
6936 rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
6937 rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
6938 rb_define_method(rb_cStat, "world_writable?", rb_stat_ww, 0);
6939 rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
6940 rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
6941 rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
6942 rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
6943 rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
6944 rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
6945 rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
6947 rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
6948 rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
6949 rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
6951 rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
6952 rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
6954 rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
6955 rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
6956 rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);