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