Ruby: file.c Source File

Ruby 3.2.5p208 (2024-07-26 revision 31d0f1a2e7dbfb60731d1f05b868e1d578cda493)

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