[ruby/etc] bump up to 1.3.1
[ruby-80x24.org.git] / file.c
blob5a5e6b27060144cf78f845058921de6190340b63
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;
1790 * call-seq:
1791 * File.readable?(file_name) -> true or false
1793 * Returns <code>true</code> if the named file is readable by the effective
1794 * user and group id of this process. See eaccess(3).
1796 * Note that some OS-level security features may cause this to return true
1797 * even though the file is not readable by the effective user/group.
1800 static VALUE
1801 rb_file_readable_p(VALUE obj, VALUE fname)
1803 return RBOOL(rb_eaccess(fname, R_OK) >= 0);
1807 * call-seq:
1808 * File.readable_real?(file_name) -> true or false
1810 * Returns <code>true</code> if the named file is readable by the real
1811 * user and group id of this process. See access(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 real user/group.
1817 static VALUE
1818 rb_file_readable_real_p(VALUE obj, VALUE fname)
1820 return RBOOL(rb_access(fname, R_OK) >= 0);
1823 #ifndef S_IRUGO
1824 # define S_IRUGO (S_IRUSR | S_IRGRP | S_IROTH)
1825 #endif
1827 #ifndef S_IWUGO
1828 # define S_IWUGO (S_IWUSR | S_IWGRP | S_IWOTH)
1829 #endif
1832 * call-seq:
1833 * File.world_readable?(file_name) -> integer or nil
1835 * If <i>file_name</i> is readable by others, returns an integer
1836 * representing the file permission bits of <i>file_name</i>. Returns
1837 * <code>nil</code> otherwise. The meaning of the bits is platform
1838 * dependent; on Unix systems, see <code>stat(2)</code>.
1840 * _file_name_ can be an IO object.
1842 * File.world_readable?("/etc/passwd") #=> 420
1843 * m = File.world_readable?("/etc/passwd")
1844 * sprintf("%o", m) #=> "644"
1847 static VALUE
1848 rb_file_world_readable_p(VALUE obj, VALUE fname)
1850 #ifdef S_IROTH
1851 struct stat st;
1853 if (rb_stat(fname, &st) < 0) return Qnil;
1854 if ((st.st_mode & (S_IROTH)) == S_IROTH) {
1855 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1857 #endif
1858 return Qnil;
1862 * call-seq:
1863 * File.writable?(file_name) -> true or false
1865 * Returns <code>true</code> if the named file is writable by the effective
1866 * user and group id of this process. See eaccess(3).
1868 * Note that some OS-level security features may cause this to return true
1869 * even though the file is not writable by the effective user/group.
1872 static VALUE
1873 rb_file_writable_p(VALUE obj, VALUE fname)
1875 return RBOOL(rb_eaccess(fname, W_OK) >= 0);
1879 * call-seq:
1880 * File.writable_real?(file_name) -> true or false
1882 * Returns <code>true</code> if the named file is writable by the real
1883 * user and group id of this process. See access(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 real user/group.
1889 static VALUE
1890 rb_file_writable_real_p(VALUE obj, VALUE fname)
1892 return RBOOL(rb_access(fname, W_OK) >= 0);
1896 * call-seq:
1897 * File.world_writable?(file_name) -> integer or nil
1899 * If <i>file_name</i> is writable by others, returns an integer
1900 * representing the file permission bits of <i>file_name</i>. Returns
1901 * <code>nil</code> otherwise. The meaning of the bits is platform
1902 * dependent; on Unix systems, see <code>stat(2)</code>.
1904 * _file_name_ can be an IO object.
1906 * File.world_writable?("/tmp") #=> 511
1907 * m = File.world_writable?("/tmp")
1908 * sprintf("%o", m) #=> "777"
1911 static VALUE
1912 rb_file_world_writable_p(VALUE obj, VALUE fname)
1914 #ifdef S_IWOTH
1915 struct stat st;
1917 if (rb_stat(fname, &st) < 0) return Qnil;
1918 if ((st.st_mode & (S_IWOTH)) == S_IWOTH) {
1919 return UINT2NUM(st.st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
1921 #endif
1922 return Qnil;
1926 * call-seq:
1927 * File.executable?(file_name) -> true or false
1929 * Returns <code>true</code> if the named file is executable by the effective
1930 * user and group id of this process. See eaccess(3).
1932 * Windows does not support execute permissions separately from read
1933 * permissions. On Windows, a file is only considered executable if it ends in
1934 * .bat, .cmd, .com, or .exe.
1936 * Note that some OS-level security features may cause this to return true
1937 * even though the file is not executable by the effective user/group.
1940 static VALUE
1941 rb_file_executable_p(VALUE obj, VALUE fname)
1943 return RBOOL(rb_eaccess(fname, X_OK) >= 0);
1947 * call-seq:
1948 * File.executable_real?(file_name) -> true or false
1950 * Returns <code>true</code> if the named file is executable by the real
1951 * user and group id of this process. See access(3).
1953 * Windows does not support execute permissions separately from read
1954 * permissions. On Windows, a file is only considered executable if it ends in
1955 * .bat, .cmd, .com, or .exe.
1957 * Note that some OS-level security features may cause this to return true
1958 * even though the file is not executable by the real user/group.
1961 static VALUE
1962 rb_file_executable_real_p(VALUE obj, VALUE fname)
1964 return RBOOL(rb_access(fname, X_OK) >= 0);
1967 #ifndef S_ISREG
1968 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1969 #endif
1972 * call-seq:
1973 * File.file?(file) -> true or false
1975 * Returns +true+ if the named +file+ exists and is a regular file.
1977 * +file+ can be an IO object.
1979 * If the +file+ argument is a symbolic link, it will resolve the symbolic link
1980 * and use the file referenced by the link.
1983 static VALUE
1984 rb_file_file_p(VALUE obj, VALUE fname)
1986 struct stat st;
1988 if (rb_stat(fname, &st) < 0) return Qfalse;
1989 return RBOOL(S_ISREG(st.st_mode));
1993 * call-seq:
1994 * File.zero?(file_name) -> true or false
1996 * Returns <code>true</code> if the named file exists and has
1997 * a zero size.
1999 * _file_name_ can be an IO object.
2002 static VALUE
2003 rb_file_zero_p(VALUE obj, VALUE fname)
2005 struct stat st;
2007 if (rb_stat(fname, &st) < 0) return Qfalse;
2008 return RBOOL(st.st_size == 0);
2012 * call-seq:
2013 * File.size?(file_name) -> Integer or nil
2015 * Returns +nil+ if +file_name+ doesn't exist or has zero size, the size of the
2016 * file otherwise.
2018 * _file_name_ can be an IO object.
2021 static VALUE
2022 rb_file_size_p(VALUE obj, VALUE fname)
2024 struct stat st;
2026 if (rb_stat(fname, &st) < 0) return Qnil;
2027 if (st.st_size == 0) return Qnil;
2028 return OFFT2NUM(st.st_size);
2032 * call-seq:
2033 * File.owned?(file_name) -> true or false
2035 * Returns <code>true</code> if the named file exists and the
2036 * effective used id of the calling process is the owner of
2037 * the file.
2039 * _file_name_ can be an IO object.
2042 static VALUE
2043 rb_file_owned_p(VALUE obj, VALUE fname)
2045 struct stat st;
2047 if (rb_stat(fname, &st) < 0) return Qfalse;
2048 return RBOOL(st.st_uid == geteuid());
2051 static VALUE
2052 rb_file_rowned_p(VALUE obj, VALUE fname)
2054 struct stat st;
2056 if (rb_stat(fname, &st) < 0) return Qfalse;
2057 return RBOOL(st.st_uid == getuid());
2061 * call-seq:
2062 * File.grpowned?(file_name) -> true or false
2064 * Returns <code>true</code> if the named file exists and the
2065 * effective group id of the calling process is the owner of
2066 * the file. Returns <code>false</code> on Windows.
2068 * _file_name_ can be an IO object.
2071 static VALUE
2072 rb_file_grpowned_p(VALUE obj, VALUE fname)
2074 #ifndef _WIN32
2075 struct stat st;
2077 if (rb_stat(fname, &st) < 0) return Qfalse;
2078 if (rb_group_member(st.st_gid)) return Qtrue;
2079 #endif
2080 return Qfalse;
2083 #if defined(S_ISUID) || defined(S_ISGID) || defined(S_ISVTX)
2084 static VALUE
2085 check3rdbyte(VALUE fname, int mode)
2087 struct stat st;
2089 if (rb_stat(fname, &st) < 0) return Qfalse;
2090 return RBOOL(st.st_mode & mode);
2092 #endif
2095 * call-seq:
2096 * File.setuid?(file_name) -> true or false
2098 * Returns <code>true</code> if the named file has the setuid bit set.
2100 * _file_name_ can be an IO object.
2103 static VALUE
2104 rb_file_suid_p(VALUE obj, VALUE fname)
2106 #ifdef S_ISUID
2107 return check3rdbyte(fname, S_ISUID);
2108 #else
2109 return Qfalse;
2110 #endif
2114 * call-seq:
2115 * File.setgid?(file_name) -> true or false
2117 * Returns <code>true</code> if the named file has the setgid bit set.
2119 * _file_name_ can be an IO object.
2122 static VALUE
2123 rb_file_sgid_p(VALUE obj, VALUE fname)
2125 #ifdef S_ISGID
2126 return check3rdbyte(fname, S_ISGID);
2127 #else
2128 return Qfalse;
2129 #endif
2133 * call-seq:
2134 * File.sticky?(file_name) -> true or false
2136 * Returns <code>true</code> if the named file has the sticky bit set.
2138 * _file_name_ can be an IO object.
2141 static VALUE
2142 rb_file_sticky_p(VALUE obj, VALUE fname)
2144 #ifdef S_ISVTX
2145 return check3rdbyte(fname, S_ISVTX);
2146 #else
2147 return Qnil;
2148 #endif
2152 * call-seq:
2153 * File.identical?(file_1, file_2) -> true or false
2155 * Returns <code>true</code> if the named files are identical.
2157 * _file_1_ and _file_2_ can be an IO object.
2159 * open("a", "w") {}
2160 * p File.identical?("a", "a") #=> true
2161 * p File.identical?("a", "./a") #=> true
2162 * File.link("a", "b")
2163 * p File.identical?("a", "b") #=> true
2164 * File.symlink("a", "c")
2165 * p File.identical?("a", "c") #=> true
2166 * open("d", "w") {}
2167 * p File.identical?("a", "d") #=> false
2170 static VALUE
2171 rb_file_identical_p(VALUE obj, VALUE fname1, VALUE fname2)
2173 #ifndef _WIN32
2174 struct stat st1, st2;
2176 if (rb_stat(fname1, &st1) < 0) return Qfalse;
2177 if (rb_stat(fname2, &st2) < 0) return Qfalse;
2178 if (st1.st_dev != st2.st_dev) return Qfalse;
2179 if (st1.st_ino != st2.st_ino) return Qfalse;
2180 return Qtrue;
2181 #else
2182 extern VALUE rb_w32_file_identical_p(VALUE, VALUE);
2183 return rb_w32_file_identical_p(fname1, fname2);
2184 #endif
2188 * call-seq:
2189 * File.size(file_name) -> integer
2191 * Returns the size of <code>file_name</code>.
2193 * _file_name_ can be an IO object.
2196 static VALUE
2197 rb_file_s_size(VALUE klass, VALUE fname)
2199 struct stat st;
2201 if (rb_stat(fname, &st) < 0) {
2202 int e = errno;
2203 FilePathValue(fname);
2204 rb_syserr_fail_path(e, fname);
2206 return OFFT2NUM(st.st_size);
2209 static VALUE
2210 rb_file_ftype(const struct stat *st)
2212 const char *t;
2214 if (S_ISREG(st->st_mode)) {
2215 t = "file";
2217 else if (S_ISDIR(st->st_mode)) {
2218 t = "directory";
2220 else if (S_ISCHR(st->st_mode)) {
2221 t = "characterSpecial";
2223 #ifdef S_ISBLK
2224 else if (S_ISBLK(st->st_mode)) {
2225 t = "blockSpecial";
2227 #endif
2228 #ifdef S_ISFIFO
2229 else if (S_ISFIFO(st->st_mode)) {
2230 t = "fifo";
2232 #endif
2233 #ifdef S_ISLNK
2234 else if (S_ISLNK(st->st_mode)) {
2235 t = "link";
2237 #endif
2238 #ifdef S_ISSOCK
2239 else if (S_ISSOCK(st->st_mode)) {
2240 t = "socket";
2242 #endif
2243 else {
2244 t = "unknown";
2247 return rb_usascii_str_new2(t);
2251 * call-seq:
2252 * File.ftype(file_name) -> string
2254 * Identifies the type of the named file; the return string is one of
2255 * ``<code>file</code>'', ``<code>directory</code>'',
2256 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
2257 * ``<code>fifo</code>'', ``<code>link</code>'',
2258 * ``<code>socket</code>'', or ``<code>unknown</code>''.
2260 * File.ftype("testfile") #=> "file"
2261 * File.ftype("/dev/tty") #=> "characterSpecial"
2262 * File.ftype("/tmp/.X11-unix/X0") #=> "socket"
2265 static VALUE
2266 rb_file_s_ftype(VALUE klass, VALUE fname)
2268 struct stat st;
2270 FilePathValue(fname);
2271 fname = rb_str_encode_ospath(fname);
2272 if (lstat_without_gvl(StringValueCStr(fname), &st) == -1) {
2273 rb_sys_fail_path(fname);
2276 return rb_file_ftype(&st);
2280 * call-seq:
2281 * File.atime(file_name) -> time
2283 * Returns the last access time for the named file as a Time object.
2285 * _file_name_ can be an IO object.
2287 * File.atime("testfile") #=> Wed Apr 09 08:51:48 CDT 2003
2291 static VALUE
2292 rb_file_s_atime(VALUE klass, VALUE fname)
2294 struct stat st;
2296 if (rb_stat(fname, &st) < 0) {
2297 int e = errno;
2298 FilePathValue(fname);
2299 rb_syserr_fail_path(e, fname);
2301 return stat_atime(&st);
2305 * call-seq:
2306 * file.atime -> time
2308 * Returns the last access time (a Time object) for <i>file</i>, or
2309 * epoch if <i>file</i> has not been accessed.
2311 * File.new("testfile").atime #=> Wed Dec 31 18:00:00 CST 1969
2315 static VALUE
2316 rb_file_atime(VALUE obj)
2318 rb_io_t *fptr;
2319 struct stat st;
2321 GetOpenFile(obj, fptr);
2322 if (fstat(fptr->fd, &st) == -1) {
2323 rb_sys_fail_path(fptr->pathv);
2325 return stat_atime(&st);
2329 * call-seq:
2330 * File.mtime(file_name) -> time
2332 * Returns the modification time for the named file as a Time object.
2334 * _file_name_ can be an IO object.
2336 * File.mtime("testfile") #=> Tue Apr 08 12:58:04 CDT 2003
2340 static VALUE
2341 rb_file_s_mtime(VALUE klass, VALUE fname)
2343 struct stat st;
2345 if (rb_stat(fname, &st) < 0) {
2346 int e = errno;
2347 FilePathValue(fname);
2348 rb_syserr_fail_path(e, fname);
2350 return stat_mtime(&st);
2354 * call-seq:
2355 * file.mtime -> time
2357 * Returns the modification time for <i>file</i>.
2359 * File.new("testfile").mtime #=> Wed Apr 09 08:53:14 CDT 2003
2363 static VALUE
2364 rb_file_mtime(VALUE obj)
2366 rb_io_t *fptr;
2367 struct stat st;
2369 GetOpenFile(obj, fptr);
2370 if (fstat(fptr->fd, &st) == -1) {
2371 rb_sys_fail_path(fptr->pathv);
2373 return stat_mtime(&st);
2377 * call-seq:
2378 * File.ctime(file_name) -> time
2380 * Returns the change time for the named file (the time at which
2381 * directory information about the file was changed, not the file
2382 * itself).
2384 * _file_name_ can be an IO object.
2386 * Note that on Windows (NTFS), returns creation time (birth time).
2388 * File.ctime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2392 static VALUE
2393 rb_file_s_ctime(VALUE klass, VALUE fname)
2395 struct stat st;
2397 if (rb_stat(fname, &st) < 0) {
2398 int e = errno;
2399 FilePathValue(fname);
2400 rb_syserr_fail_path(e, fname);
2402 return stat_ctime(&st);
2406 * call-seq:
2407 * file.ctime -> time
2409 * Returns the change time for <i>file</i> (that is, the time directory
2410 * information about the file was changed, not the file itself).
2412 * Note that on Windows (NTFS), returns creation time (birth time).
2414 * File.new("testfile").ctime #=> Wed Apr 09 08:53:14 CDT 2003
2418 static VALUE
2419 rb_file_ctime(VALUE obj)
2421 rb_io_t *fptr;
2422 struct stat st;
2424 GetOpenFile(obj, fptr);
2425 if (fstat(fptr->fd, &st) == -1) {
2426 rb_sys_fail_path(fptr->pathv);
2428 return stat_ctime(&st);
2432 * call-seq:
2433 * File.birthtime(file_name) -> time
2435 * Returns the birth time for the named file.
2437 * _file_name_ can be an IO object.
2439 * File.birthtime("testfile") #=> Wed Apr 09 08:53:13 CDT 2003
2441 * If the platform doesn't have birthtime, raises NotImplementedError.
2445 #if defined(HAVE_STAT_BIRTHTIME)
2446 RUBY_FUNC_EXPORTED VALUE
2447 rb_file_s_birthtime(VALUE klass, VALUE fname)
2449 statx_data st;
2451 if (rb_statx(fname, &st, STATX_BTIME) < 0) {
2452 int e = errno;
2453 FilePathValue(fname);
2454 rb_syserr_fail_path(e, fname);
2456 return statx_birthtime(&st, fname);
2458 #else
2459 # define rb_file_s_birthtime rb_f_notimplement
2460 #endif
2462 #if defined(HAVE_STAT_BIRTHTIME)
2464 * call-seq:
2465 * file.birthtime -> time
2467 * Returns the birth time for <i>file</i>.
2469 * File.new("testfile").birthtime #=> Wed Apr 09 08:53:14 CDT 2003
2471 * If the platform doesn't have birthtime, raises NotImplementedError.
2475 static VALUE
2476 rb_file_birthtime(VALUE obj)
2478 rb_io_t *fptr;
2479 statx_data st;
2481 GetOpenFile(obj, fptr);
2482 if (fstatx_without_gvl(fptr->fd, &st, STATX_BTIME) == -1) {
2483 rb_sys_fail_path(fptr->pathv);
2485 return statx_birthtime(&st, fptr->pathv);
2487 #else
2488 # define rb_file_birthtime rb_f_notimplement
2489 #endif
2492 * call-seq:
2493 * file.size -> integer
2495 * Returns the size of <i>file</i> in bytes.
2497 * File.new("testfile").size #=> 66
2501 off_t
2502 rb_file_size(VALUE file)
2504 if (RB_TYPE_P(file, T_FILE)) {
2505 rb_io_t *fptr;
2506 struct stat st;
2508 RB_IO_POINTER(file, fptr);
2509 if (fptr->mode & FMODE_WRITABLE) {
2510 rb_io_flush_raw(file, 0);
2513 if (fstat(fptr->fd, &st) == -1) {
2514 rb_sys_fail_path(fptr->pathv);
2517 return st.st_size;
2519 else {
2520 return NUM2OFFT(rb_funcall(file, idSize, 0));
2524 static VALUE
2525 file_size(VALUE self)
2527 return OFFT2NUM(rb_file_size(self));
2530 static int
2531 chmod_internal(const char *path, void *mode)
2533 return chmod(path, *(mode_t *)mode);
2537 * call-seq:
2538 * File.chmod(mode_int, file_name, ... ) -> integer
2540 * Changes permission bits on the named file(s) to the bit pattern
2541 * represented by <i>mode_int</i>. Actual effects are operating system
2542 * dependent (see the beginning of this section). On Unix systems, see
2543 * <code>chmod(2)</code> for details. Returns the number of files
2544 * processed.
2546 * File.chmod(0644, "testfile", "out") #=> 2
2549 static VALUE
2550 rb_file_s_chmod(int argc, VALUE *argv, VALUE _)
2552 mode_t mode;
2554 apply2args(1);
2555 mode = NUM2MODET(*argv++);
2557 return apply2files(chmod_internal, argc, argv, &mode);
2561 * call-seq:
2562 * file.chmod(mode_int) -> 0
2564 * Changes permission bits on <i>file</i> to the bit pattern
2565 * represented by <i>mode_int</i>. Actual effects are platform
2566 * dependent; on Unix systems, see <code>chmod(2)</code> for details.
2567 * Follows symbolic links. Also see File#lchmod.
2569 * f = File.new("out", "w");
2570 * f.chmod(0644) #=> 0
2573 static VALUE
2574 rb_file_chmod(VALUE obj, VALUE vmode)
2576 rb_io_t *fptr;
2577 mode_t mode;
2578 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2579 VALUE path;
2580 #endif
2582 mode = NUM2MODET(vmode);
2584 GetOpenFile(obj, fptr);
2585 #ifdef HAVE_FCHMOD
2586 if (fchmod(fptr->fd, mode) == -1) {
2587 if (HAVE_FCHMOD || errno != ENOSYS)
2588 rb_sys_fail_path(fptr->pathv);
2590 else {
2591 if (!HAVE_FCHMOD) return INT2FIX(0);
2593 #endif
2594 #if !defined HAVE_FCHMOD || !HAVE_FCHMOD
2595 if (NIL_P(fptr->pathv)) return Qnil;
2596 path = rb_str_encode_ospath(fptr->pathv);
2597 if (chmod(RSTRING_PTR(path), mode) == -1)
2598 rb_sys_fail_path(fptr->pathv);
2599 #endif
2601 return INT2FIX(0);
2604 #if defined(HAVE_LCHMOD)
2605 static int
2606 lchmod_internal(const char *path, void *mode)
2608 return lchmod(path, *(mode_t *)mode);
2612 * call-seq:
2613 * File.lchmod(mode_int, file_name, ...) -> integer
2615 * Equivalent to File::chmod, but does not follow symbolic links (so
2616 * it will change the permissions associated with the link, not the
2617 * file referenced by the link). Often not available.
2621 static VALUE
2622 rb_file_s_lchmod(int argc, VALUE *argv, VALUE _)
2624 mode_t mode;
2626 apply2args(1);
2627 mode = NUM2MODET(*argv++);
2629 return apply2files(lchmod_internal, argc, argv, &mode);
2631 #else
2632 #define rb_file_s_lchmod rb_f_notimplement
2633 #endif
2635 static inline rb_uid_t
2636 to_uid(VALUE u)
2638 if (NIL_P(u)) {
2639 return (rb_uid_t)-1;
2641 return NUM2UIDT(u);
2644 static inline rb_gid_t
2645 to_gid(VALUE g)
2647 if (NIL_P(g)) {
2648 return (rb_gid_t)-1;
2650 return NUM2GIDT(g);
2653 struct chown_args {
2654 rb_uid_t owner;
2655 rb_gid_t group;
2658 static int
2659 chown_internal(const char *path, void *arg)
2661 struct chown_args *args = arg;
2662 return chown(path, args->owner, args->group);
2666 * call-seq:
2667 * File.chown(owner_int, group_int, file_name, ...) -> integer
2669 * Changes the owner and group of the named file(s) to the given
2670 * numeric owner and group id's. Only a process with superuser
2671 * privileges may change the owner of a file. The current owner of a
2672 * file may change the file's group to any group to which the owner
2673 * belongs. A <code>nil</code> or -1 owner or group id is ignored.
2674 * Returns the number of files processed.
2676 * File.chown(nil, 100, "testfile")
2680 static VALUE
2681 rb_file_s_chown(int argc, VALUE *argv, VALUE _)
2683 struct chown_args arg;
2685 apply2args(2);
2686 arg.owner = to_uid(*argv++);
2687 arg.group = to_gid(*argv++);
2689 return apply2files(chown_internal, argc, argv, &arg);
2693 * call-seq:
2694 * file.chown(owner_int, group_int ) -> 0
2696 * Changes the owner and group of <i>file</i> to the given numeric
2697 * owner and group id's. Only a process with superuser privileges may
2698 * change the owner of a file. The current owner of a file may change
2699 * the file's group to any group to which the owner belongs. A
2700 * <code>nil</code> or -1 owner or group id is ignored. Follows
2701 * symbolic links. See also File#lchown.
2703 * File.new("testfile").chown(502, 1000)
2707 static VALUE
2708 rb_file_chown(VALUE obj, VALUE owner, VALUE group)
2710 rb_io_t *fptr;
2711 rb_uid_t o;
2712 rb_gid_t g;
2713 #ifndef HAVE_FCHOWN
2714 VALUE path;
2715 #endif
2717 o = to_uid(owner);
2718 g = to_gid(group);
2719 GetOpenFile(obj, fptr);
2720 #ifndef HAVE_FCHOWN
2721 if (NIL_P(fptr->pathv)) return Qnil;
2722 path = rb_str_encode_ospath(fptr->pathv);
2723 if (chown(RSTRING_PTR(path), o, g) == -1)
2724 rb_sys_fail_path(fptr->pathv);
2725 #else
2726 if (fchown(fptr->fd, o, g) == -1)
2727 rb_sys_fail_path(fptr->pathv);
2728 #endif
2730 return INT2FIX(0);
2733 #if defined(HAVE_LCHOWN)
2734 static int
2735 lchown_internal(const char *path, void *arg)
2737 struct chown_args *args = arg;
2738 return lchown(path, args->owner, args->group);
2742 * call-seq:
2743 * File.lchown(owner_int, group_int, file_name,..) -> integer
2745 * Equivalent to File::chown, but does not follow symbolic
2746 * links (so it will change the owner associated with the link, not the
2747 * file referenced by the link). Often not available. Returns number
2748 * of files in the argument list.
2752 static VALUE
2753 rb_file_s_lchown(int argc, VALUE *argv, VALUE _)
2755 struct chown_args arg;
2757 apply2args(2);
2758 arg.owner = to_uid(*argv++);
2759 arg.group = to_gid(*argv++);
2761 return apply2files(lchown_internal, argc, argv, &arg);
2763 #else
2764 #define rb_file_s_lchown rb_f_notimplement
2765 #endif
2767 struct utime_args {
2768 const struct timespec* tsp;
2769 VALUE atime, mtime;
2770 int follow; /* Whether to act on symlinks (1) or their referent (0) */
2773 #ifdef UTIME_EINVAL
2774 NORETURN(static void utime_failed(struct apply_arg *));
2776 static void
2777 utime_failed(struct apply_arg *aa)
2779 int e = aa->errnum;
2780 VALUE path = aa->fn[aa->i].path;
2781 struct utime_args *ua = aa->arg;
2783 if (ua->tsp && e == EINVAL) {
2784 VALUE e[2], a = Qnil, m = Qnil;
2785 int d = 0;
2786 VALUE atime = ua->atime;
2787 VALUE mtime = ua->mtime;
2789 if (!NIL_P(atime)) {
2790 a = rb_inspect(atime);
2792 if (!NIL_P(mtime) && mtime != atime && !rb_equal(atime, mtime)) {
2793 m = rb_inspect(mtime);
2795 if (NIL_P(a)) e[0] = m;
2796 else if (NIL_P(m) || rb_str_cmp(a, m) == 0) e[0] = a;
2797 else {
2798 e[0] = rb_str_plus(a, rb_str_new_cstr(" or "));
2799 rb_str_append(e[0], m);
2800 d = 1;
2802 if (!NIL_P(e[0])) {
2803 if (path) {
2804 if (!d) e[0] = rb_str_dup(e[0]);
2805 rb_str_append(rb_str_cat2(e[0], " for "), path);
2807 e[1] = INT2FIX(EINVAL);
2808 rb_exc_raise(rb_class_new_instance(2, e, rb_eSystemCallError));
2811 rb_syserr_fail_path(e, path);
2813 #endif
2815 #if defined(HAVE_UTIMES)
2817 static int
2818 utime_internal(const char *path, void *arg)
2820 struct utime_args *v = arg;
2821 const struct timespec *tsp = v->tsp;
2822 struct timeval tvbuf[2], *tvp = NULL;
2824 #if defined(HAVE_UTIMENSAT)
2825 static int try_utimensat = 1;
2826 # ifdef AT_SYMLINK_NOFOLLOW
2827 static int try_utimensat_follow = 1;
2828 # else
2829 const int try_utimensat_follow = 0;
2830 # endif
2831 int flags = 0;
2833 if (v->follow ? try_utimensat_follow : try_utimensat) {
2834 # ifdef AT_SYMLINK_NOFOLLOW
2835 if (v->follow) {
2836 flags = AT_SYMLINK_NOFOLLOW;
2838 # endif
2840 if (utimensat(AT_FDCWD, path, tsp, flags) < 0) {
2841 if (errno == ENOSYS) {
2842 # ifdef AT_SYMLINK_NOFOLLOW
2843 try_utimensat_follow = 0;
2844 # endif
2845 if (!v->follow)
2846 try_utimensat = 0;
2847 goto no_utimensat;
2849 return -1; /* calls utime_failed */
2851 return 0;
2853 no_utimensat:
2854 #endif
2856 if (tsp) {
2857 tvbuf[0].tv_sec = tsp[0].tv_sec;
2858 tvbuf[0].tv_usec = (int)(tsp[0].tv_nsec / 1000);
2859 tvbuf[1].tv_sec = tsp[1].tv_sec;
2860 tvbuf[1].tv_usec = (int)(tsp[1].tv_nsec / 1000);
2861 tvp = tvbuf;
2863 #ifdef HAVE_LUTIMES
2864 if (v->follow) return lutimes(path, tvp);
2865 #endif
2866 return utimes(path, tvp);
2869 #else
2871 #if !defined HAVE_UTIME_H && !defined HAVE_SYS_UTIME_H
2872 struct utimbuf {
2873 long actime;
2874 long modtime;
2876 #endif
2878 static int
2879 utime_internal(const char *path, void *arg)
2881 struct utime_args *v = arg;
2882 const struct timespec *tsp = v->tsp;
2883 struct utimbuf utbuf, *utp = NULL;
2884 if (tsp) {
2885 utbuf.actime = tsp[0].tv_sec;
2886 utbuf.modtime = tsp[1].tv_sec;
2887 utp = &utbuf;
2889 return utime(path, utp);
2892 #endif
2894 static VALUE
2895 utime_internal_i(int argc, VALUE *argv, int follow)
2897 struct utime_args args;
2898 struct timespec tss[2], *tsp = NULL;
2900 apply2args(2);
2901 args.atime = *argv++;
2902 args.mtime = *argv++;
2904 args.follow = follow;
2906 if (!NIL_P(args.atime) || !NIL_P(args.mtime)) {
2907 tsp = tss;
2908 tsp[0] = rb_time_timespec(args.atime);
2909 if (args.atime == args.mtime)
2910 tsp[1] = tsp[0];
2911 else
2912 tsp[1] = rb_time_timespec(args.mtime);
2914 args.tsp = tsp;
2916 return apply2files(utime_internal, argc, argv, &args);
2920 * call-seq:
2921 * File.utime(atime, mtime, file_name, ...) -> integer
2923 * Sets the access and modification times of each named file to the
2924 * first two arguments. If a file is a symlink, this method acts upon
2925 * its referent rather than the link itself; for the inverse
2926 * behavior see File.lutime. Returns the number of file
2927 * names in the argument list.
2930 static VALUE
2931 rb_file_s_utime(int argc, VALUE *argv, VALUE _)
2933 return utime_internal_i(argc, argv, FALSE);
2936 #if defined(HAVE_UTIMES) && (defined(HAVE_LUTIMES) || (defined(HAVE_UTIMENSAT) && defined(AT_SYMLINK_NOFOLLOW)))
2939 * call-seq:
2940 * File.lutime(atime, mtime, file_name, ...) -> integer
2942 * Sets the access and modification times of each named file to the
2943 * first two arguments. If a file is a symlink, this method acts upon
2944 * the link itself as opposed to its referent; for the inverse
2945 * behavior, see File.utime. Returns the number of file
2946 * names in the argument list.
2949 static VALUE
2950 rb_file_s_lutime(int argc, VALUE *argv, VALUE _)
2952 return utime_internal_i(argc, argv, TRUE);
2954 #else
2955 #define rb_file_s_lutime rb_f_notimplement
2956 #endif
2958 #ifdef RUBY_FUNCTION_NAME_STRING
2959 # define syserr_fail2(e, s1, s2) syserr_fail2_in(RUBY_FUNCTION_NAME_STRING, e, s1, s2)
2960 #else
2961 # define syserr_fail2_in(func, e, s1, s2) syserr_fail2(e, s1, s2)
2962 #endif
2963 #define sys_fail2(s1, s2) syserr_fail2(errno, s1, s2)
2964 NORETURN(static void syserr_fail2_in(const char *,int,VALUE,VALUE));
2965 static void
2966 syserr_fail2_in(const char *func, int e, VALUE s1, VALUE s2)
2968 VALUE str;
2969 #ifdef MAX_PATH
2970 const int max_pathlen = MAX_PATH;
2971 #else
2972 const int max_pathlen = MAXPATHLEN;
2973 #endif
2975 if (e == EEXIST) {
2976 rb_syserr_fail_path(e, rb_str_ellipsize(s2, max_pathlen));
2978 str = rb_str_new_cstr("(");
2979 rb_str_append(str, rb_str_ellipsize(s1, max_pathlen));
2980 rb_str_cat2(str, ", ");
2981 rb_str_append(str, rb_str_ellipsize(s2, max_pathlen));
2982 rb_str_cat2(str, ")");
2983 #ifdef RUBY_FUNCTION_NAME_STRING
2984 rb_syserr_fail_path_in(func, e, str);
2985 #else
2986 rb_syserr_fail_path(e, str);
2987 #endif
2990 #ifdef HAVE_LINK
2992 * call-seq:
2993 * File.link(old_name, new_name) -> 0
2995 * Creates a new name for an existing file using a hard link. Will not
2996 * overwrite <i>new_name</i> if it already exists (raising a subclass
2997 * of SystemCallError). Not available on all platforms.
2999 * File.link("testfile", ".testfile") #=> 0
3000 * IO.readlines(".testfile")[0] #=> "This is line one\n"
3003 static VALUE
3004 rb_file_s_link(VALUE klass, VALUE from, VALUE to)
3006 FilePathValue(from);
3007 FilePathValue(to);
3008 from = rb_str_encode_ospath(from);
3009 to = rb_str_encode_ospath(to);
3011 if (link(StringValueCStr(from), StringValueCStr(to)) < 0) {
3012 sys_fail2(from, to);
3014 return INT2FIX(0);
3016 #else
3017 #define rb_file_s_link rb_f_notimplement
3018 #endif
3020 #ifdef HAVE_SYMLINK
3022 * call-seq:
3023 * File.symlink(old_name, new_name) -> 0
3025 * Creates a symbolic link called <i>new_name</i> for the existing file
3026 * <i>old_name</i>. Raises a NotImplemented exception on
3027 * platforms that do not support symbolic links.
3029 * File.symlink("testfile", "link2test") #=> 0
3033 static VALUE
3034 rb_file_s_symlink(VALUE klass, VALUE from, VALUE to)
3036 FilePathValue(from);
3037 FilePathValue(to);
3038 from = rb_str_encode_ospath(from);
3039 to = rb_str_encode_ospath(to);
3041 if (symlink(StringValueCStr(from), StringValueCStr(to)) < 0) {
3042 sys_fail2(from, to);
3044 return INT2FIX(0);
3046 #else
3047 #define rb_file_s_symlink rb_f_notimplement
3048 #endif
3050 #ifdef HAVE_READLINK
3052 * call-seq:
3053 * File.readlink(link_name) -> file_name
3055 * Returns the name of the file referenced by the given link.
3056 * Not available on all platforms.
3058 * File.symlink("testfile", "link2test") #=> 0
3059 * File.readlink("link2test") #=> "testfile"
3062 static VALUE
3063 rb_file_s_readlink(VALUE klass, VALUE path)
3065 return rb_readlink(path, rb_filesystem_encoding());
3068 #ifndef _WIN32
3069 struct readlink_arg {
3070 const char *path;
3071 char *buf;
3072 size_t size;
3075 static void *
3076 nogvl_readlink(void *ptr)
3078 struct readlink_arg *ra = ptr;
3080 return (void *)(VALUE)readlink(ra->path, ra->buf, ra->size);
3083 static ssize_t
3084 readlink_without_gvl(VALUE path, VALUE buf, size_t size)
3086 struct readlink_arg ra;
3088 ra.path = RSTRING_PTR(path);
3089 ra.buf = RSTRING_PTR(buf);
3090 ra.size = size;
3092 return (ssize_t)rb_thread_call_without_gvl(nogvl_readlink, &ra,
3093 RUBY_UBF_IO, 0);
3096 VALUE
3097 rb_readlink(VALUE path, rb_encoding *enc)
3099 int size = 100;
3100 ssize_t rv;
3101 VALUE v;
3103 FilePathValue(path);
3104 path = rb_str_encode_ospath(path);
3105 v = rb_enc_str_new(0, size, enc);
3106 while ((rv = readlink_without_gvl(path, v, size)) == size
3107 #ifdef _AIX
3108 || (rv < 0 && errno == ERANGE) /* quirky behavior of GPFS */
3109 #endif
3111 rb_str_modify_expand(v, size);
3112 size *= 2;
3113 rb_str_set_len(v, size);
3115 if (rv < 0) {
3116 int e = errno;
3117 rb_str_resize(v, 0);
3118 rb_syserr_fail_path(e, path);
3120 rb_str_resize(v, rv);
3122 return v;
3124 #endif
3125 #else
3126 #define rb_file_s_readlink rb_f_notimplement
3127 #endif
3129 static int
3130 unlink_internal(const char *path, void *arg)
3132 return unlink(path);
3136 * call-seq:
3137 * File.delete(file_name, ...) -> integer
3138 * File.unlink(file_name, ...) -> integer
3140 * Deletes the named files, returning the number of names
3141 * passed as arguments. Raises an exception on any error.
3142 * Since the underlying implementation relies on the
3143 * <code>unlink(2)</code> system call, the type of
3144 * exception raised depends on its error type (see
3145 * https://linux.die.net/man/2/unlink) and has the form of
3146 * e.g. Errno::ENOENT.
3148 * See also Dir::rmdir.
3151 static VALUE
3152 rb_file_s_unlink(int argc, VALUE *argv, VALUE klass)
3154 return apply2files(unlink_internal, argc, argv, 0);
3157 struct rename_args {
3158 const char *src;
3159 const char *dst;
3162 static void *
3163 no_gvl_rename(void *ptr)
3165 struct rename_args *ra = ptr;
3167 return (void *)(VALUE)rename(ra->src, ra->dst);
3171 * call-seq:
3172 * File.rename(old_name, new_name) -> 0
3174 * Renames the given file to the new name. Raises a SystemCallError
3175 * if the file cannot be renamed.
3177 * File.rename("afile", "afile.bak") #=> 0
3180 static VALUE
3181 rb_file_s_rename(VALUE klass, VALUE from, VALUE to)
3183 struct rename_args ra;
3184 VALUE f, t;
3186 FilePathValue(from);
3187 FilePathValue(to);
3188 f = rb_str_encode_ospath(from);
3189 t = rb_str_encode_ospath(to);
3190 ra.src = StringValueCStr(f);
3191 ra.dst = StringValueCStr(t);
3192 #if defined __CYGWIN__
3193 errno = 0;
3194 #endif
3195 if ((int)(VALUE)rb_thread_call_without_gvl(no_gvl_rename, &ra,
3196 RUBY_UBF_IO, 0) < 0) {
3197 int e = errno;
3198 #if defined DOSISH
3199 switch (e) {
3200 case EEXIST:
3201 if (chmod(ra.dst, 0666) == 0 &&
3202 unlink(ra.dst) == 0 &&
3203 rename(ra.src, ra.dst) == 0)
3204 return INT2FIX(0);
3206 #endif
3207 syserr_fail2(e, from, to);
3210 return INT2FIX(0);
3214 * call-seq:
3215 * File.umask() -> integer
3216 * File.umask(integer) -> integer
3218 * Returns the current umask value for this process. If the optional
3219 * argument is given, set the umask to that value and return the
3220 * previous value. Umask values are <em>subtracted</em> from the
3221 * default permissions, so a umask of <code>0222</code> would make a
3222 * file read-only for everyone.
3224 * File.umask(0006) #=> 18
3225 * File.umask #=> 6
3228 static VALUE
3229 rb_file_s_umask(int argc, VALUE *argv, VALUE _)
3231 mode_t omask = 0;
3233 switch (argc) {
3234 case 0:
3235 omask = umask(0);
3236 umask(omask);
3237 break;
3238 case 1:
3239 omask = umask(NUM2MODET(argv[0]));
3240 break;
3241 default:
3242 rb_error_arity(argc, 0, 1);
3244 return MODET2NUM(omask);
3247 #ifdef __CYGWIN__
3248 #undef DOSISH
3249 #endif
3250 #if defined __CYGWIN__ || defined DOSISH
3251 #define DOSISH_UNC
3252 #define DOSISH_DRIVE_LETTER
3253 #define FILE_ALT_SEPARATOR '\\'
3254 #endif
3255 #ifdef FILE_ALT_SEPARATOR
3256 #define isdirsep(x) ((x) == '/' || (x) == FILE_ALT_SEPARATOR)
3257 # ifdef DOSISH
3258 static const char file_alt_separator[] = {FILE_ALT_SEPARATOR, '\0'};
3259 # endif
3260 #else
3261 #define isdirsep(x) ((x) == '/')
3262 #endif
3264 #ifndef USE_NTFS
3265 #if defined _WIN32
3266 #define USE_NTFS 1
3267 #else
3268 #define USE_NTFS 0
3269 #endif
3270 #endif
3271 #ifndef USE_NTFS_ADS
3272 # if USE_NTFS
3273 # define USE_NTFS_ADS 1
3274 # else
3275 # define USE_NTFS_ADS 0
3276 # endif
3277 #endif
3279 #if USE_NTFS
3280 #define istrailinggarbage(x) ((x) == '.' || (x) == ' ')
3281 #else
3282 #define istrailinggarbage(x) 0
3283 #endif
3284 #if USE_NTFS_ADS
3285 # define isADS(x) ((x) == ':')
3286 #else
3287 # define isADS(x) 0
3288 #endif
3290 #define Next(p, e, enc) ((p) + rb_enc_mbclen((p), (e), (enc)))
3291 #define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
3293 #if defined(DOSISH_UNC)
3294 #define has_unc(buf) (isdirsep((buf)[0]) && isdirsep((buf)[1]))
3295 #else
3296 #define has_unc(buf) 0
3297 #endif
3299 #ifdef DOSISH_DRIVE_LETTER
3300 static inline int
3301 has_drive_letter(const char *buf)
3303 if (ISALPHA(buf[0]) && buf[1] == ':') {
3304 return 1;
3306 else {
3307 return 0;
3311 #ifndef _WIN32
3312 static char*
3313 getcwdofdrv(int drv)
3315 char drive[4];
3316 char *drvcwd, *oldcwd;
3318 drive[0] = drv;
3319 drive[1] = ':';
3320 drive[2] = '\0';
3322 /* the only way that I know to get the current directory
3323 of a particular drive is to change chdir() to that drive,
3324 so save the old cwd before chdir()
3326 oldcwd = ruby_getcwd();
3327 if (chdir(drive) == 0) {
3328 drvcwd = ruby_getcwd();
3329 chdir(oldcwd);
3330 xfree(oldcwd);
3332 else {
3333 /* perhaps the drive is not exist. we return only drive letter */
3334 drvcwd = strdup(drive);
3336 return drvcwd;
3339 static inline int
3340 not_same_drive(VALUE path, int drive)
3342 const char *p = RSTRING_PTR(path);
3343 if (RSTRING_LEN(path) < 2) return 0;
3344 if (has_drive_letter(p)) {
3345 return TOLOWER(p[0]) != TOLOWER(drive);
3347 else {
3348 return has_unc(p);
3351 #endif
3352 #endif
3354 static inline char *
3355 skiproot(const char *path, const char *end, rb_encoding *enc)
3357 #ifdef DOSISH_DRIVE_LETTER
3358 if (path + 2 <= end && has_drive_letter(path)) path += 2;
3359 #endif
3360 while (path < end && isdirsep(*path)) path++;
3361 return (char *)path;
3364 #define nextdirsep rb_enc_path_next
3365 char *
3366 rb_enc_path_next(const char *s, const char *e, rb_encoding *enc)
3368 while (s < e && !isdirsep(*s)) {
3369 Inc(s, e, enc);
3371 return (char *)s;
3374 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3375 #define skipprefix rb_enc_path_skip_prefix
3376 #else
3377 #define skipprefix(path, end, enc) (path)
3378 #endif
3379 char *
3380 rb_enc_path_skip_prefix(const char *path, const char *end, rb_encoding *enc)
3382 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3383 #ifdef DOSISH_UNC
3384 if (path + 2 <= end && isdirsep(path[0]) && isdirsep(path[1])) {
3385 path += 2;
3386 while (path < end && isdirsep(*path)) path++;
3387 if ((path = rb_enc_path_next(path, end, enc)) < end && path[0] && path[1] && !isdirsep(path[1]))
3388 path = rb_enc_path_next(path + 1, end, enc);
3389 return (char *)path;
3391 #endif
3392 #ifdef DOSISH_DRIVE_LETTER
3393 if (has_drive_letter(path))
3394 return (char *)(path + 2);
3395 #endif
3396 #endif
3397 return (char *)path;
3400 static inline char *
3401 skipprefixroot(const char *path, const char *end, rb_encoding *enc)
3403 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
3404 char *p = skipprefix(path, end, enc);
3405 while (isdirsep(*p)) p++;
3406 return p;
3407 #else
3408 return skiproot(path, end, enc);
3409 #endif
3412 #define strrdirsep rb_enc_path_last_separator
3413 char *
3414 rb_enc_path_last_separator(const char *path, const char *end, rb_encoding *enc)
3416 char *last = NULL;
3417 while (path < end) {
3418 if (isdirsep(*path)) {
3419 const char *tmp = path++;
3420 while (path < end && isdirsep(*path)) path++;
3421 if (path >= end) break;
3422 last = (char *)tmp;
3424 else {
3425 Inc(path, end, enc);
3428 return last;
3431 static char *
3432 chompdirsep(const char *path, const char *end, rb_encoding *enc)
3434 while (path < end) {
3435 if (isdirsep(*path)) {
3436 const char *last = path++;
3437 while (path < end && isdirsep(*path)) path++;
3438 if (path >= end) return (char *)last;
3440 else {
3441 Inc(path, end, enc);
3444 return (char *)path;
3447 char *
3448 rb_enc_path_end(const char *path, const char *end, rb_encoding *enc)
3450 if (path < end && isdirsep(*path)) path++;
3451 return chompdirsep(path, end, enc);
3454 static rb_encoding *
3455 fs_enc_check(VALUE path1, VALUE path2)
3457 rb_encoding *enc = rb_enc_check(path1, path2);
3458 int encidx = rb_enc_to_index(enc);
3459 if (encidx == ENCINDEX_US_ASCII) {
3460 encidx = rb_enc_get_index(path1);
3461 if (encidx == ENCINDEX_US_ASCII)
3462 encidx = rb_enc_get_index(path2);
3463 enc = rb_enc_from_index(encidx);
3465 return enc;
3468 #if USE_NTFS
3469 static char *
3470 ntfs_tail(const char *path, const char *end, rb_encoding *enc)
3472 while (path < end && *path == '.') path++;
3473 while (path < end && !isADS(*path)) {
3474 if (istrailinggarbage(*path)) {
3475 const char *last = path++;
3476 while (path < end && istrailinggarbage(*path)) path++;
3477 if (path >= end || isADS(*path)) return (char *)last;
3479 else if (isdirsep(*path)) {
3480 const char *last = path++;
3481 while (path < end && isdirsep(*path)) path++;
3482 if (path >= end) return (char *)last;
3483 if (isADS(*path)) path++;
3485 else {
3486 Inc(path, end, enc);
3489 return (char *)path;
3491 #endif
3493 #define BUFCHECK(cond) do {\
3494 bdiff = p - buf;\
3495 if (cond) {\
3496 do {buflen *= 2;} while (cond);\
3497 rb_str_resize(result, buflen);\
3498 buf = RSTRING_PTR(result);\
3499 p = buf + bdiff;\
3500 pend = buf + buflen;\
3502 } while (0)
3504 #define BUFINIT() (\
3505 p = buf = RSTRING_PTR(result),\
3506 buflen = RSTRING_LEN(result),\
3507 pend = p + buflen)
3509 #ifdef __APPLE__
3510 # define SKIPPATHSEP(p) ((*(p)) ? 1 : 0)
3511 #else
3512 # define SKIPPATHSEP(p) 1
3513 #endif
3515 #define BUFCOPY(srcptr, srclen) do { \
3516 const int skip = SKIPPATHSEP(p); \
3517 rb_str_set_len(result, p-buf+skip); \
3518 BUFCHECK(bdiff + ((srclen)+skip) >= buflen); \
3519 p += skip; \
3520 memcpy(p, (srcptr), (srclen)); \
3521 p += (srclen); \
3522 } while (0)
3524 #define WITH_ROOTDIFF(stmt) do { \
3525 long rootdiff = root - buf; \
3526 stmt; \
3527 root = buf + rootdiff; \
3528 } while (0)
3530 static VALUE
3531 copy_home_path(VALUE result, const char *dir)
3533 char *buf;
3534 #if defined DOSISH || defined __CYGWIN__
3535 char *p, *bend;
3536 rb_encoding *enc;
3537 #endif
3538 long dirlen;
3539 int encidx;
3541 dirlen = strlen(dir);
3542 rb_str_resize(result, dirlen);
3543 memcpy(buf = RSTRING_PTR(result), dir, dirlen);
3544 encidx = rb_filesystem_encindex();
3545 rb_enc_associate_index(result, encidx);
3546 #if defined DOSISH || defined __CYGWIN__
3547 enc = rb_enc_from_index(encidx);
3548 for (bend = (p = buf) + dirlen; p < bend; Inc(p, bend, enc)) {
3549 if (*p == '\\') {
3550 *p = '/';
3553 #endif
3554 return result;
3557 VALUE
3558 rb_home_dir_of(VALUE user, VALUE result)
3560 #ifdef HAVE_PWD_H
3561 struct passwd *pwPtr;
3562 #else
3563 extern char *getlogin(void);
3564 const char *pwPtr = 0;
3565 # define endpwent() ((void)0)
3566 #endif
3567 const char *dir, *username = RSTRING_PTR(user);
3568 rb_encoding *enc = rb_enc_get(user);
3569 #if defined _WIN32
3570 rb_encoding *fsenc = rb_utf8_encoding();
3571 #else
3572 rb_encoding *fsenc = rb_filesystem_encoding();
3573 #endif
3574 if (enc != fsenc) {
3575 dir = username = RSTRING_PTR(rb_str_conv_enc(user, enc, fsenc));
3578 #ifdef HAVE_PWD_H
3579 pwPtr = getpwnam(username);
3580 #else
3581 if (strcasecmp(username, getlogin()) == 0)
3582 dir = pwPtr = getenv("HOME");
3583 #endif
3584 if (!pwPtr) {
3585 endpwent();
3586 rb_raise(rb_eArgError, "user %"PRIsVALUE" doesn't exist", user);
3588 #ifdef HAVE_PWD_H
3589 dir = pwPtr->pw_dir;
3590 #endif
3591 copy_home_path(result, dir);
3592 endpwent();
3593 return result;
3596 #ifndef _WIN32
3597 VALUE
3598 rb_default_home_dir(VALUE result)
3600 const char *dir = getenv("HOME");
3602 #if defined HAVE_PWD_H
3603 if (!dir) {
3604 /* We'll look up the user's default home dir in the password db by
3605 * login name, if possible, and failing that will fall back to looking
3606 * the information up by uid (as would be needed for processes that
3607 * are not a descendant of login(1) or a work-alike).
3609 * While the lookup by uid is more likely to succeed (since we always
3610 * have a uid, but may or may not have a login name), we prefer first
3611 * looking up by name to accommodate the possibility of multiple login
3612 * names (each with its own record in the password database, so each
3613 * with a potentially different home directory) being mapped to the
3614 * same uid (as explicitly allowed for by POSIX; see getlogin(3posix)).
3616 VALUE login_name = rb_getlogin();
3618 # if !defined(HAVE_GETPWUID_R) && !defined(HAVE_GETPWUID)
3619 /* This is a corner case, but for backward compatibility reasons we
3620 * want to emit this error if neither the lookup by login name nor
3621 * lookup by getuid() has a chance of succeeding.
3623 if (NIL_P(login_name)) {
3624 rb_raise(rb_eArgError, "couldn't find login name -- expanding `~'");
3626 # endif
3628 VALUE pw_dir = rb_getpwdirnam_for_login(login_name);
3629 if (NIL_P(pw_dir)) {
3630 pw_dir = rb_getpwdiruid();
3631 if (NIL_P(pw_dir)) {
3632 rb_raise(rb_eArgError, "couldn't find home for uid `%ld'", (long)getuid());
3636 /* found it */
3637 copy_home_path(result, RSTRING_PTR(pw_dir));
3638 rb_str_resize(pw_dir, 0);
3639 return result;
3641 #endif
3642 if (!dir) {
3643 rb_raise(rb_eArgError, "couldn't find HOME environment -- expanding `~'");
3645 return copy_home_path(result, dir);
3648 static VALUE
3649 ospath_new(const char *ptr, long len, rb_encoding *fsenc)
3651 #if NORMALIZE_UTF8PATH
3652 VALUE path = rb_str_normalize_ospath(ptr, len);
3653 rb_enc_associate(path, fsenc);
3654 return path;
3655 #else
3656 return rb_enc_str_new(ptr, len, fsenc);
3657 #endif
3660 static char *
3661 append_fspath(VALUE result, VALUE fname, char *dir, rb_encoding **enc, rb_encoding *fsenc)
3663 char *buf, *cwdp = dir;
3664 VALUE dirname = Qnil;
3665 size_t dirlen = strlen(dir), buflen = rb_str_capacity(result);
3667 if (NORMALIZE_UTF8PATH || *enc != fsenc) {
3668 rb_encoding *direnc = fs_enc_check(fname, dirname = ospath_new(dir, dirlen, fsenc));
3669 if (direnc != fsenc) {
3670 dirname = rb_str_conv_enc(dirname, fsenc, direnc);
3671 RSTRING_GETMEM(dirname, cwdp, dirlen);
3673 else if (NORMALIZE_UTF8PATH) {
3674 RSTRING_GETMEM(dirname, cwdp, dirlen);
3676 *enc = direnc;
3678 do {buflen *= 2;} while (dirlen > buflen);
3679 rb_str_resize(result, buflen);
3680 buf = RSTRING_PTR(result);
3681 memcpy(buf, cwdp, dirlen);
3682 xfree(dir);
3683 if (!NIL_P(dirname)) rb_str_resize(dirname, 0);
3684 rb_enc_associate(result, *enc);
3685 return buf + dirlen;
3688 VALUE
3689 rb_file_expand_path_internal(VALUE fname, VALUE dname, int abs_mode, int long_name, VALUE result)
3691 const char *s, *b, *fend;
3692 char *buf, *p, *pend, *root;
3693 size_t buflen, bdiff;
3694 rb_encoding *enc, *fsenc = rb_filesystem_encoding();
3696 s = StringValuePtr(fname);
3697 fend = s + RSTRING_LEN(fname);
3698 enc = rb_enc_get(fname);
3699 BUFINIT();
3701 if (s[0] == '~' && abs_mode == 0) { /* execute only if NOT absolute_path() */
3702 long userlen = 0;
3703 if (isdirsep(s[1]) || s[1] == '\0') {
3704 buf = 0;
3705 b = 0;
3706 rb_str_set_len(result, 0);
3707 if (*++s) ++s;
3708 rb_default_home_dir(result);
3710 else {
3711 s = nextdirsep(b = s, fend, enc);
3712 b++; /* b[0] is '~' */
3713 userlen = s - b;
3714 BUFCHECK(bdiff + userlen >= buflen);
3715 memcpy(p, b, userlen);
3716 ENC_CODERANGE_CLEAR(result);
3717 rb_str_set_len(result, userlen);
3718 rb_enc_associate(result, enc);
3719 rb_home_dir_of(result, result);
3720 buf = p + 1;
3721 p += userlen;
3723 if (!rb_is_absolute_path(RSTRING_PTR(result))) {
3724 if (userlen) {
3725 rb_enc_raise(enc, rb_eArgError, "non-absolute home of %.*s%.0"PRIsVALUE,
3726 (int)userlen, b, fname);
3728 else {
3729 rb_raise(rb_eArgError, "non-absolute home");
3732 BUFINIT();
3733 p = pend;
3735 #ifdef DOSISH_DRIVE_LETTER
3736 /* skip drive letter */
3737 else if (has_drive_letter(s)) {
3738 if (isdirsep(s[2])) {
3739 /* specified drive letter, and full path */
3740 /* skip drive letter */
3741 BUFCHECK(bdiff + 2 >= buflen);
3742 memcpy(p, s, 2);
3743 p += 2;
3744 s += 2;
3745 rb_enc_copy(result, fname);
3747 else {
3748 /* specified drive, but not full path */
3749 int same = 0;
3750 if (!NIL_P(dname) && !not_same_drive(dname, s[0])) {
3751 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3752 BUFINIT();
3753 if (has_drive_letter(p) && TOLOWER(p[0]) == TOLOWER(s[0])) {
3754 /* ok, same drive */
3755 same = 1;
3758 if (!same) {
3759 char *e = append_fspath(result, fname, getcwdofdrv(*s), &enc, fsenc);
3760 BUFINIT();
3761 p = e;
3763 else {
3764 rb_enc_associate(result, enc = fs_enc_check(result, fname));
3765 p = pend;
3767 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3768 s += 2;
3771 #endif
3772 else if (!rb_is_absolute_path(s)) {
3773 if (!NIL_P(dname)) {
3774 rb_file_expand_path_internal(dname, Qnil, abs_mode, long_name, result);
3775 rb_enc_associate(result, fs_enc_check(result, fname));
3776 BUFINIT();
3777 p = pend;
3779 else {
3780 char *e = append_fspath(result, fname, ruby_getcwd(), &enc, fsenc);
3781 BUFINIT();
3782 p = e;
3784 #if defined DOSISH || defined __CYGWIN__
3785 if (isdirsep(*s)) {
3786 /* specified full path, but not drive letter nor UNC */
3787 /* we need to get the drive letter or UNC share name */
3788 p = skipprefix(buf, p, enc);
3790 else
3791 #endif
3792 p = chompdirsep(skiproot(buf, p, enc), p, enc);
3794 else {
3795 size_t len;
3796 b = s;
3797 do s++; while (isdirsep(*s));
3798 len = s - b;
3799 p = buf + len;
3800 BUFCHECK(bdiff >= buflen);
3801 memset(buf, '/', len);
3802 rb_str_set_len(result, len);
3803 rb_enc_associate(result, fs_enc_check(result, fname));
3805 if (p > buf && p[-1] == '/')
3806 --p;
3807 else {
3808 rb_str_set_len(result, p-buf);
3809 BUFCHECK(bdiff + 1 >= buflen);
3810 *p = '/';
3813 rb_str_set_len(result, p-buf+1);
3814 BUFCHECK(bdiff + 1 >= buflen);
3815 p[1] = 0;
3816 root = skipprefix(buf, p+1, enc);
3818 b = s;
3819 while (*s) {
3820 switch (*s) {
3821 case '.':
3822 if (b == s++) { /* beginning of path element */
3823 switch (*s) {
3824 case '\0':
3825 b = s;
3826 break;
3827 case '.':
3828 if (*(s+1) == '\0' || isdirsep(*(s+1))) {
3829 /* We must go back to the parent */
3830 char *n;
3831 *p = '\0';
3832 if (!(n = strrdirsep(root, p, enc))) {
3833 *p = '/';
3835 else {
3836 p = n;
3838 b = ++s;
3840 #if USE_NTFS
3841 else {
3842 do ++s; while (istrailinggarbage(*s));
3844 #endif
3845 break;
3846 case '/':
3847 #if defined DOSISH || defined __CYGWIN__
3848 case '\\':
3849 #endif
3850 b = ++s;
3851 break;
3852 default:
3853 /* ordinary path element, beginning don't move */
3854 break;
3857 #if USE_NTFS
3858 else {
3859 --s;
3860 case ' ': {
3861 const char *e = s;
3862 while (s < fend && istrailinggarbage(*s)) s++;
3863 if (s >= fend) {
3864 s = e;
3865 goto endpath;
3869 #endif
3870 break;
3871 case '/':
3872 #if defined DOSISH || defined __CYGWIN__
3873 case '\\':
3874 #endif
3875 if (s > b) {
3876 WITH_ROOTDIFF(BUFCOPY(b, s-b));
3877 *p = '/';
3879 b = ++s;
3880 break;
3881 default:
3882 #ifdef __APPLE__
3884 int n = ignored_char_p(s, fend, enc);
3885 if (n) {
3886 if (s > b) {
3887 WITH_ROOTDIFF(BUFCOPY(b, s-b));
3888 *p = '\0';
3890 b = s += n;
3891 break;
3894 #endif
3895 Inc(s, fend, enc);
3896 break;
3900 if (s > b) {
3901 #if USE_NTFS
3902 # if USE_NTFS_ADS
3903 static const char prime[] = ":$DATA";
3904 enum {prime_len = sizeof(prime) -1};
3905 # endif
3906 endpath:
3907 # if USE_NTFS_ADS
3908 if (s > b + prime_len && strncasecmp(s - prime_len, prime, prime_len) == 0) {
3909 /* alias of stream */
3910 /* get rid of a bug of x64 VC++ */
3911 if (isADS(*(s - (prime_len+1)))) {
3912 s -= prime_len + 1; /* prime */
3914 else if (memchr(b, ':', s - prime_len - b)) {
3915 s -= prime_len; /* alternative */
3918 # endif
3919 #endif
3920 BUFCOPY(b, s-b);
3921 rb_str_set_len(result, p-buf);
3923 if (p == skiproot(buf, p + !!*p, enc) - 1) p++;
3925 #if USE_NTFS
3926 *p = '\0';
3927 if ((s = strrdirsep(b = buf, p, enc)) != 0 && !strpbrk(s, "*?")) {
3928 VALUE tmp, v;
3929 size_t len;
3930 int encidx;
3931 WCHAR *wstr;
3932 WIN32_FIND_DATAW wfd;
3933 HANDLE h;
3934 #ifdef __CYGWIN__
3935 #ifdef HAVE_CYGWIN_CONV_PATH
3936 char *w32buf = NULL;
3937 const int flags = CCP_POSIX_TO_WIN_A | CCP_RELATIVE;
3938 #else
3939 char w32buf[MAXPATHLEN];
3940 #endif
3941 const char *path;
3942 ssize_t bufsize;
3943 int lnk_added = 0, is_symlink = 0;
3944 struct stat st;
3945 p = (char *)s;
3946 len = strlen(p);
3947 if (lstat_without_gvl(buf, &st) == 0 && S_ISLNK(st.st_mode)) {
3948 is_symlink = 1;
3949 if (len > 4 && STRCASECMP(p + len - 4, ".lnk") != 0) {
3950 lnk_added = 1;
3953 path = *buf ? buf : "/";
3954 #ifdef HAVE_CYGWIN_CONV_PATH
3955 bufsize = cygwin_conv_path(flags, path, NULL, 0);
3956 if (bufsize > 0) {
3957 bufsize += len;
3958 if (lnk_added) bufsize += 4;
3959 w32buf = ALLOCA_N(char, bufsize);
3960 if (cygwin_conv_path(flags, path, w32buf, bufsize) == 0) {
3961 b = w32buf;
3964 #else
3965 bufsize = MAXPATHLEN;
3966 if (cygwin_conv_to_win32_path(path, w32buf) == 0) {
3967 b = w32buf;
3969 #endif
3970 if (is_symlink && b == w32buf) {
3971 *p = '\\';
3972 strlcat(w32buf, p, bufsize);
3973 if (lnk_added) {
3974 strlcat(w32buf, ".lnk", bufsize);
3977 else {
3978 lnk_added = 0;
3980 *p = '/';
3981 #endif
3982 rb_str_set_len(result, p - buf + strlen(p));
3983 encidx = ENCODING_GET(result);
3984 tmp = result;
3985 if (encidx != ENCINDEX_UTF_8 && rb_enc_str_coderange(result) != ENC_CODERANGE_7BIT) {
3986 tmp = rb_str_encode_ospath(result);
3988 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
3989 wstr = ALLOCV_N(WCHAR, v, len);
3990 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, wstr, len);
3991 if (tmp != result) rb_str_set_len(tmp, 0);
3992 h = FindFirstFileW(wstr, &wfd);
3993 ALLOCV_END(v);
3994 if (h != INVALID_HANDLE_VALUE) {
3995 size_t wlen;
3996 FindClose(h);
3997 len = lstrlenW(wfd.cFileName);
3998 #ifdef __CYGWIN__
3999 if (lnk_added && len > 4 &&
4000 wcscasecmp(wfd.cFileName + len - 4, L".lnk") == 0) {
4001 wfd.cFileName[len -= 4] = L'\0';
4003 #else
4004 p = (char *)s;
4005 #endif
4006 ++p;
4007 wlen = (int)len;
4008 len = WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, NULL, 0, NULL, NULL);
4009 if (tmp == result) {
4010 BUFCHECK(bdiff + len >= buflen);
4011 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, p, len + 1, NULL, NULL);
4013 else {
4014 rb_str_modify_expand(tmp, len);
4015 WideCharToMultiByte(CP_UTF8, 0, wfd.cFileName, wlen, RSTRING_PTR(tmp), len + 1, NULL, NULL);
4016 rb_str_cat_conv_enc_opts(result, bdiff, RSTRING_PTR(tmp), len,
4017 rb_utf8_encoding(), 0, Qnil);
4018 BUFINIT();
4019 rb_str_resize(tmp, 0);
4021 p += len;
4023 #ifdef __CYGWIN__
4024 else {
4025 p += strlen(p);
4027 #endif
4029 #endif
4031 rb_str_set_len(result, p - buf);
4032 rb_enc_check(fname, result);
4033 ENC_CODERANGE_CLEAR(result);
4034 return result;
4036 #endif /* _WIN32 */
4038 #define EXPAND_PATH_BUFFER() rb_usascii_str_new(0, MAXPATHLEN + 2)
4040 static VALUE
4041 str_shrink(VALUE str)
4043 rb_str_resize(str, RSTRING_LEN(str));
4044 return str;
4047 #define expand_path(fname, dname, abs_mode, long_name, result) \
4048 str_shrink(rb_file_expand_path_internal(fname, dname, abs_mode, long_name, result))
4050 #define check_expand_path_args(fname, dname) \
4051 (((fname) = rb_get_path(fname)), \
4052 (void)(NIL_P(dname) ? (dname) : ((dname) = rb_get_path(dname))))
4054 static VALUE
4055 file_expand_path_1(VALUE fname)
4057 return rb_file_expand_path_internal(fname, Qnil, 0, 0, EXPAND_PATH_BUFFER());
4060 VALUE
4061 rb_file_expand_path(VALUE fname, VALUE dname)
4063 check_expand_path_args(fname, dname);
4064 return expand_path(fname, dname, 0, 1, EXPAND_PATH_BUFFER());
4067 VALUE
4068 rb_file_expand_path_fast(VALUE fname, VALUE dname)
4070 return expand_path(fname, dname, 0, 0, EXPAND_PATH_BUFFER());
4073 VALUE
4074 rb_file_s_expand_path(int argc, const VALUE *argv)
4076 rb_check_arity(argc, 1, 2);
4077 return rb_file_expand_path(argv[0], argc > 1 ? argv[1] : Qnil);
4081 * call-seq:
4082 * File.expand_path(file_name [, dir_string] ) -> abs_file_name
4084 * Converts a pathname to an absolute pathname. Relative paths are
4085 * referenced from the current working directory of the process unless
4086 * +dir_string+ is given, in which case it will be used as the
4087 * starting point. The given pathname may start with a
4088 * ``<code>~</code>'', which expands to the process owner's home
4089 * directory (the environment variable +HOME+ must be set
4090 * correctly). ``<code>~</code><i>user</i>'' expands to the named
4091 * user's home directory.
4093 * File.expand_path("~oracle/bin") #=> "/home/oracle/bin"
4095 * A simple example of using +dir_string+ is as follows.
4096 * File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"
4098 * A more complex example which also resolves parent directory is as follows.
4099 * Suppose we are in bin/mygem and want the absolute path of lib/mygem.rb.
4101 * File.expand_path("../../lib/mygem.rb", __FILE__)
4102 * #=> ".../path/to/project/lib/mygem.rb"
4104 * So first it resolves the parent of __FILE__, that is bin/, then go to the
4105 * parent, the root of the project and appends +lib/mygem.rb+.
4108 static VALUE
4109 s_expand_path(int c, const VALUE * v, VALUE _)
4111 return rb_file_s_expand_path(c, v);
4114 VALUE
4115 rb_file_absolute_path(VALUE fname, VALUE dname)
4117 check_expand_path_args(fname, dname);
4118 return expand_path(fname, dname, 1, 1, EXPAND_PATH_BUFFER());
4121 VALUE
4122 rb_file_s_absolute_path(int argc, const VALUE *argv)
4124 rb_check_arity(argc, 1, 2);
4125 return rb_file_absolute_path(argv[0], argc > 1 ? argv[1] : Qnil);
4129 * call-seq:
4130 * File.absolute_path(file_name [, dir_string] ) -> abs_file_name
4132 * Converts a pathname to an absolute pathname. Relative paths are
4133 * referenced from the current working directory of the process unless
4134 * <i>dir_string</i> is given, in which case it will be used as the
4135 * starting point. If the given pathname starts with a ``<code>~</code>''
4136 * it is NOT expanded, it is treated as a normal directory name.
4138 * File.absolute_path("~oracle/bin") #=> "<relative_path>/~oracle/bin"
4141 static VALUE
4142 s_absolute_path(int c, const VALUE * v, VALUE _)
4144 return rb_file_s_absolute_path(c, v);
4148 * call-seq:
4149 * File.absolute_path?(file_name) -> true or false
4151 * Returns <code>true</code> if +file_name+ is an absolute path, and
4152 * <code>false</code> otherwise.
4154 * File.absolute_path?("c:/foo") #=> false (on Linux), true (on Windows)
4157 static VALUE
4158 s_absolute_path_p(VALUE klass, VALUE fname)
4160 VALUE path = rb_get_path(fname);
4162 if (!rb_is_absolute_path(RSTRING_PTR(path))) return Qfalse;
4163 return Qtrue;
4166 enum rb_realpath_mode {
4167 RB_REALPATH_CHECK,
4168 RB_REALPATH_DIR,
4169 RB_REALPATH_STRICT,
4170 RB_REALPATH_MODE_MAX
4173 static int
4174 realpath_rec(long *prefixlenp, VALUE *resolvedp, const char *unresolved, VALUE fallback,
4175 VALUE loopcheck, enum rb_realpath_mode mode, int last)
4177 const char *pend = unresolved + strlen(unresolved);
4178 rb_encoding *enc = rb_enc_get(*resolvedp);
4179 ID resolving;
4180 CONST_ID(resolving, "resolving");
4181 while (unresolved < pend) {
4182 const char *testname = unresolved;
4183 const char *unresolved_firstsep = rb_enc_path_next(unresolved, pend, enc);
4184 long testnamelen = unresolved_firstsep - unresolved;
4185 const char *unresolved_nextname = unresolved_firstsep;
4186 while (unresolved_nextname < pend && isdirsep(*unresolved_nextname))
4187 unresolved_nextname++;
4188 unresolved = unresolved_nextname;
4189 if (testnamelen == 1 && testname[0] == '.') {
4191 else if (testnamelen == 2 && testname[0] == '.' && testname[1] == '.') {
4192 if (*prefixlenp < RSTRING_LEN(*resolvedp)) {
4193 const char *resolved_str = RSTRING_PTR(*resolvedp);
4194 const char *resolved_names = resolved_str + *prefixlenp;
4195 const char *lastsep = strrdirsep(resolved_names, resolved_str + RSTRING_LEN(*resolvedp), enc);
4196 long len = lastsep ? lastsep - resolved_names : 0;
4197 rb_str_resize(*resolvedp, *prefixlenp + len);
4200 else {
4201 VALUE checkval;
4202 VALUE testpath = rb_str_dup(*resolvedp);
4203 if (*prefixlenp < RSTRING_LEN(testpath))
4204 rb_str_cat2(testpath, "/");
4205 #if defined(DOSISH_UNC) || defined(DOSISH_DRIVE_LETTER)
4206 if (*prefixlenp > 1 && *prefixlenp == RSTRING_LEN(testpath)) {
4207 const char *prefix = RSTRING_PTR(testpath);
4208 const char *last = rb_enc_left_char_head(prefix, prefix + *prefixlenp - 1, prefix + *prefixlenp, enc);
4209 if (!isdirsep(*last)) rb_str_cat2(testpath, "/");
4211 #endif
4212 rb_str_cat(testpath, testname, testnamelen);
4213 checkval = rb_hash_aref(loopcheck, testpath);
4214 if (!NIL_P(checkval)) {
4215 if (checkval == ID2SYM(resolving)) {
4216 if (mode == RB_REALPATH_CHECK) {
4217 errno = ELOOP;
4218 return -1;
4220 rb_syserr_fail_path(ELOOP, testpath);
4222 else {
4223 *resolvedp = rb_str_dup(checkval);
4226 else {
4227 struct stat sbuf;
4228 int ret;
4229 ret = lstat_without_gvl(RSTRING_PTR(testpath), &sbuf);
4230 if (ret == -1) {
4231 int e = errno;
4232 if (e == ENOENT && !NIL_P(fallback)) {
4233 if (stat_without_gvl(RSTRING_PTR(fallback), &sbuf) == 0) {
4234 rb_str_replace(*resolvedp, fallback);
4235 return 0;
4238 if (mode == RB_REALPATH_CHECK) return -1;
4239 if (e == ENOENT) {
4240 if (mode == RB_REALPATH_STRICT || !last || *unresolved_firstsep)
4241 rb_syserr_fail_path(e, testpath);
4242 *resolvedp = testpath;
4243 break;
4245 else {
4246 rb_syserr_fail_path(e, testpath);
4249 #ifdef HAVE_READLINK
4250 if (S_ISLNK(sbuf.st_mode)) {
4251 VALUE link;
4252 VALUE link_orig = Qnil;
4253 const char *link_prefix, *link_names;
4254 long link_prefixlen;
4255 rb_hash_aset(loopcheck, testpath, ID2SYM(resolving));
4256 link = rb_readlink(testpath, enc);
4257 link_prefix = RSTRING_PTR(link);
4258 link_names = skipprefixroot(link_prefix, link_prefix + RSTRING_LEN(link), rb_enc_get(link));
4259 link_prefixlen = link_names - link_prefix;
4260 if (link_prefixlen > 0) {
4261 rb_encoding *tmpenc, *linkenc = rb_enc_get(link);
4262 link_orig = link;
4263 link = rb_str_subseq(link, 0, link_prefixlen);
4264 tmpenc = fs_enc_check(*resolvedp, link);
4265 if (tmpenc != linkenc) link = rb_str_conv_enc(link, linkenc, tmpenc);
4266 *resolvedp = link;
4267 *prefixlenp = link_prefixlen;
4269 if (realpath_rec(prefixlenp, resolvedp, link_names, testpath,
4270 loopcheck, mode, !*unresolved_firstsep))
4271 return -1;
4272 RB_GC_GUARD(link_orig);
4273 rb_hash_aset(loopcheck, testpath, rb_str_dup_frozen(*resolvedp));
4275 else
4276 #endif
4278 VALUE s = rb_str_dup_frozen(testpath);
4279 rb_hash_aset(loopcheck, s, s);
4280 *resolvedp = testpath;
4285 return 0;
4288 static VALUE
4289 rb_check_realpath_emulate(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4291 long prefixlen;
4292 VALUE resolved;
4293 VALUE unresolved_path;
4294 VALUE loopcheck;
4295 VALUE curdir = Qnil;
4297 rb_encoding *enc;
4298 char *path_names = NULL, *basedir_names = NULL, *curdir_names = NULL;
4299 char *ptr, *prefixptr = NULL, *pend;
4300 long len;
4302 unresolved_path = rb_str_dup_frozen(path);
4304 if (!NIL_P(basedir)) {
4305 FilePathValue(basedir);
4306 basedir = TO_OSPATH(rb_str_dup_frozen(basedir));
4309 enc = rb_enc_get(unresolved_path);
4310 unresolved_path = TO_OSPATH(unresolved_path);
4311 RSTRING_GETMEM(unresolved_path, ptr, len);
4312 path_names = skipprefixroot(ptr, ptr + len, rb_enc_get(unresolved_path));
4313 if (ptr != path_names) {
4314 resolved = rb_str_subseq(unresolved_path, 0, path_names - ptr);
4315 goto root_found;
4318 if (!NIL_P(basedir)) {
4319 RSTRING_GETMEM(basedir, ptr, len);
4320 basedir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(basedir));
4321 if (ptr != basedir_names) {
4322 resolved = rb_str_subseq(basedir, 0, basedir_names - ptr);
4323 goto root_found;
4327 curdir = rb_dir_getwd_ospath();
4328 RSTRING_GETMEM(curdir, ptr, len);
4329 curdir_names = skipprefixroot(ptr, ptr + len, rb_enc_get(curdir));
4330 resolved = rb_str_subseq(curdir, 0, curdir_names - ptr);
4332 root_found:
4333 RSTRING_GETMEM(resolved, prefixptr, prefixlen);
4334 pend = prefixptr + prefixlen;
4335 ptr = chompdirsep(prefixptr, pend, enc);
4336 if (ptr < pend) {
4337 prefixlen = ++ptr - prefixptr;
4338 rb_str_set_len(resolved, prefixlen);
4340 #ifdef FILE_ALT_SEPARATOR
4341 while (prefixptr < ptr) {
4342 if (*prefixptr == FILE_ALT_SEPARATOR) {
4343 *prefixptr = '/';
4345 Inc(prefixptr, pend, enc);
4347 #endif
4349 switch (rb_enc_to_index(enc)) {
4350 case ENCINDEX_ASCII:
4351 case ENCINDEX_US_ASCII:
4352 rb_enc_associate_index(resolved, rb_filesystem_encindex());
4355 loopcheck = rb_hash_new();
4356 if (curdir_names) {
4357 if (realpath_rec(&prefixlen, &resolved, curdir_names, Qnil, loopcheck, mode, 0))
4358 return Qnil;
4360 if (basedir_names) {
4361 if (realpath_rec(&prefixlen, &resolved, basedir_names, Qnil, loopcheck, mode, 0))
4362 return Qnil;
4364 if (realpath_rec(&prefixlen, &resolved, path_names, Qnil, loopcheck, mode, 1))
4365 return Qnil;
4367 if (origenc && origenc != rb_enc_get(resolved)) {
4368 if (rb_enc_str_asciionly_p(resolved)) {
4369 rb_enc_associate(resolved, origenc);
4371 else {
4372 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4376 RB_GC_GUARD(unresolved_path);
4377 RB_GC_GUARD(curdir);
4378 return resolved;
4381 static VALUE rb_file_join(VALUE ary);
4383 #ifndef HAVE_REALPATH
4384 static VALUE
4385 rb_check_realpath_emulate_try(VALUE arg)
4387 VALUE *args = (VALUE *)arg;
4388 return rb_check_realpath_emulate(args[0], args[1], (rb_encoding *)args[2], RB_REALPATH_CHECK);
4391 static VALUE
4392 rb_check_realpath_emulate_rescue(VALUE arg, VALUE exc)
4394 return Qnil;
4396 #endif /* HAVE_REALPATH */
4398 static VALUE
4399 rb_check_realpath_internal(VALUE basedir, VALUE path, rb_encoding *origenc, enum rb_realpath_mode mode)
4401 #ifdef HAVE_REALPATH
4402 VALUE unresolved_path;
4403 char *resolved_ptr = NULL;
4404 VALUE resolved;
4406 if (mode == RB_REALPATH_DIR) {
4407 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4410 unresolved_path = rb_str_dup_frozen(path);
4411 if (*RSTRING_PTR(unresolved_path) != '/' && !NIL_P(basedir)) {
4412 unresolved_path = rb_file_join(rb_assoc_new(basedir, unresolved_path));
4414 if (origenc) unresolved_path = TO_OSPATH(unresolved_path);
4416 if ((resolved_ptr = realpath(RSTRING_PTR(unresolved_path), NULL)) == NULL) {
4417 /* glibc realpath(3) does not allow /path/to/file.rb/../other_file.rb,
4418 returning ENOTDIR in that case.
4419 glibc realpath(3) can also return ENOENT for paths that exist,
4420 such as /dev/fd/5.
4421 Fallback to the emulated approach in either of those cases. */
4422 if (errno == ENOTDIR ||
4423 (errno == ENOENT && rb_file_exist_p(0, unresolved_path))) {
4424 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4427 if (mode == RB_REALPATH_CHECK) {
4428 return Qnil;
4430 rb_sys_fail_path(unresolved_path);
4432 resolved = ospath_new(resolved_ptr, strlen(resolved_ptr), rb_filesystem_encoding());
4433 free(resolved_ptr);
4435 # if !defined(__LINUX__) && !defined(__APPLE__)
4436 /* As `resolved` is a String in the filesystem encoding, no
4437 * conversion is needed */
4438 struct stat st;
4439 if (stat_without_gvl(RSTRING_PTR(resolved), &st) < 0) {
4440 if (mode == RB_REALPATH_CHECK) {
4441 return Qnil;
4443 rb_sys_fail_path(unresolved_path);
4445 # endif
4447 if (origenc && origenc != rb_enc_get(resolved)) {
4448 if (!rb_enc_str_asciionly_p(resolved)) {
4449 resolved = rb_str_conv_enc(resolved, NULL, origenc);
4451 rb_enc_associate(resolved, origenc);
4454 if (rb_enc_str_coderange(resolved) == ENC_CODERANGE_BROKEN) {
4455 rb_enc_associate(resolved, rb_filesystem_encoding());
4456 if (rb_enc_str_coderange(resolved) == ENC_CODERANGE_BROKEN) {
4457 rb_enc_associate(resolved, rb_ascii8bit_encoding());
4461 RB_GC_GUARD(unresolved_path);
4462 return resolved;
4463 #else
4464 if (mode == RB_REALPATH_CHECK) {
4465 VALUE arg[3];
4466 arg[0] = basedir;
4467 arg[1] = path;
4468 arg[2] = (VALUE)origenc;
4470 return rb_rescue(rb_check_realpath_emulate_try, (VALUE)arg,
4471 rb_check_realpath_emulate_rescue, Qnil);
4473 else {
4474 return rb_check_realpath_emulate(basedir, path, origenc, mode);
4476 #endif /* HAVE_REALPATH */
4479 VALUE
4480 rb_realpath_internal(VALUE basedir, VALUE path, int strict)
4482 const enum rb_realpath_mode mode =
4483 strict ? RB_REALPATH_STRICT : RB_REALPATH_DIR;
4484 return rb_check_realpath_internal(basedir, path, rb_enc_get(path), mode);
4487 VALUE
4488 rb_check_realpath(VALUE basedir, VALUE path, rb_encoding *enc)
4490 return rb_check_realpath_internal(basedir, path, enc, RB_REALPATH_CHECK);
4494 * call-seq:
4495 * File.realpath(pathname [, dir_string]) -> real_pathname
4497 * Returns the real (absolute) pathname of _pathname_ in the actual
4498 * filesystem not containing symlinks or useless dots.
4500 * If _dir_string_ is given, it is used as a base directory
4501 * for interpreting relative pathname instead of the current directory.
4503 * All components of the pathname must exist when this method is
4504 * called.
4506 static VALUE
4507 rb_file_s_realpath(int argc, VALUE *argv, VALUE klass)
4509 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4510 VALUE path = argv[0];
4511 FilePathValue(path);
4512 return rb_realpath_internal(basedir, path, 1);
4516 * call-seq:
4517 * File.realdirpath(pathname [, dir_string]) -> real_pathname
4519 * Returns the real (absolute) pathname of _pathname_ in the actual filesystem.
4520 * The real pathname doesn't contain symlinks or useless dots.
4522 * If _dir_string_ is given, it is used as a base directory
4523 * for interpreting relative pathname instead of the current directory.
4525 * The last component of the real pathname can be nonexistent.
4527 static VALUE
4528 rb_file_s_realdirpath(int argc, VALUE *argv, VALUE klass)
4530 VALUE basedir = (rb_check_arity(argc, 1, 2) > 1) ? argv[1] : Qnil;
4531 VALUE path = argv[0];
4532 FilePathValue(path);
4533 return rb_realpath_internal(basedir, path, 0);
4536 static size_t
4537 rmext(const char *p, long l0, long l1, const char *e, long l2, rb_encoding *enc)
4539 int len1, len2;
4540 unsigned int c;
4541 const char *s, *last;
4543 if (!e || !l2) return 0;
4545 c = rb_enc_codepoint_len(e, e + l2, &len1, enc);
4546 if (rb_enc_ascget(e + len1, e + l2, &len2, enc) == '*' && len1 + len2 == l2) {
4547 if (c == '.') return l0;
4548 s = p;
4549 e = p + l1;
4550 last = e;
4551 while (s < e) {
4552 if (rb_enc_codepoint_len(s, e, &len1, enc) == c) last = s;
4553 s += len1;
4555 return last - p;
4557 if (l1 < l2) return l1;
4559 s = p+l1-l2;
4560 if (rb_enc_left_char_head(p, s, p+l1, enc) != s) return 0;
4561 #if CASEFOLD_FILESYSTEM
4562 #define fncomp strncasecmp
4563 #else
4564 #define fncomp strncmp
4565 #endif
4566 if (fncomp(s, e, l2) == 0) {
4567 return l1-l2;
4569 return 0;
4572 const char *
4573 ruby_enc_find_basename(const char *name, long *baselen, long *alllen, rb_encoding *enc)
4575 const char *p, *q, *e, *end;
4576 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4577 const char *root;
4578 #endif
4579 long f = 0, n = -1;
4581 end = name + (alllen ? (size_t)*alllen : strlen(name));
4582 name = skipprefix(name, end, enc);
4583 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4584 root = name;
4585 #endif
4586 while (isdirsep(*name))
4587 name++;
4588 if (!*name) {
4589 p = name - 1;
4590 f = 1;
4591 #if defined DOSISH_DRIVE_LETTER || defined DOSISH_UNC
4592 if (name != root) {
4593 /* has slashes */
4595 #ifdef DOSISH_DRIVE_LETTER
4596 else if (*p == ':') {
4597 p++;
4598 f = 0;
4600 #endif
4601 #ifdef DOSISH_UNC
4602 else {
4603 p = "/";
4605 #endif
4606 #endif
4608 else {
4609 if (!(p = strrdirsep(name, end, enc))) {
4610 p = name;
4612 else {
4613 while (isdirsep(*p)) p++; /* skip last / */
4615 #if USE_NTFS
4616 n = ntfs_tail(p, end, enc) - p;
4617 #else
4618 n = chompdirsep(p, end, enc) - p;
4619 #endif
4620 for (q = p; q - p < n && *q == '.'; q++);
4621 for (e = 0; q - p < n; Inc(q, end, enc)) {
4622 if (*q == '.') e = q;
4624 if (e) f = e - p;
4625 else f = n;
4628 if (baselen)
4629 *baselen = f;
4630 if (alllen)
4631 *alllen = n;
4632 return p;
4636 * call-seq:
4637 * File.basename(file_name [, suffix] ) -> base_name
4639 * Returns the last component of the filename given in
4640 * <i>file_name</i> (after first stripping trailing separators),
4641 * which can be formed using both File::SEPARATOR and
4642 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4643 * not <code>nil</code>. If <i>suffix</i> is given and present at the
4644 * end of <i>file_name</i>, it is removed. If <i>suffix</i> is ".*",
4645 * any extension will be removed.
4647 * File.basename("/home/gumby/work/ruby.rb") #=> "ruby.rb"
4648 * File.basename("/home/gumby/work/ruby.rb", ".rb") #=> "ruby"
4649 * File.basename("/home/gumby/work/ruby.rb", ".*") #=> "ruby"
4652 static VALUE
4653 rb_file_s_basename(int argc, VALUE *argv, VALUE _)
4655 VALUE fname, fext, basename;
4656 const char *name, *p;
4657 long f, n;
4658 rb_encoding *enc;
4660 fext = Qnil;
4661 if (rb_check_arity(argc, 1, 2) == 2) {
4662 fext = argv[1];
4663 StringValue(fext);
4664 enc = check_path_encoding(fext);
4666 fname = argv[0];
4667 FilePathStringValue(fname);
4668 if (NIL_P(fext) || !(enc = rb_enc_compatible(fname, fext))) {
4669 enc = rb_enc_get(fname);
4670 fext = Qnil;
4672 if ((n = RSTRING_LEN(fname)) == 0 || !*(name = RSTRING_PTR(fname)))
4673 return rb_str_new_shared(fname);
4675 p = ruby_enc_find_basename(name, &f, &n, enc);
4676 if (n >= 0) {
4677 if (NIL_P(fext)) {
4678 f = n;
4680 else {
4681 const char *fp;
4682 fp = StringValueCStr(fext);
4683 if (!(f = rmext(p, f, n, fp, RSTRING_LEN(fext), enc))) {
4684 f = n;
4686 RB_GC_GUARD(fext);
4688 if (f == RSTRING_LEN(fname)) return rb_str_new_shared(fname);
4691 basename = rb_str_new(p, f);
4692 rb_enc_copy(basename, fname);
4693 return basename;
4696 static VALUE rb_file_dirname_n(VALUE fname, int n);
4699 * call-seq:
4700 * File.dirname(file_name, level = 1) -> dir_name
4702 * Returns all components of the filename given in <i>file_name</i>
4703 * except the last one (after first stripping trailing separators).
4704 * The filename can be formed using both File::SEPARATOR and
4705 * File::ALT_SEPARATOR as the separator when File::ALT_SEPARATOR is
4706 * not <code>nil</code>.
4708 * File.dirname("/home/gumby/work/ruby.rb") #=> "/home/gumby/work"
4710 * If +level+ is given, removes the last +level+ components, not only
4711 * one.
4713 * File.dirname("/home/gumby/work/ruby.rb", 2) #=> "/home/gumby"
4714 * File.dirname("/home/gumby/work/ruby.rb", 4) #=> "/"
4717 static VALUE
4718 rb_file_s_dirname(int argc, VALUE *argv, VALUE klass)
4720 int n = 1;
4721 if ((argc = rb_check_arity(argc, 1, 2)) > 1) {
4722 n = NUM2INT(argv[1]);
4724 return rb_file_dirname_n(argv[0], n);
4727 VALUE
4728 rb_file_dirname(VALUE fname)
4730 return rb_file_dirname_n(fname, 1);
4733 static VALUE
4734 rb_file_dirname_n(VALUE fname, int n)
4736 const char *name, *root, *p, *end;
4737 VALUE dirname;
4738 rb_encoding *enc;
4739 VALUE sepsv = 0;
4740 const char **seps;
4742 if (n < 0) rb_raise(rb_eArgError, "negative level: %d", n);
4743 FilePathStringValue(fname);
4744 name = StringValueCStr(fname);
4745 end = name + RSTRING_LEN(fname);
4746 enc = rb_enc_get(fname);
4747 root = skiproot(name, end, enc);
4748 #ifdef DOSISH_UNC
4749 if (root > name + 1 && isdirsep(*name))
4750 root = skipprefix(name = root - 2, end, enc);
4751 #else
4752 if (root > name + 1)
4753 name = root - 1;
4754 #endif
4755 if (n > (end - root + 1) / 2) {
4756 p = root;
4758 else {
4759 int i;
4760 switch (n) {
4761 case 0:
4762 p = end;
4763 break;
4764 case 1:
4765 if (!(p = strrdirsep(root, end, enc))) p = root;
4766 break;
4767 default:
4768 seps = ALLOCV_N(const char *, sepsv, n);
4769 for (i = 0; i < n; ++i) seps[i] = root;
4770 i = 0;
4771 for (p = root; p < end; ) {
4772 if (isdirsep(*p)) {
4773 const char *tmp = p++;
4774 while (p < end && isdirsep(*p)) p++;
4775 if (p >= end) break;
4776 seps[i++] = tmp;
4777 if (i == n) i = 0;
4779 else {
4780 Inc(p, end, enc);
4783 p = seps[i];
4784 ALLOCV_END(sepsv);
4785 break;
4788 if (p == name)
4789 return rb_usascii_str_new2(".");
4790 #ifdef DOSISH_DRIVE_LETTER
4791 if (has_drive_letter(name) && isdirsep(*(name + 2))) {
4792 const char *top = skiproot(name + 2, end, enc);
4793 dirname = rb_str_new(name, 3);
4794 rb_str_cat(dirname, top, p - top);
4796 else
4797 #endif
4798 dirname = rb_str_new(name, p - name);
4799 #ifdef DOSISH_DRIVE_LETTER
4800 if (has_drive_letter(name) && root == name + 2 && p - name == 2)
4801 rb_str_cat(dirname, ".", 1);
4802 #endif
4803 rb_enc_copy(dirname, fname);
4804 return dirname;
4808 * accept a String, and return the pointer of the extension.
4809 * if len is passed, set the length of extension to it.
4810 * returned pointer is in ``name'' or NULL.
4811 * returns *len
4812 * no dot NULL 0
4813 * dotfile top 0
4814 * end with dot dot 1
4815 * .ext dot len of .ext
4816 * .ext:stream dot len of .ext without :stream (NT only)
4819 const char *
4820 ruby_enc_find_extname(const char *name, long *len, rb_encoding *enc)
4822 const char *p, *e, *end = name + (len ? *len : (long)strlen(name));
4824 p = strrdirsep(name, end, enc); /* get the last path component */
4825 if (!p)
4826 p = name;
4827 else
4828 do name = ++p; while (isdirsep(*p));
4830 e = 0;
4831 while (*p && *p == '.') p++;
4832 while (*p) {
4833 if (*p == '.' || istrailinggarbage(*p)) {
4834 #if USE_NTFS
4835 const char *last = p++, *dot = last;
4836 while (istrailinggarbage(*p)) {
4837 if (*p == '.') dot = p;
4838 p++;
4840 if (!*p || isADS(*p)) {
4841 p = last;
4842 break;
4844 if (*last == '.' || dot > last) e = dot;
4845 continue;
4846 #else
4847 e = p; /* get the last dot of the last component */
4848 #endif
4850 #if USE_NTFS
4851 else if (isADS(*p)) {
4852 break;
4854 #endif
4855 else if (isdirsep(*p))
4856 break;
4857 Inc(p, end, enc);
4860 if (len) {
4861 /* no dot, or the only dot is first or end? */
4862 if (!e || e == name)
4863 *len = 0;
4864 else if (e+1 == p)
4865 *len = 1;
4866 else
4867 *len = p - e;
4869 return e;
4873 * call-seq:
4874 * File.extname(path) -> string
4876 * Returns the extension (the portion of file name in +path+
4877 * starting from the last period).
4879 * If +path+ is a dotfile, or starts with a period, then the starting
4880 * dot is not dealt with the start of the extension.
4882 * An empty string will also be returned when the period is the last character
4883 * in +path+.
4885 * On Windows, trailing dots are truncated.
4887 * File.extname("test.rb") #=> ".rb"
4888 * File.extname("a/b/d/test.rb") #=> ".rb"
4889 * File.extname(".a/b/d/test.rb") #=> ".rb"
4890 * File.extname("foo.") #=> "" on Windows
4891 * File.extname("foo.") #=> "." on non-Windows
4892 * File.extname("test") #=> ""
4893 * File.extname(".profile") #=> ""
4894 * File.extname(".profile.sh") #=> ".sh"
4898 static VALUE
4899 rb_file_s_extname(VALUE klass, VALUE fname)
4901 const char *name, *e;
4902 long len;
4903 VALUE extname;
4905 FilePathStringValue(fname);
4906 name = StringValueCStr(fname);
4907 len = RSTRING_LEN(fname);
4908 e = ruby_enc_find_extname(name, &len, rb_enc_get(fname));
4909 if (len < 1)
4910 return rb_str_new(0, 0);
4911 extname = rb_str_subseq(fname, e - name, len); /* keep the dot, too! */
4912 return extname;
4916 * call-seq:
4917 * File.path(path) -> string
4919 * Returns the string representation of the path
4921 * File.path("/dev/null") #=> "/dev/null"
4922 * File.path(Pathname.new("/tmp")) #=> "/tmp"
4926 static VALUE
4927 rb_file_s_path(VALUE klass, VALUE fname)
4929 return rb_get_path(fname);
4933 * call-seq:
4934 * File.split(file_name) -> array
4936 * Splits the given string into a directory and a file component and
4937 * returns them in a two-element array. See also File::dirname and
4938 * File::basename.
4940 * File.split("/home/gumby/.profile") #=> ["/home/gumby", ".profile"]
4943 static VALUE
4944 rb_file_s_split(VALUE klass, VALUE path)
4946 FilePathStringValue(path); /* get rid of converting twice */
4947 return rb_assoc_new(rb_file_dirname(path), rb_file_s_basename(1,&path,Qundef));
4950 static VALUE
4951 file_inspect_join(VALUE ary, VALUE arg, int recur)
4953 if (recur || ary == arg) rb_raise(rb_eArgError, "recursive array");
4954 return rb_file_join(arg);
4957 static VALUE
4958 rb_file_join(VALUE ary)
4960 long len, i;
4961 VALUE result, tmp;
4962 const char *name, *tail;
4963 int checked = TRUE;
4964 rb_encoding *enc;
4966 if (RARRAY_LEN(ary) == 0) return rb_str_new(0, 0);
4968 len = 1;
4969 for (i=0; i<RARRAY_LEN(ary); i++) {
4970 tmp = RARRAY_AREF(ary, i);
4971 if (RB_TYPE_P(tmp, T_STRING)) {
4972 check_path_encoding(tmp);
4973 len += RSTRING_LEN(tmp);
4975 else {
4976 len += 10;
4979 len += RARRAY_LEN(ary) - 1;
4980 result = rb_str_buf_new(len);
4981 RBASIC_CLEAR_CLASS(result);
4982 for (i=0; i<RARRAY_LEN(ary); i++) {
4983 tmp = RARRAY_AREF(ary, i);
4984 switch (OBJ_BUILTIN_TYPE(tmp)) {
4985 case T_STRING:
4986 if (!checked) check_path_encoding(tmp);
4987 StringValueCStr(tmp);
4988 break;
4989 case T_ARRAY:
4990 if (ary == tmp) {
4991 rb_raise(rb_eArgError, "recursive array");
4993 else {
4994 tmp = rb_exec_recursive(file_inspect_join, ary, tmp);
4996 break;
4997 default:
4998 FilePathStringValue(tmp);
4999 checked = FALSE;
5001 RSTRING_GETMEM(result, name, len);
5002 if (i == 0) {
5003 rb_enc_copy(result, tmp);
5005 else {
5006 tail = chompdirsep(name, name + len, rb_enc_get(result));
5007 if (RSTRING_PTR(tmp) && isdirsep(RSTRING_PTR(tmp)[0])) {
5008 rb_str_set_len(result, tail - name);
5010 else if (!*tail) {
5011 rb_str_cat(result, "/", 1);
5014 enc = fs_enc_check(result, tmp);
5015 rb_str_buf_append(result, tmp);
5016 rb_enc_associate(result, enc);
5018 RBASIC_SET_CLASS_RAW(result, rb_cString);
5020 return result;
5024 * call-seq:
5025 * File.join(string, ...) -> string
5027 * Returns a new string formed by joining the strings using
5028 * <code>"/"</code>.
5030 * File.join("usr", "mail", "gumby") #=> "usr/mail/gumby"
5034 static VALUE
5035 rb_file_s_join(VALUE klass, VALUE args)
5037 return rb_file_join(args);
5040 #if defined(HAVE_TRUNCATE) || defined(HAVE_CHSIZE)
5041 struct truncate_arg {
5042 const char *path;
5043 #if defined(HAVE_TRUNCATE)
5044 #define NUM2POS(n) NUM2OFFT(n)
5045 off_t pos;
5046 #else
5047 #define NUM2POS(n) NUM2LONG(n)
5048 long pos;
5049 #endif
5052 static void *
5053 nogvl_truncate(void *ptr)
5055 struct truncate_arg *ta = ptr;
5056 #ifdef HAVE_TRUNCATE
5057 return (void *)(VALUE)truncate(ta->path, ta->pos);
5058 #else /* defined(HAVE_CHSIZE) */
5060 int tmpfd = rb_cloexec_open(ta->path, 0, 0);
5062 if (tmpfd < 0)
5063 return (void *)-1;
5064 rb_update_max_fd(tmpfd);
5065 if (chsize(tmpfd, ta->pos) < 0) {
5066 int e = errno;
5067 close(tmpfd);
5068 errno = e;
5069 return (void *)-1;
5071 close(tmpfd);
5072 return 0;
5074 #endif
5078 * call-seq:
5079 * File.truncate(file_name, integer) -> 0
5081 * Truncates the file <i>file_name</i> to be at most <i>integer</i>
5082 * bytes long. Not available on all platforms.
5084 * f = File.new("out", "w")
5085 * f.write("1234567890") #=> 10
5086 * f.close #=> nil
5087 * File.truncate("out", 5) #=> 0
5088 * File.size("out") #=> 5
5092 static VALUE
5093 rb_file_s_truncate(VALUE klass, VALUE path, VALUE len)
5095 struct truncate_arg ta;
5096 int r;
5098 ta.pos = NUM2POS(len);
5099 FilePathValue(path);
5100 path = rb_str_encode_ospath(path);
5101 ta.path = StringValueCStr(path);
5103 r = (int)(VALUE)rb_thread_call_without_gvl(nogvl_truncate, &ta,
5104 RUBY_UBF_IO, NULL);
5105 if (r < 0)
5106 rb_sys_fail_path(path);
5107 return INT2FIX(0);
5108 #undef NUM2POS
5110 #else
5111 #define rb_file_s_truncate rb_f_notimplement
5112 #endif
5114 #if defined(HAVE_FTRUNCATE) || defined(HAVE_CHSIZE)
5115 struct ftruncate_arg {
5116 int fd;
5117 #if defined(HAVE_FTRUNCATE)
5118 #define NUM2POS(n) NUM2OFFT(n)
5119 off_t pos;
5120 #else
5121 #define NUM2POS(n) NUM2LONG(n)
5122 long pos;
5123 #endif
5126 static VALUE
5127 nogvl_ftruncate(void *ptr)
5129 struct ftruncate_arg *fa = ptr;
5131 #ifdef HAVE_FTRUNCATE
5132 return (VALUE)ftruncate(fa->fd, fa->pos);
5133 #else /* defined(HAVE_CHSIZE) */
5134 return (VALUE)chsize(fa->fd, fa->pos);
5135 #endif
5139 * call-seq:
5140 * file.truncate(integer) -> 0
5142 * Truncates <i>file</i> to at most <i>integer</i> bytes. The file
5143 * must be opened for writing. Not available on all platforms.
5145 * f = File.new("out", "w")
5146 * f.syswrite("1234567890") #=> 10
5147 * f.truncate(5) #=> 0
5148 * f.close() #=> nil
5149 * File.size("out") #=> 5
5152 static VALUE
5153 rb_file_truncate(VALUE obj, VALUE len)
5155 rb_io_t *fptr;
5156 struct ftruncate_arg fa;
5158 fa.pos = NUM2POS(len);
5159 GetOpenFile(obj, fptr);
5160 if (!(fptr->mode & FMODE_WRITABLE)) {
5161 rb_raise(rb_eIOError, "not opened for writing");
5163 rb_io_flush_raw(obj, 0);
5164 fa.fd = fptr->fd;
5165 if ((int)rb_thread_io_blocking_region(nogvl_ftruncate, &fa, fa.fd) < 0) {
5166 rb_sys_fail_path(fptr->pathv);
5168 return INT2FIX(0);
5169 #undef NUM2POS
5171 #else
5172 #define rb_file_truncate rb_f_notimplement
5173 #endif
5175 # ifndef LOCK_SH
5176 # define LOCK_SH 1
5177 # endif
5178 # ifndef LOCK_EX
5179 # define LOCK_EX 2
5180 # endif
5181 # ifndef LOCK_NB
5182 # define LOCK_NB 4
5183 # endif
5184 # ifndef LOCK_UN
5185 # define LOCK_UN 8
5186 # endif
5188 #ifdef __CYGWIN__
5189 #include <winerror.h>
5190 #endif
5192 static VALUE
5193 rb_thread_flock(void *data)
5195 #ifdef __CYGWIN__
5196 int old_errno = errno;
5197 #endif
5198 int *op = data, ret = flock(op[0], op[1]);
5200 #ifdef __CYGWIN__
5201 if (GetLastError() == ERROR_NOT_LOCKED) {
5202 ret = 0;
5203 errno = old_errno;
5205 #endif
5206 return (VALUE)ret;
5210 * call-seq:
5211 * file.flock(locking_constant) -> 0 or false
5213 * Locks or unlocks a file according to <i>locking_constant</i> (a
5214 * logical <em>or</em> of the values in the table below).
5215 * Returns <code>false</code> if File::LOCK_NB is specified and the
5216 * operation would otherwise have blocked. Not available on all
5217 * platforms.
5219 * Locking constants (in class File):
5221 * LOCK_EX | Exclusive lock. Only one process may hold an
5222 * | exclusive lock for a given file at a time.
5223 * ----------+------------------------------------------------
5224 * LOCK_NB | Don't block when locking. May be combined
5225 * | with other lock options using logical or.
5226 * ----------+------------------------------------------------
5227 * LOCK_SH | Shared lock. Multiple processes may each hold a
5228 * | shared lock for a given file at the same time.
5229 * ----------+------------------------------------------------
5230 * LOCK_UN | Unlock.
5232 * Example:
5234 * # update a counter using write lock
5235 * # don't use "w" because it truncates the file before lock.
5236 * File.open("counter", File::RDWR|File::CREAT, 0644) {|f|
5237 * f.flock(File::LOCK_EX)
5238 * value = f.read.to_i + 1
5239 * f.rewind
5240 * f.write("#{value}\n")
5241 * f.flush
5242 * f.truncate(f.pos)
5245 * # read the counter using read lock
5246 * File.open("counter", "r") {|f|
5247 * f.flock(File::LOCK_SH)
5248 * p f.read
5253 static VALUE
5254 rb_file_flock(VALUE obj, VALUE operation)
5256 rb_io_t *fptr;
5257 int op[2], op1;
5258 struct timeval time;
5260 op[1] = op1 = NUM2INT(operation);
5261 GetOpenFile(obj, fptr);
5262 op[0] = fptr->fd;
5264 if (fptr->mode & FMODE_WRITABLE) {
5265 rb_io_flush_raw(obj, 0);
5267 while ((int)rb_thread_io_blocking_region(rb_thread_flock, op, fptr->fd) < 0) {
5268 int e = errno;
5269 switch (e) {
5270 case EAGAIN:
5271 case EACCES:
5272 #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5273 case EWOULDBLOCK:
5274 #endif
5275 if (op1 & LOCK_NB) return Qfalse;
5277 time.tv_sec = 0;
5278 time.tv_usec = 100 * 1000; /* 0.1 sec */
5279 rb_thread_wait_for(time);
5280 rb_io_check_closed(fptr);
5281 continue;
5283 case EINTR:
5284 #if defined(ERESTART)
5285 case ERESTART:
5286 #endif
5287 break;
5289 default:
5290 rb_syserr_fail_path(e, fptr->pathv);
5293 return INT2FIX(0);
5296 static void
5297 test_check(int n, int argc, VALUE *argv)
5299 int i;
5301 n+=1;
5302 rb_check_arity(argc, n, n);
5303 for (i=1; i<n; i++) {
5304 if (!RB_TYPE_P(argv[i], T_FILE)) {
5305 FilePathValue(argv[i]);
5310 #define CHECK(n) test_check((n), argc, argv)
5313 * call-seq:
5314 * test(cmd, file1 [, file2] ) -> obj
5316 * Uses the character +cmd+ to perform various tests on +file1+ (first
5317 * table below) or on +file1+ and +file2+ (second table).
5319 * File tests on a single file:
5321 * Cmd Returns Meaning
5322 * "A" | Time | Last access time for file1
5323 * "b" | boolean | True if file1 is a block device
5324 * "c" | boolean | True if file1 is a character device
5325 * "C" | Time | Last change time for file1
5326 * "d" | boolean | True if file1 exists and is a directory
5327 * "e" | boolean | True if file1 exists
5328 * "f" | boolean | True if file1 exists and is a regular file
5329 * "g" | boolean | True if file1 has the \CF{setgid} bit
5330 * | | set (false under NT)
5331 * "G" | boolean | True if file1 exists and has a group
5332 * | | ownership equal to the caller's group
5333 * "k" | boolean | True if file1 exists and has the sticky bit set
5334 * "l" | boolean | True if file1 exists and is a symbolic link
5335 * "M" | Time | Last modification time for file1
5336 * "o" | boolean | True if file1 exists and is owned by
5337 * | | the caller's effective uid
5338 * "O" | boolean | True if file1 exists and is owned by
5339 * | | the caller's real uid
5340 * "p" | boolean | True if file1 exists and is a fifo
5341 * "r" | boolean | True if file1 is readable by the effective
5342 * | | uid/gid of the caller
5343 * "R" | boolean | True if file is readable by the real
5344 * | | uid/gid of the caller
5345 * "s" | int/nil | If file1 has nonzero size, return the size,
5346 * | | otherwise return nil
5347 * "S" | boolean | True if file1 exists and is a socket
5348 * "u" | boolean | True if file1 has the setuid bit set
5349 * "w" | boolean | True if file1 exists and is writable by
5350 * | | the effective uid/gid
5351 * "W" | boolean | True if file1 exists and is writable by
5352 * | | the real uid/gid
5353 * "x" | boolean | True if file1 exists and is executable by
5354 * | | the effective uid/gid
5355 * "X" | boolean | True if file1 exists and is executable by
5356 * | | the real uid/gid
5357 * "z" | boolean | True if file1 exists and has a zero length
5359 * Tests that take two files:
5361 * "-" | boolean | True if file1 and file2 are identical
5362 * "=" | boolean | True if the modification times of file1
5363 * | | and file2 are equal
5364 * "<" | boolean | True if the modification time of file1
5365 * | | is prior to that of file2
5366 * ">" | boolean | True if the modification time of file1
5367 * | | is after that of file2
5370 static VALUE
5371 rb_f_test(int argc, VALUE *argv, VALUE _)
5373 int cmd;
5375 if (argc == 0) rb_check_arity(argc, 2, 3);
5376 cmd = NUM2CHR(argv[0]);
5377 if (cmd == 0) {
5378 goto unknown;
5380 if (strchr("bcdefgGkloOprRsSuwWxXz", cmd)) {
5381 CHECK(1);
5382 switch (cmd) {
5383 case 'b':
5384 return rb_file_blockdev_p(0, argv[1]);
5386 case 'c':
5387 return rb_file_chardev_p(0, argv[1]);
5389 case 'd':
5390 return rb_file_directory_p(0, argv[1]);
5392 case 'e':
5393 return rb_file_exist_p(0, argv[1]);
5395 case 'f':
5396 return rb_file_file_p(0, argv[1]);
5398 case 'g':
5399 return rb_file_sgid_p(0, argv[1]);
5401 case 'G':
5402 return rb_file_grpowned_p(0, argv[1]);
5404 case 'k':
5405 return rb_file_sticky_p(0, argv[1]);
5407 case 'l':
5408 return rb_file_symlink_p(0, argv[1]);
5410 case 'o':
5411 return rb_file_owned_p(0, argv[1]);
5413 case 'O':
5414 return rb_file_rowned_p(0, argv[1]);
5416 case 'p':
5417 return rb_file_pipe_p(0, argv[1]);
5419 case 'r':
5420 return rb_file_readable_p(0, argv[1]);
5422 case 'R':
5423 return rb_file_readable_real_p(0, argv[1]);
5425 case 's':
5426 return rb_file_size_p(0, argv[1]);
5428 case 'S':
5429 return rb_file_socket_p(0, argv[1]);
5431 case 'u':
5432 return rb_file_suid_p(0, argv[1]);
5434 case 'w':
5435 return rb_file_writable_p(0, argv[1]);
5437 case 'W':
5438 return rb_file_writable_real_p(0, argv[1]);
5440 case 'x':
5441 return rb_file_executable_p(0, argv[1]);
5443 case 'X':
5444 return rb_file_executable_real_p(0, argv[1]);
5446 case 'z':
5447 return rb_file_zero_p(0, argv[1]);
5451 if (strchr("MAC", cmd)) {
5452 struct stat st;
5453 VALUE fname = argv[1];
5455 CHECK(1);
5456 if (rb_stat(fname, &st) == -1) {
5457 int e = errno;
5458 FilePathValue(fname);
5459 rb_syserr_fail_path(e, fname);
5462 switch (cmd) {
5463 case 'A':
5464 return stat_atime(&st);
5465 case 'M':
5466 return stat_mtime(&st);
5467 case 'C':
5468 return stat_ctime(&st);
5472 if (cmd == '-') {
5473 CHECK(2);
5474 return rb_file_identical_p(0, argv[1], argv[2]);
5477 if (strchr("=<>", cmd)) {
5478 struct stat st1, st2;
5479 struct timespec t1, t2;
5481 CHECK(2);
5482 if (rb_stat(argv[1], &st1) < 0) return Qfalse;
5483 if (rb_stat(argv[2], &st2) < 0) return Qfalse;
5485 t1 = stat_mtimespec(&st1);
5486 t2 = stat_mtimespec(&st2);
5488 switch (cmd) {
5489 case '=':
5490 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec == t2.tv_nsec) return Qtrue;
5491 return Qfalse;
5493 case '>':
5494 if (t1.tv_sec > t2.tv_sec) return Qtrue;
5495 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec > t2.tv_nsec) return Qtrue;
5496 return Qfalse;
5498 case '<':
5499 if (t1.tv_sec < t2.tv_sec) return Qtrue;
5500 if (t1.tv_sec == t2.tv_sec && t1.tv_nsec < t2.tv_nsec) return Qtrue;
5501 return Qfalse;
5504 unknown:
5505 /* unknown command */
5506 if (ISPRINT(cmd)) {
5507 rb_raise(rb_eArgError, "unknown command '%s%c'", cmd == '\'' || cmd == '\\' ? "\\" : "", cmd);
5509 else {
5510 rb_raise(rb_eArgError, "unknown command \"\\x%02X\"", cmd);
5512 UNREACHABLE_RETURN(Qundef);
5517 * Document-class: File::Stat
5519 * Objects of class File::Stat encapsulate common status information
5520 * for File objects. The information is recorded at the moment the
5521 * File::Stat object is created; changes made to the file after that
5522 * point will not be reflected. File::Stat objects are returned by
5523 * IO#stat, File::stat, File#lstat, and File::lstat. Many of these
5524 * methods return platform-specific values, and not all values are
5525 * meaningful on all systems. See also Kernel#test.
5528 static VALUE
5529 rb_stat_s_alloc(VALUE klass)
5531 return stat_new_0(klass, 0);
5535 * call-seq:
5537 * File::Stat.new(file_name) -> stat
5539 * Create a File::Stat object for the given file name (raising an
5540 * exception if the file doesn't exist).
5543 static VALUE
5544 rb_stat_init(VALUE obj, VALUE fname)
5546 struct stat st, *nst;
5548 FilePathValue(fname);
5549 fname = rb_str_encode_ospath(fname);
5550 if (STAT(StringValueCStr(fname), &st) == -1) {
5551 rb_sys_fail_path(fname);
5553 if (DATA_PTR(obj)) {
5554 xfree(DATA_PTR(obj));
5555 DATA_PTR(obj) = NULL;
5557 nst = ALLOC(struct stat);
5558 *nst = st;
5559 DATA_PTR(obj) = nst;
5561 return Qnil;
5564 /* :nodoc: */
5565 static VALUE
5566 rb_stat_init_copy(VALUE copy, VALUE orig)
5568 struct stat *nst;
5570 if (!OBJ_INIT_COPY(copy, orig)) return copy;
5571 if (DATA_PTR(copy)) {
5572 xfree(DATA_PTR(copy));
5573 DATA_PTR(copy) = 0;
5575 if (DATA_PTR(orig)) {
5576 nst = ALLOC(struct stat);
5577 *nst = *(struct stat*)DATA_PTR(orig);
5578 DATA_PTR(copy) = nst;
5581 return copy;
5585 * call-seq:
5586 * stat.ftype -> string
5588 * Identifies the type of <i>stat</i>. The return string is one of:
5589 * ``<code>file</code>'', ``<code>directory</code>'',
5590 * ``<code>characterSpecial</code>'', ``<code>blockSpecial</code>'',
5591 * ``<code>fifo</code>'', ``<code>link</code>'',
5592 * ``<code>socket</code>'', or ``<code>unknown</code>''.
5594 * File.stat("/dev/tty").ftype #=> "characterSpecial"
5598 static VALUE
5599 rb_stat_ftype(VALUE obj)
5601 return rb_file_ftype(get_stat(obj));
5605 * call-seq:
5606 * stat.directory? -> true or false
5608 * Returns <code>true</code> if <i>stat</i> is a directory,
5609 * <code>false</code> otherwise.
5611 * File.stat("testfile").directory? #=> false
5612 * File.stat(".").directory? #=> true
5615 static VALUE
5616 rb_stat_d(VALUE obj)
5618 if (S_ISDIR(get_stat(obj)->st_mode)) return Qtrue;
5619 return Qfalse;
5623 * call-seq:
5624 * stat.pipe? -> true or false
5626 * Returns <code>true</code> if the operating system supports pipes and
5627 * <i>stat</i> is a pipe; <code>false</code> otherwise.
5630 static VALUE
5631 rb_stat_p(VALUE obj)
5633 #ifdef S_IFIFO
5634 if (S_ISFIFO(get_stat(obj)->st_mode)) return Qtrue;
5636 #endif
5637 return Qfalse;
5641 * call-seq:
5642 * stat.symlink? -> true or false
5644 * Returns <code>true</code> if <i>stat</i> is a symbolic link,
5645 * <code>false</code> if it isn't or if the operating system doesn't
5646 * support this feature. As File::stat automatically follows symbolic
5647 * links, #symlink? will always be <code>false</code> for an object
5648 * returned by File::stat.
5650 * File.symlink("testfile", "alink") #=> 0
5651 * File.stat("alink").symlink? #=> false
5652 * File.lstat("alink").symlink? #=> true
5656 static VALUE
5657 rb_stat_l(VALUE obj)
5659 #ifdef S_ISLNK
5660 if (S_ISLNK(get_stat(obj)->st_mode)) return Qtrue;
5661 #endif
5662 return Qfalse;
5666 * call-seq:
5667 * stat.socket? -> true or false
5669 * Returns <code>true</code> if <i>stat</i> is a socket,
5670 * <code>false</code> if it isn't or if the operating system doesn't
5671 * support this feature.
5673 * File.stat("testfile").socket? #=> false
5677 static VALUE
5678 rb_stat_S(VALUE obj)
5680 #ifdef S_ISSOCK
5681 if (S_ISSOCK(get_stat(obj)->st_mode)) return Qtrue;
5683 #endif
5684 return Qfalse;
5688 * call-seq:
5689 * stat.blockdev? -> true or false
5691 * Returns <code>true</code> if the file is a block device,
5692 * <code>false</code> if it isn't or if the operating system doesn't
5693 * support this feature.
5695 * File.stat("testfile").blockdev? #=> false
5696 * File.stat("/dev/hda1").blockdev? #=> true
5700 static VALUE
5701 rb_stat_b(VALUE obj)
5703 #ifdef S_ISBLK
5704 if (S_ISBLK(get_stat(obj)->st_mode)) return Qtrue;
5706 #endif
5707 return Qfalse;
5711 * call-seq:
5712 * stat.chardev? -> true or false
5714 * Returns <code>true</code> if the file is a character device,
5715 * <code>false</code> if it isn't or if the operating system doesn't
5716 * support this feature.
5718 * File.stat("/dev/tty").chardev? #=> true
5722 static VALUE
5723 rb_stat_c(VALUE obj)
5725 if (S_ISCHR(get_stat(obj)->st_mode)) return Qtrue;
5727 return Qfalse;
5731 * call-seq:
5732 * stat.owned? -> true or false
5734 * Returns <code>true</code> if the effective user id of the process is
5735 * the same as the owner of <i>stat</i>.
5737 * File.stat("testfile").owned? #=> true
5738 * File.stat("/etc/passwd").owned? #=> false
5742 static VALUE
5743 rb_stat_owned(VALUE obj)
5745 if (get_stat(obj)->st_uid == geteuid()) return Qtrue;
5746 return Qfalse;
5749 static VALUE
5750 rb_stat_rowned(VALUE obj)
5752 if (get_stat(obj)->st_uid == getuid()) return Qtrue;
5753 return Qfalse;
5757 * call-seq:
5758 * stat.grpowned? -> true or false
5760 * Returns true if the effective group id of the process is the same as
5761 * the group id of <i>stat</i>. On Windows NT, returns <code>false</code>.
5763 * File.stat("testfile").grpowned? #=> true
5764 * File.stat("/etc/passwd").grpowned? #=> false
5768 static VALUE
5769 rb_stat_grpowned(VALUE obj)
5771 #ifndef _WIN32
5772 if (rb_group_member(get_stat(obj)->st_gid)) return Qtrue;
5773 #endif
5774 return Qfalse;
5778 * call-seq:
5779 * stat.readable? -> true or false
5781 * Returns <code>true</code> if <i>stat</i> is readable by the
5782 * effective user id of this process.
5784 * File.stat("testfile").readable? #=> true
5788 static VALUE
5789 rb_stat_r(VALUE obj)
5791 struct stat *st = get_stat(obj);
5793 #ifdef USE_GETEUID
5794 if (geteuid() == 0) return Qtrue;
5795 #endif
5796 #ifdef S_IRUSR
5797 if (rb_stat_owned(obj))
5798 return RBOOL(st->st_mode & S_IRUSR);
5799 #endif
5800 #ifdef S_IRGRP
5801 if (rb_stat_grpowned(obj))
5802 return RBOOL(st->st_mode & S_IRGRP);
5803 #endif
5804 #ifdef S_IROTH
5805 if (!(st->st_mode & S_IROTH)) return Qfalse;
5806 #endif
5807 return Qtrue;
5811 * call-seq:
5812 * stat.readable_real? -> true or false
5814 * Returns <code>true</code> if <i>stat</i> is readable by the real
5815 * user id of this process.
5817 * File.stat("testfile").readable_real? #=> true
5821 static VALUE
5822 rb_stat_R(VALUE obj)
5824 struct stat *st = get_stat(obj);
5826 #ifdef USE_GETEUID
5827 if (getuid() == 0) return Qtrue;
5828 #endif
5829 #ifdef S_IRUSR
5830 if (rb_stat_rowned(obj))
5831 return RBOOL(st->st_mode & S_IRUSR);
5832 #endif
5833 #ifdef S_IRGRP
5834 if (rb_group_member(get_stat(obj)->st_gid))
5835 return RBOOL(st->st_mode & S_IRGRP);
5836 #endif
5837 #ifdef S_IROTH
5838 if (!(st->st_mode & S_IROTH)) return Qfalse;
5839 #endif
5840 return Qtrue;
5844 * call-seq:
5845 * stat.world_readable? -> integer or nil
5847 * If <i>stat</i> is readable by others, returns an integer
5848 * representing the file permission bits of <i>stat</i>. Returns
5849 * <code>nil</code> otherwise. The meaning of the bits is platform
5850 * dependent; on Unix systems, see <code>stat(2)</code>.
5852 * m = File.stat("/etc/passwd").world_readable? #=> 420
5853 * sprintf("%o", m) #=> "644"
5856 static VALUE
5857 rb_stat_wr(VALUE obj)
5859 #ifdef S_IROTH
5860 struct stat *st = get_stat(obj);
5861 if ((st->st_mode & (S_IROTH)) == S_IROTH) {
5862 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
5864 else {
5865 return Qnil;
5867 #endif
5871 * call-seq:
5872 * stat.writable? -> true or false
5874 * Returns <code>true</code> if <i>stat</i> is writable by the
5875 * effective user id of this process.
5877 * File.stat("testfile").writable? #=> true
5881 static VALUE
5882 rb_stat_w(VALUE obj)
5884 struct stat *st = get_stat(obj);
5886 #ifdef USE_GETEUID
5887 if (geteuid() == 0) return Qtrue;
5888 #endif
5889 #ifdef S_IWUSR
5890 if (rb_stat_owned(obj))
5891 return RBOOL(st->st_mode & S_IWUSR);
5892 #endif
5893 #ifdef S_IWGRP
5894 if (rb_stat_grpowned(obj))
5895 return RBOOL(st->st_mode & S_IWGRP);
5896 #endif
5897 #ifdef S_IWOTH
5898 if (!(st->st_mode & S_IWOTH)) return Qfalse;
5899 #endif
5900 return Qtrue;
5904 * call-seq:
5905 * stat.writable_real? -> true or false
5907 * Returns <code>true</code> if <i>stat</i> is writable by the real
5908 * user id of this process.
5910 * File.stat("testfile").writable_real? #=> true
5914 static VALUE
5915 rb_stat_W(VALUE obj)
5917 struct stat *st = get_stat(obj);
5919 #ifdef USE_GETEUID
5920 if (getuid() == 0) return Qtrue;
5921 #endif
5922 #ifdef S_IWUSR
5923 if (rb_stat_rowned(obj))
5924 return RBOOL(st->st_mode & S_IWUSR);
5925 #endif
5926 #ifdef S_IWGRP
5927 if (rb_group_member(get_stat(obj)->st_gid))
5928 return RBOOL(st->st_mode & S_IWGRP);
5929 #endif
5930 #ifdef S_IWOTH
5931 if (!(st->st_mode & S_IWOTH)) return Qfalse;
5932 #endif
5933 return Qtrue;
5937 * call-seq:
5938 * stat.world_writable? -> integer or nil
5940 * If <i>stat</i> is writable by others, returns an integer
5941 * representing the file permission bits of <i>stat</i>. Returns
5942 * <code>nil</code> otherwise. The meaning of the bits is platform
5943 * dependent; on Unix systems, see <code>stat(2)</code>.
5945 * m = File.stat("/tmp").world_writable? #=> 511
5946 * sprintf("%o", m) #=> "777"
5949 static VALUE
5950 rb_stat_ww(VALUE obj)
5952 #ifdef S_IROTH
5953 struct stat *st = get_stat(obj);
5954 if ((st->st_mode & (S_IWOTH)) == S_IWOTH) {
5955 return UINT2NUM(st->st_mode & (S_IRUGO|S_IWUGO|S_IXUGO));
5957 else {
5958 return Qnil;
5960 #endif
5964 * call-seq:
5965 * stat.executable? -> true or false
5967 * Returns <code>true</code> if <i>stat</i> is executable or if the
5968 * operating system doesn't distinguish executable files from
5969 * nonexecutable files. The tests are made using the effective owner of
5970 * the process.
5972 * File.stat("testfile").executable? #=> false
5976 static VALUE
5977 rb_stat_x(VALUE obj)
5979 struct stat *st = get_stat(obj);
5981 #ifdef USE_GETEUID
5982 if (geteuid() == 0) {
5983 return RBOOL(st->st_mode & S_IXUGO);
5985 #endif
5986 #ifdef S_IXUSR
5987 if (rb_stat_owned(obj))
5988 return RBOOL(st->st_mode & S_IXUSR);
5989 #endif
5990 #ifdef S_IXGRP
5991 if (rb_stat_grpowned(obj))
5992 return RBOOL(st->st_mode & S_IXGRP);
5993 #endif
5994 #ifdef S_IXOTH
5995 if (!(st->st_mode & S_IXOTH)) return Qfalse;
5996 #endif
5997 return Qtrue;
6001 * call-seq:
6002 * stat.executable_real? -> true or false
6004 * Same as <code>executable?</code>, but tests using the real owner of
6005 * the process.
6008 static VALUE
6009 rb_stat_X(VALUE obj)
6011 struct stat *st = get_stat(obj);
6013 #ifdef USE_GETEUID
6014 if (getuid() == 0) {
6015 return RBOOL(st->st_mode & S_IXUGO);
6017 #endif
6018 #ifdef S_IXUSR
6019 if (rb_stat_rowned(obj))
6020 return RBOOL(st->st_mode & S_IXUSR);
6021 #endif
6022 #ifdef S_IXGRP
6023 if (rb_group_member(get_stat(obj)->st_gid))
6024 return RBOOL(st->st_mode & S_IXGRP);
6025 #endif
6026 #ifdef S_IXOTH
6027 if (!(st->st_mode & S_IXOTH)) return Qfalse;
6028 #endif
6029 return Qtrue;
6033 * call-seq:
6034 * stat.file? -> true or false
6036 * Returns <code>true</code> if <i>stat</i> is a regular file (not
6037 * a device file, pipe, socket, etc.).
6039 * File.stat("testfile").file? #=> true
6043 static VALUE
6044 rb_stat_f(VALUE obj)
6046 if (S_ISREG(get_stat(obj)->st_mode)) return Qtrue;
6047 return Qfalse;
6051 * call-seq:
6052 * stat.zero? -> true or false
6054 * Returns <code>true</code> if <i>stat</i> is a zero-length file;
6055 * <code>false</code> otherwise.
6057 * File.stat("testfile").zero? #=> false
6061 static VALUE
6062 rb_stat_z(VALUE obj)
6064 if (get_stat(obj)->st_size == 0) return Qtrue;
6065 return Qfalse;
6069 * call-seq:
6070 * stat.size? -> Integer or nil
6072 * Returns +nil+ if <i>stat</i> is a zero-length file, the size of
6073 * the file otherwise.
6075 * File.stat("testfile").size? #=> 66
6076 * File.stat("/dev/null").size? #=> nil
6080 static VALUE
6081 rb_stat_s(VALUE obj)
6083 off_t size = get_stat(obj)->st_size;
6085 if (size == 0) return Qnil;
6086 return OFFT2NUM(size);
6090 * call-seq:
6091 * stat.setuid? -> true or false
6093 * Returns <code>true</code> if <i>stat</i> has the set-user-id
6094 * permission bit set, <code>false</code> if it doesn't or if the
6095 * operating system doesn't support this feature.
6097 * File.stat("/bin/su").setuid? #=> true
6100 static VALUE
6101 rb_stat_suid(VALUE obj)
6103 #ifdef S_ISUID
6104 if (get_stat(obj)->st_mode & S_ISUID) return Qtrue;
6105 #endif
6106 return Qfalse;
6110 * call-seq:
6111 * stat.setgid? -> true or false
6113 * Returns <code>true</code> if <i>stat</i> has the set-group-id
6114 * permission bit set, <code>false</code> if it doesn't or if the
6115 * operating system doesn't support this feature.
6117 * File.stat("/usr/sbin/lpc").setgid? #=> true
6121 static VALUE
6122 rb_stat_sgid(VALUE obj)
6124 #ifdef S_ISGID
6125 if (get_stat(obj)->st_mode & S_ISGID) return Qtrue;
6126 #endif
6127 return Qfalse;
6131 * call-seq:
6132 * stat.sticky? -> true or false
6134 * Returns <code>true</code> if <i>stat</i> has its sticky bit set,
6135 * <code>false</code> if it doesn't or if the operating system doesn't
6136 * support this feature.
6138 * File.stat("testfile").sticky? #=> false
6142 static VALUE
6143 rb_stat_sticky(VALUE obj)
6145 #ifdef S_ISVTX
6146 if (get_stat(obj)->st_mode & S_ISVTX) return Qtrue;
6147 #endif
6148 return Qfalse;
6151 #if !defined HAVE_MKFIFO && defined HAVE_MKNOD && defined S_IFIFO
6152 #define mkfifo(path, mode) mknod(path, (mode)&~S_IFMT|S_IFIFO, 0)
6153 #define HAVE_MKFIFO
6154 #endif
6156 #ifdef HAVE_MKFIFO
6157 struct mkfifo_arg {
6158 const char *path;
6159 mode_t mode;
6162 static void *
6163 nogvl_mkfifo(void *ptr)
6165 struct mkfifo_arg *ma = ptr;
6167 return (void *)(VALUE)mkfifo(ma->path, ma->mode);
6171 * call-seq:
6172 * File.mkfifo(file_name, mode=0666) => 0
6174 * Creates a FIFO special file with name _file_name_. _mode_
6175 * specifies the FIFO's permissions. It is modified by the process's
6176 * umask in the usual way: the permissions of the created file are
6177 * (mode & ~umask).
6180 static VALUE
6181 rb_file_s_mkfifo(int argc, VALUE *argv, VALUE _)
6183 VALUE path;
6184 struct mkfifo_arg ma;
6186 ma.mode = 0666;
6187 rb_check_arity(argc, 1, 2);
6188 if (argc > 1) {
6189 ma.mode = NUM2MODET(argv[1]);
6191 path = argv[0];
6192 FilePathValue(path);
6193 path = rb_str_encode_ospath(path);
6194 ma.path = RSTRING_PTR(path);
6195 if (rb_thread_call_without_gvl(nogvl_mkfifo, &ma, RUBY_UBF_IO, 0)) {
6196 rb_sys_fail_path(path);
6198 return INT2FIX(0);
6200 #else
6201 #define rb_file_s_mkfifo rb_f_notimplement
6202 #endif
6204 static VALUE rb_mFConst;
6206 void
6207 rb_file_const(const char *name, VALUE value)
6209 rb_define_const(rb_mFConst, name, value);
6213 rb_is_absolute_path(const char *path)
6215 #ifdef DOSISH_DRIVE_LETTER
6216 if (has_drive_letter(path) && isdirsep(path[2])) return 1;
6217 #endif
6218 #ifdef DOSISH_UNC
6219 if (isdirsep(path[0]) && isdirsep(path[1])) return 1;
6220 #endif
6221 #ifndef DOSISH
6222 if (path[0] == '/') return 1;
6223 #endif
6224 return 0;
6227 #ifndef ENABLE_PATH_CHECK
6228 # if defined DOSISH || defined __CYGWIN__
6229 # define ENABLE_PATH_CHECK 0
6230 # else
6231 # define ENABLE_PATH_CHECK 1
6232 # endif
6233 #endif
6235 #if ENABLE_PATH_CHECK
6236 static int
6237 path_check_0(VALUE path)
6239 struct stat st;
6240 const char *p0 = StringValueCStr(path);
6241 const char *e0;
6242 rb_encoding *enc;
6243 char *p = 0, *s;
6245 if (!rb_is_absolute_path(p0)) {
6246 char *buf = ruby_getcwd();
6247 VALUE newpath;
6249 newpath = rb_str_new2(buf);
6250 xfree(buf);
6252 rb_str_cat2(newpath, "/");
6253 rb_str_cat2(newpath, p0);
6254 path = newpath;
6255 p0 = RSTRING_PTR(path);
6257 e0 = p0 + RSTRING_LEN(path);
6258 enc = rb_enc_get(path);
6259 for (;;) {
6260 #ifndef S_IWOTH
6261 # define S_IWOTH 002
6262 #endif
6263 if (STAT(p0, &st) == 0 && S_ISDIR(st.st_mode) && (st.st_mode & S_IWOTH)
6264 #ifdef S_ISVTX
6265 && !(p && (st.st_mode & S_ISVTX))
6266 #endif
6267 && !access(p0, W_OK)) {
6268 rb_enc_warn(enc, "Insecure world writable dir %s in PATH, mode 0%"
6269 #if SIZEOF_DEV_T > SIZEOF_INT
6270 PRI_MODET_PREFIX"o",
6271 #else
6272 "o",
6273 #endif
6274 p0, st.st_mode);
6275 if (p) *p = '/';
6276 RB_GC_GUARD(path);
6277 return 0;
6279 s = strrdirsep(p0, e0, enc);
6280 if (p) *p = '/';
6281 if (!s || s == p0) return 1;
6282 p = s;
6283 e0 = p;
6284 *p = '\0';
6287 #endif
6290 rb_path_check(const char *path)
6292 #if ENABLE_PATH_CHECK
6293 const char *p0, *p, *pend;
6294 const char sep = PATH_SEP_CHAR;
6296 if (!path) return 1;
6298 pend = path + strlen(path);
6299 p0 = path;
6300 p = strchr(path, sep);
6301 if (!p) p = pend;
6303 for (;;) {
6304 if (!path_check_0(rb_str_new(p0, p - p0))) {
6305 return 0; /* not safe */
6307 p0 = p + 1;
6308 if (p0 > pend) break;
6309 p = strchr(p0, sep);
6310 if (!p) p = pend;
6312 #endif
6313 return 1;
6317 ruby_is_fd_loadable(int fd)
6319 #ifdef _WIN32
6320 return 1;
6321 #else
6322 struct stat st;
6324 if (fstat(fd, &st) < 0)
6325 return 0;
6327 if (S_ISREG(st.st_mode))
6328 return 1;
6330 if (S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode))
6331 return -1;
6333 if (S_ISDIR(st.st_mode))
6334 errno = EISDIR;
6335 else
6336 errno = ENXIO;
6338 return 0;
6339 #endif
6342 #ifndef _WIN32
6344 rb_file_load_ok(const char *path)
6346 int ret = 1;
6348 open(2) may block if path is FIFO and it's empty. Let's use O_NONBLOCK.
6349 FIXME: Why O_NDELAY is checked?
6351 int mode = (O_RDONLY |
6352 #if defined O_NONBLOCK
6353 O_NONBLOCK |
6354 #elif defined O_NDELAY
6355 O_NDELAY |
6356 #endif
6358 int fd = rb_cloexec_open(path, mode, 0);
6359 if (fd == -1) return 0;
6360 rb_update_max_fd(fd);
6361 ret = ruby_is_fd_loadable(fd);
6362 (void)close(fd);
6363 return ret;
6365 #endif
6367 static int
6368 is_explicit_relative(const char *path)
6370 if (*path++ != '.') return 0;
6371 if (*path == '.') path++;
6372 return isdirsep(*path);
6375 static VALUE
6376 copy_path_class(VALUE path, VALUE orig)
6378 int encidx = rb_enc_get_index(orig);
6379 if (encidx == ENCINDEX_ASCII || encidx == ENCINDEX_US_ASCII)
6380 encidx = rb_filesystem_encindex();
6381 rb_enc_associate_index(path, encidx);
6382 str_shrink(path);
6383 RBASIC_SET_CLASS(path, rb_obj_class(orig));
6384 OBJ_FREEZE(path);
6385 return path;
6389 rb_find_file_ext(VALUE *filep, const char *const *ext)
6391 const char *f = StringValueCStr(*filep);
6392 VALUE fname = *filep, load_path, tmp;
6393 long i, j, fnlen;
6394 int expanded = 0;
6396 if (!ext[0]) return 0;
6398 if (f[0] == '~') {
6399 fname = file_expand_path_1(fname);
6400 f = RSTRING_PTR(fname);
6401 *filep = fname;
6402 expanded = 1;
6405 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6406 if (!expanded) fname = file_expand_path_1(fname);
6407 fnlen = RSTRING_LEN(fname);
6408 for (i=0; ext[i]; i++) {
6409 rb_str_cat2(fname, ext[i]);
6410 if (rb_file_load_ok(RSTRING_PTR(fname))) {
6411 *filep = copy_path_class(fname, *filep);
6412 return (int)(i+1);
6414 rb_str_set_len(fname, fnlen);
6416 return 0;
6419 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6420 if (!load_path) return 0;
6422 fname = rb_str_dup(*filep);
6423 RBASIC_CLEAR_CLASS(fname);
6424 fnlen = RSTRING_LEN(fname);
6425 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6426 rb_enc_associate_index(tmp, rb_usascii_encindex());
6427 for (j=0; ext[j]; j++) {
6428 rb_str_cat2(fname, ext[j]);
6429 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6430 VALUE str = RARRAY_AREF(load_path, i);
6432 RB_GC_GUARD(str) = rb_get_path(str);
6433 if (RSTRING_LEN(str) == 0) continue;
6434 rb_file_expand_path_internal(fname, str, 0, 0, tmp);
6435 if (rb_file_load_ok(RSTRING_PTR(tmp))) {
6436 *filep = copy_path_class(tmp, *filep);
6437 return (int)(j+1);
6440 rb_str_set_len(fname, fnlen);
6442 rb_str_resize(tmp, 0);
6443 RB_GC_GUARD(load_path);
6444 return 0;
6447 VALUE
6448 rb_find_file(VALUE path)
6450 VALUE tmp, load_path;
6451 const char *f = StringValueCStr(path);
6452 int expanded = 0;
6454 if (f[0] == '~') {
6455 tmp = file_expand_path_1(path);
6456 path = copy_path_class(tmp, path);
6457 f = RSTRING_PTR(path);
6458 expanded = 1;
6461 if (expanded || rb_is_absolute_path(f) || is_explicit_relative(f)) {
6462 if (!rb_file_load_ok(f)) return 0;
6463 if (!expanded)
6464 path = copy_path_class(file_expand_path_1(path), path);
6465 return path;
6468 RB_GC_GUARD(load_path) = rb_get_expanded_load_path();
6469 if (load_path) {
6470 long i;
6472 tmp = rb_str_tmp_new(MAXPATHLEN + 2);
6473 rb_enc_associate_index(tmp, rb_usascii_encindex());
6474 for (i = 0; i < RARRAY_LEN(load_path); i++) {
6475 VALUE str = RARRAY_AREF(load_path, i);
6476 RB_GC_GUARD(str) = rb_get_path(str);
6477 if (RSTRING_LEN(str) > 0) {
6478 rb_file_expand_path_internal(path, str, 0, 0, tmp);
6479 f = RSTRING_PTR(tmp);
6480 if (rb_file_load_ok(f)) goto found;
6483 rb_str_resize(tmp, 0);
6484 return 0;
6486 else {
6487 return 0; /* no path, no load */
6490 found:
6491 return copy_path_class(tmp, path);
6494 static void
6495 define_filetest_function(const char *name, VALUE (*func)(ANYARGS), int argc)
6497 rb_define_module_function(rb_mFileTest, name, func, argc);
6498 rb_define_singleton_method(rb_cFile, name, func, argc);
6501 const char ruby_null_device[] =
6502 #if defined DOSISH
6503 "NUL"
6504 #elif defined AMIGA || defined __amigaos__
6505 "NIL"
6506 #elif defined __VMS
6507 "NL:"
6508 #else
6509 "/dev/null"
6510 #endif
6514 * A File is an abstraction of any file object accessible by the
6515 * program and is closely associated with class IO. File includes
6516 * the methods of module FileTest as class methods, allowing you to
6517 * write (for example) <code>File.exist?("foo")</code>.
6519 * In the description of File methods,
6520 * <em>permission bits</em> are a platform-specific
6521 * set of bits that indicate permissions of a file. On Unix-based
6522 * systems, permissions are viewed as a set of three octets, for the
6523 * owner, the group, and the rest of the world. For each of these
6524 * entities, permissions may be set to read, write, or execute the
6525 * file:
6527 * The permission bits <code>0644</code> (in octal) would thus be
6528 * interpreted as read/write for owner, and read-only for group and
6529 * other. Higher-order bits may also be used to indicate the type of
6530 * file (plain, directory, pipe, socket, and so on) and various other
6531 * special features. If the permissions are for a directory, the
6532 * meaning of the execute bit changes; when set the directory can be
6533 * searched.
6535 * On non-Posix operating systems, there may be only the ability to
6536 * make a file read-only or read-write. In this case, the remaining
6537 * permission bits will be synthesized to resemble typical values. For
6538 * instance, on Windows NT the default permission bits are
6539 * <code>0644</code>, which means read/write for owner, read-only for
6540 * all others. The only change that can be made is to make the file
6541 * read-only, which is reported as <code>0444</code>.
6543 * Various constants for the methods in File can be found in File::Constants.
6545 * == What's Here
6547 * First, what's elsewhere. \Class \File:
6549 * - Inherits from {class IO}[IO.html#class-IO-label-What-27s+Here],
6550 * in particular, methods for creating, reading, and writing files
6551 * - Includes {module FileTest}[FileTest.html#module-FileTest-label-What-27s+Here].
6552 * which provides dozens of additional methods.
6554 * Here, class \File provides methods that are useful for:
6556 * - {Creating}[#class-File-label-Creating]
6557 * - {Querying}[#class-File-label-Querying]
6558 * - {Settings}[#class-File-label-Settings]
6559 * - {Other}[#class-File-label-Other]
6561 * === Creating
6563 * - ::new:: Opens the file at the given path; returns the file.
6564 * - ::open:: Same as ::new, but when given a block will yield the file to the block,
6565 * and close the file upon exiting the block.
6566 * - ::link:: Creates a new name for an existing file using a hard link.
6567 * - ::mkfifo:: Returns the FIFO file created at the given path.
6568 * - ::symlink:: Creates a symbolic link for the given file path.
6570 * === Querying
6572 * _Paths_
6574 * - ::absolute_path:: Returns the absolute file path for the given path.
6575 * - ::absolute_path?:: Returns whether the given path is the absolute file path.
6576 * - ::basename:: Returns the last component of the given file path.
6577 * - ::dirname:: Returns all but the last component of the given file path.
6578 * - ::expand_path:: Returns the absolute file path for the given path,
6579 * expanding <tt>~</tt> for a home directory.
6580 * - ::extname:: Returns the file extension for the given file path.
6581 * - ::fnmatch? (aliased as ::fnmatch):: Returns whether the given file path
6582 * matches the given pattern.
6583 * - ::join:: Joins path components into a single path string.
6584 * - ::path:: Returns the string representation of the given path.
6585 * - ::readlink:: Returns the path to the file at the given symbolic link.
6586 * - ::realdirpath:: Returns the real path for the given file path,
6587 * where the last component need not exist.
6588 * - ::realpath:: Returns the real path for the given file path,
6589 * where all components must exist.
6590 * - ::split:: Returns an array of two strings: the directory name and basename
6591 * of the file at the given path.
6592 * - #path (aliased as #to_path):: Returns the string representation of the given path.
6594 * _Times_
6596 * - ::atime:: Returns a \Time for the most recent access to the given file.
6597 * - ::birthtime:: Returns a \Time for the creation of the given file.
6598 * - ::ctime:: Returns a \Time for the metadata change of the given file.
6599 * - ::mtime:: Returns a \Time for the most recent data modification to
6600 * the content of the given file.
6601 * - #atime:: Returns a \Time for the most recent access to +self+.
6602 * - #birthtime:: Returns a \Time the creation for +self+.
6603 * - #ctime:: Returns a \Time for the metadata change of +self+.
6604 * - #mtime:: Returns a \Time for the most recent data modification
6605 * to the content of +self+.
6607 * _Types_
6609 * - ::blockdev?:: Returns whether the file at the given path is a block device.
6610 * - ::chardev?:: Returns whether the file at the given path is a character device.
6611 * - ::directory?:: Returns whether the file at the given path is a diretory.
6612 * - ::executable?:: Returns whether the file at the given path is executable
6613 * by the effective user and group of the current process.
6614 * - ::executable_real?:: Returns whether the file at the given path is executable
6615 * by the real user and group of the current process.
6616 * - ::exist?:: Returns whether the file at the given path exists.
6617 * - ::file?:: Returns whether the file at the given path is a regular file.
6618 * - ::ftype:: Returns a string giving the type of the file at the given path.
6619 * - ::grpowned?:: Returns whether the effective group of the current process
6620 * owns the file at the given path.
6621 * - ::identical?:: Returns whether the files at two given paths are identical.
6622 * - ::lstat:: Returns the File::Stat object for the last symbolic link
6623 * in the given path.
6624 * - ::owned?:: Returns whether the effective user of the current process
6625 * owns the file at the given path.
6626 * - ::pipe?:: Returns whether the file at the given path is a pipe.
6627 * - ::readable?:: Returns whether the file at the given path is readable
6628 * by the effective user and group of the current process.
6629 * - ::readable_real?:: Returns whether the file at the given path is readable
6630 * by the real user and group of the current process.
6631 * - ::setgid?:: Returns whether the setgid bit is set for the file at the given path.
6632 * - ::setuid?:: Returns whether the setuid bit is set for the file at the given path.
6633 * - ::socket?:: Returns whether the file at the given path is a socket.
6634 * - ::stat:: Returns the File::Stat object for the file at the given path.
6635 * - ::sticky?:: Returns whether the file at the given path has its sticky bit set.
6636 * - ::symlink?:: Returns whether the file at the given path is a symbolic link.
6637 * - ::umask:: Returns the umask value for the current process.
6638 * - ::world_readable?:: Returns whether the file at the given path is readable
6639 * by others.
6640 * - ::world_writable?:: Returns whether the file at the given path is writable
6641 * by others.
6642 * - ::writable?:: Returns whether the file at the given path is writable
6643 * by the effective user and group of the current process.
6644 * - ::writable_real?:: Returns whether the file at the given path is writable
6645 * by the real user and group of the current process.
6646 * - #lstat:: Returns the File::Stat object for the last symbolic link
6647 * in the path for +self+.
6649 * _Contents_
6651 * - ::empty? (aliased as ::zero?):: Returns whether the file at the given path
6652 * exists and is empty.
6653 * - ::size:: Returns the size (bytes) of the file at the given path.
6654 * - ::size?:: Returns +nil+ if there is no file at the given path,
6655 * or if that file is empty; otherwise returns the file size (bytes).
6656 * - #size:: Returns the size (bytes) of +self+.
6658 * === Settings
6660 * - ::chmod:: Changes permissions of the file at the given path.
6661 * - ::chown:: Change ownership of the file at the given path.
6662 * - ::lchmod:: Changes permissions of the last symbolic link in the given path.
6663 * - ::lchown:: Change ownership of the last symbolic in the given path.
6664 * - ::lutime:: For each given file path, sets the access time and modification time
6665 * of the last symbolic link in the path.
6666 * - ::rename:: Moves the file at one given path to another given path.
6667 * - ::utime:: Sets the access time and modification time of each file
6668 * at the given paths.
6669 * - #flock:: Locks or unlocks +self+.
6671 * === Other
6673 * - ::truncate:: Truncates the file at the given file path to the given size.
6674 * - ::unlink (aliased as ::delete):: Deletes the file for each given file path.
6675 * - #truncate:: Truncates +self+ to the given size.
6679 void
6680 Init_File(void)
6682 VALUE separator;
6684 rb_mFileTest = rb_define_module("FileTest");
6685 rb_cFile = rb_define_class("File", rb_cIO);
6687 define_filetest_function("directory?", rb_file_directory_p, 1);
6688 define_filetest_function("exist?", rb_file_exist_p, 1);
6689 define_filetest_function("readable?", rb_file_readable_p, 1);
6690 define_filetest_function("readable_real?", rb_file_readable_real_p, 1);
6691 define_filetest_function("world_readable?", rb_file_world_readable_p, 1);
6692 define_filetest_function("writable?", rb_file_writable_p, 1);
6693 define_filetest_function("writable_real?", rb_file_writable_real_p, 1);
6694 define_filetest_function("world_writable?", rb_file_world_writable_p, 1);
6695 define_filetest_function("executable?", rb_file_executable_p, 1);
6696 define_filetest_function("executable_real?", rb_file_executable_real_p, 1);
6697 define_filetest_function("file?", rb_file_file_p, 1);
6698 define_filetest_function("zero?", rb_file_zero_p, 1);
6699 define_filetest_function("empty?", rb_file_zero_p, 1);
6700 define_filetest_function("size?", rb_file_size_p, 1);
6701 define_filetest_function("size", rb_file_s_size, 1);
6702 define_filetest_function("owned?", rb_file_owned_p, 1);
6703 define_filetest_function("grpowned?", rb_file_grpowned_p, 1);
6705 define_filetest_function("pipe?", rb_file_pipe_p, 1);
6706 define_filetest_function("symlink?", rb_file_symlink_p, 1);
6707 define_filetest_function("socket?", rb_file_socket_p, 1);
6709 define_filetest_function("blockdev?", rb_file_blockdev_p, 1);
6710 define_filetest_function("chardev?", rb_file_chardev_p, 1);
6712 define_filetest_function("setuid?", rb_file_suid_p, 1);
6713 define_filetest_function("setgid?", rb_file_sgid_p, 1);
6714 define_filetest_function("sticky?", rb_file_sticky_p, 1);
6716 define_filetest_function("identical?", rb_file_identical_p, 2);
6718 rb_define_singleton_method(rb_cFile, "stat", rb_file_s_stat, 1);
6719 rb_define_singleton_method(rb_cFile, "lstat", rb_file_s_lstat, 1);
6720 rb_define_singleton_method(rb_cFile, "ftype", rb_file_s_ftype, 1);
6722 rb_define_singleton_method(rb_cFile, "atime", rb_file_s_atime, 1);
6723 rb_define_singleton_method(rb_cFile, "mtime", rb_file_s_mtime, 1);
6724 rb_define_singleton_method(rb_cFile, "ctime", rb_file_s_ctime, 1);
6725 rb_define_singleton_method(rb_cFile, "birthtime", rb_file_s_birthtime, 1);
6727 rb_define_singleton_method(rb_cFile, "utime", rb_file_s_utime, -1);
6728 rb_define_singleton_method(rb_cFile, "chmod", rb_file_s_chmod, -1);
6729 rb_define_singleton_method(rb_cFile, "chown", rb_file_s_chown, -1);
6730 rb_define_singleton_method(rb_cFile, "lchmod", rb_file_s_lchmod, -1);
6731 rb_define_singleton_method(rb_cFile, "lchown", rb_file_s_lchown, -1);
6732 rb_define_singleton_method(rb_cFile, "lutime", rb_file_s_lutime, -1);
6734 rb_define_singleton_method(rb_cFile, "link", rb_file_s_link, 2);
6735 rb_define_singleton_method(rb_cFile, "symlink", rb_file_s_symlink, 2);
6736 rb_define_singleton_method(rb_cFile, "readlink", rb_file_s_readlink, 1);
6738 rb_define_singleton_method(rb_cFile, "unlink", rb_file_s_unlink, -1);
6739 rb_define_singleton_method(rb_cFile, "delete", rb_file_s_unlink, -1);
6740 rb_define_singleton_method(rb_cFile, "rename", rb_file_s_rename, 2);
6741 rb_define_singleton_method(rb_cFile, "umask", rb_file_s_umask, -1);
6742 rb_define_singleton_method(rb_cFile, "truncate", rb_file_s_truncate, 2);
6743 rb_define_singleton_method(rb_cFile, "mkfifo", rb_file_s_mkfifo, -1);
6744 rb_define_singleton_method(rb_cFile, "expand_path", s_expand_path, -1);
6745 rb_define_singleton_method(rb_cFile, "absolute_path", s_absolute_path, -1);
6746 rb_define_singleton_method(rb_cFile, "absolute_path?", s_absolute_path_p, 1);
6747 rb_define_singleton_method(rb_cFile, "realpath", rb_file_s_realpath, -1);
6748 rb_define_singleton_method(rb_cFile, "realdirpath", rb_file_s_realdirpath, -1);
6749 rb_define_singleton_method(rb_cFile, "basename", rb_file_s_basename, -1);
6750 rb_define_singleton_method(rb_cFile, "dirname", rb_file_s_dirname, -1);
6751 rb_define_singleton_method(rb_cFile, "extname", rb_file_s_extname, 1);
6752 rb_define_singleton_method(rb_cFile, "path", rb_file_s_path, 1);
6754 separator = rb_fstring_lit("/");
6755 /* separates directory parts in path */
6756 rb_define_const(rb_cFile, "Separator", separator);
6757 /* separates directory parts in path */
6758 rb_define_const(rb_cFile, "SEPARATOR", separator);
6759 rb_define_singleton_method(rb_cFile, "split", rb_file_s_split, 1);
6760 rb_define_singleton_method(rb_cFile, "join", rb_file_s_join, -2);
6762 #ifdef DOSISH
6763 /* platform specific alternative separator */
6764 rb_define_const(rb_cFile, "ALT_SEPARATOR", rb_obj_freeze(rb_usascii_str_new2(file_alt_separator)));
6765 #else
6766 rb_define_const(rb_cFile, "ALT_SEPARATOR", Qnil);
6767 #endif
6768 /* path list separator */
6769 rb_define_const(rb_cFile, "PATH_SEPARATOR", rb_fstring_cstr(PATH_SEP));
6771 rb_define_method(rb_cIO, "stat", rb_io_stat, 0); /* this is IO's method */
6772 rb_define_method(rb_cFile, "lstat", rb_file_lstat, 0);
6774 rb_define_method(rb_cFile, "atime", rb_file_atime, 0);
6775 rb_define_method(rb_cFile, "mtime", rb_file_mtime, 0);
6776 rb_define_method(rb_cFile, "ctime", rb_file_ctime, 0);
6777 rb_define_method(rb_cFile, "birthtime", rb_file_birthtime, 0);
6778 rb_define_method(rb_cFile, "size", file_size, 0);
6780 rb_define_method(rb_cFile, "chmod", rb_file_chmod, 1);
6781 rb_define_method(rb_cFile, "chown", rb_file_chown, 2);
6782 rb_define_method(rb_cFile, "truncate", rb_file_truncate, 1);
6784 rb_define_method(rb_cFile, "flock", rb_file_flock, 1);
6787 * Document-module: File::Constants
6789 * File::Constants provides file-related constants. All possible
6790 * file constants are listed in the documentation but they may not all
6791 * be present on your platform.
6793 * If the underlying platform doesn't define a constant the corresponding
6794 * Ruby constant is not defined.
6796 * Your platform documentations (e.g. man open(2)) may describe more
6797 * detailed information.
6799 rb_mFConst = rb_define_module_under(rb_cFile, "Constants");
6800 rb_include_module(rb_cIO, rb_mFConst);
6802 /* open for reading only */
6803 rb_define_const(rb_mFConst, "RDONLY", INT2FIX(O_RDONLY));
6804 /* open for writing only */
6805 rb_define_const(rb_mFConst, "WRONLY", INT2FIX(O_WRONLY));
6806 /* open for reading and writing */
6807 rb_define_const(rb_mFConst, "RDWR", INT2FIX(O_RDWR));
6808 /* append on each write */
6809 rb_define_const(rb_mFConst, "APPEND", INT2FIX(O_APPEND));
6810 /* create file if it does not exist */
6811 rb_define_const(rb_mFConst, "CREAT", INT2FIX(O_CREAT));
6812 /* error if CREAT and the file exists */
6813 rb_define_const(rb_mFConst, "EXCL", INT2FIX(O_EXCL));
6814 #if defined(O_NDELAY) || defined(O_NONBLOCK)
6815 # ifndef O_NONBLOCK
6816 # define O_NONBLOCK O_NDELAY
6817 # endif
6818 /* do not block on open or for data to become available */
6819 rb_define_const(rb_mFConst, "NONBLOCK", INT2FIX(O_NONBLOCK));
6820 #endif
6821 /* truncate size to 0 */
6822 rb_define_const(rb_mFConst, "TRUNC", INT2FIX(O_TRUNC));
6823 #ifdef O_NOCTTY
6824 /* not to make opened IO the controlling terminal device */
6825 rb_define_const(rb_mFConst, "NOCTTY", INT2FIX(O_NOCTTY));
6826 #endif
6827 #ifndef O_BINARY
6828 # define O_BINARY 0
6829 #endif
6830 /* disable line code conversion */
6831 rb_define_const(rb_mFConst, "BINARY", INT2FIX(O_BINARY));
6832 #ifndef O_SHARE_DELETE
6833 # define O_SHARE_DELETE 0
6834 #endif
6835 /* can delete opened file */
6836 rb_define_const(rb_mFConst, "SHARE_DELETE", INT2FIX(O_SHARE_DELETE));
6837 #ifdef O_SYNC
6838 /* any write operation perform synchronously */
6839 rb_define_const(rb_mFConst, "SYNC", INT2FIX(O_SYNC));
6840 #endif
6841 #ifdef O_DSYNC
6842 /* any write operation perform synchronously except some meta data */
6843 rb_define_const(rb_mFConst, "DSYNC", INT2FIX(O_DSYNC));
6844 #endif
6845 #ifdef O_RSYNC
6846 /* any read operation perform synchronously. used with SYNC or DSYNC. */
6847 rb_define_const(rb_mFConst, "RSYNC", INT2FIX(O_RSYNC));
6848 #endif
6849 #ifdef O_NOFOLLOW
6850 /* do not follow symlinks */
6851 rb_define_const(rb_mFConst, "NOFOLLOW", INT2FIX(O_NOFOLLOW)); /* FreeBSD, Linux */
6852 #endif
6853 #ifdef O_NOATIME
6854 /* do not change atime */
6855 rb_define_const(rb_mFConst, "NOATIME", INT2FIX(O_NOATIME)); /* Linux */
6856 #endif
6857 #ifdef O_DIRECT
6858 /* Try to minimize cache effects of the I/O to and from this file. */
6859 rb_define_const(rb_mFConst, "DIRECT", INT2FIX(O_DIRECT));
6860 #endif
6861 #ifdef O_TMPFILE
6862 /* Create an unnamed temporary file */
6863 rb_define_const(rb_mFConst, "TMPFILE", INT2FIX(O_TMPFILE));
6864 #endif
6866 /* shared lock. see File#flock */
6867 rb_define_const(rb_mFConst, "LOCK_SH", INT2FIX(LOCK_SH));
6868 /* exclusive lock. see File#flock */
6869 rb_define_const(rb_mFConst, "LOCK_EX", INT2FIX(LOCK_EX));
6870 /* unlock. see File#flock */
6871 rb_define_const(rb_mFConst, "LOCK_UN", INT2FIX(LOCK_UN));
6872 /* non-blocking lock. used with LOCK_SH or LOCK_EX. see File#flock */
6873 rb_define_const(rb_mFConst, "LOCK_NB", INT2FIX(LOCK_NB));
6875 /* Name of the null device */
6876 rb_define_const(rb_mFConst, "NULL", rb_fstring_cstr(ruby_null_device));
6878 rb_define_method(rb_cFile, "path", rb_file_path, 0);
6879 rb_define_method(rb_cFile, "to_path", rb_file_path, 0);
6880 rb_define_global_function("test", rb_f_test, -1);
6882 rb_cStat = rb_define_class_under(rb_cFile, "Stat", rb_cObject);
6883 rb_define_alloc_func(rb_cStat, rb_stat_s_alloc);
6884 rb_define_method(rb_cStat, "initialize", rb_stat_init, 1);
6885 rb_define_method(rb_cStat, "initialize_copy", rb_stat_init_copy, 1);
6887 rb_include_module(rb_cStat, rb_mComparable);
6889 rb_define_method(rb_cStat, "<=>", rb_stat_cmp, 1);
6891 rb_define_method(rb_cStat, "dev", rb_stat_dev, 0);
6892 rb_define_method(rb_cStat, "dev_major", rb_stat_dev_major, 0);
6893 rb_define_method(rb_cStat, "dev_minor", rb_stat_dev_minor, 0);
6894 rb_define_method(rb_cStat, "ino", rb_stat_ino, 0);
6895 rb_define_method(rb_cStat, "mode", rb_stat_mode, 0);
6896 rb_define_method(rb_cStat, "nlink", rb_stat_nlink, 0);
6897 rb_define_method(rb_cStat, "uid", rb_stat_uid, 0);
6898 rb_define_method(rb_cStat, "gid", rb_stat_gid, 0);
6899 rb_define_method(rb_cStat, "rdev", rb_stat_rdev, 0);
6900 rb_define_method(rb_cStat, "rdev_major", rb_stat_rdev_major, 0);
6901 rb_define_method(rb_cStat, "rdev_minor", rb_stat_rdev_minor, 0);
6902 rb_define_method(rb_cStat, "size", rb_stat_size, 0);
6903 rb_define_method(rb_cStat, "blksize", rb_stat_blksize, 0);
6904 rb_define_method(rb_cStat, "blocks", rb_stat_blocks, 0);
6905 rb_define_method(rb_cStat, "atime", rb_stat_atime, 0);
6906 rb_define_method(rb_cStat, "mtime", rb_stat_mtime, 0);
6907 rb_define_method(rb_cStat, "ctime", rb_stat_ctime, 0);
6908 rb_define_method(rb_cStat, "birthtime", rb_stat_birthtime, 0);
6910 rb_define_method(rb_cStat, "inspect", rb_stat_inspect, 0);
6912 rb_define_method(rb_cStat, "ftype", rb_stat_ftype, 0);
6914 rb_define_method(rb_cStat, "directory?", rb_stat_d, 0);
6915 rb_define_method(rb_cStat, "readable?", rb_stat_r, 0);
6916 rb_define_method(rb_cStat, "readable_real?", rb_stat_R, 0);
6917 rb_define_method(rb_cStat, "world_readable?", rb_stat_wr, 0);
6918 rb_define_method(rb_cStat, "writable?", rb_stat_w, 0);
6919 rb_define_method(rb_cStat, "writable_real?", rb_stat_W, 0);
6920 rb_define_method(rb_cStat, "world_writable?", rb_stat_ww, 0);
6921 rb_define_method(rb_cStat, "executable?", rb_stat_x, 0);
6922 rb_define_method(rb_cStat, "executable_real?", rb_stat_X, 0);
6923 rb_define_method(rb_cStat, "file?", rb_stat_f, 0);
6924 rb_define_method(rb_cStat, "zero?", rb_stat_z, 0);
6925 rb_define_method(rb_cStat, "size?", rb_stat_s, 0);
6926 rb_define_method(rb_cStat, "owned?", rb_stat_owned, 0);
6927 rb_define_method(rb_cStat, "grpowned?", rb_stat_grpowned, 0);
6929 rb_define_method(rb_cStat, "pipe?", rb_stat_p, 0);
6930 rb_define_method(rb_cStat, "symlink?", rb_stat_l, 0);
6931 rb_define_method(rb_cStat, "socket?", rb_stat_S, 0);
6933 rb_define_method(rb_cStat, "blockdev?", rb_stat_b, 0);
6934 rb_define_method(rb_cStat, "chardev?", rb_stat_c, 0);
6936 rb_define_method(rb_cStat, "setuid?", rb_stat_suid, 0);
6937 rb_define_method(rb_cStat, "setgid?", rb_stat_sgid, 0);
6938 rb_define_method(rb_cStat, "sticky?", rb_stat_sticky, 0);