Ruby 4.1.0dev (2026-03-01 revision 19b636d3ecc8a824437e0d6abd7fe0c24b594ce0)
dir.c (19b636d3ecc8a824437e0d6abd7fe0c24b594ce0)
1/**********************************************************************
2
3 dir.c -
4
5 $Author$
6 created at: Wed Jan 5 09:51:01 JST 1994
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#include <ctype.h>
17#include <errno.h>
18#include <sys/types.h>
19#include <sys/stat.h>
20
21#ifdef HAVE_UNISTD_H
22#include <unistd.h>
23#endif
24
25#ifndef USE_OPENDIR_AT
26# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD) && \
27 defined(HAVE_OPENAT) && defined(HAVE_FSTATAT)
28# define USE_OPENDIR_AT 1
29# else
30# define USE_OPENDIR_AT 0
31# endif
32#endif
33
34#ifdef HAVE_FCNTL_H
35# include <fcntl.h>
36#endif
37
38#ifndef O_CLOEXEC
39# define O_CLOEXEC 0
40#endif
41
42#undef HAVE_DIRENT_NAMLEN
43#if defined HAVE_DIRENT_H && !defined _WIN32
44# include <dirent.h>
45# define NAMLEN(dirent) strlen((dirent)->d_name)
46#elif defined HAVE_DIRECT_H && !defined _WIN32
47# include <direct.h>
48# define NAMLEN(dirent) strlen((dirent)->d_name)
49#else
50# define dirent direct
51# define NAMLEN(dirent) (dirent)->d_namlen
52# define HAVE_DIRENT_NAMLEN 1
53# ifdef HAVE_SYS_NDIR_H
54# include <sys/ndir.h>
55# endif
56# ifdef HAVE_SYS_DIR_H
57# include <sys/dir.h>
58# endif
59# ifdef HAVE_NDIR_H
60# include <ndir.h>
61# endif
62# ifdef _WIN32
63# include "win32/dir.h"
64# endif
65#endif
66
67#ifndef HAVE_STDLIB_H
68char *getenv();
69#endif
70
71#ifndef HAVE_STRING_H
72char *strchr(char*,char);
73#endif
74
75#ifdef HAVE_SYS_ATTR_H
76#include <sys/attr.h>
77#endif
78
79#define USE_NAME_ON_FS_REAL_BASENAME 1 /* platform dependent APIs to
80 * get real basenames */
81#define USE_NAME_ON_FS_BY_FNMATCH 2 /* select the matching
82 * basename by fnmatch */
83
84#ifdef HAVE_GETATTRLIST
85# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
86# define RUP32(size) ((size)+3/4)
87# define SIZEUP32(type) RUP32(sizeof(type))
88#elif defined _WIN32
89# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
90#elif defined DOSISH
91# define USE_NAME_ON_FS USE_NAME_ON_FS_BY_FNMATCH
92#else
93# define USE_NAME_ON_FS 0
94#endif
95
96#ifdef __APPLE__
97# define NORMALIZE_UTF8PATH 1
98# include <sys/param.h>
99# include <sys/mount.h>
100# include <sys/vnode.h>
101#else
102# define NORMALIZE_UTF8PATH 0
103#endif
104
105#include "encindex.h"
106#include "id.h"
107#include "internal.h"
108#include "internal/array.h"
109#include "internal/dir.h"
110#include "internal/encoding.h"
111#include "internal/error.h"
112#include "internal/file.h"
113#include "internal/gc.h"
114#include "internal/io.h"
115#include "internal/object.h"
116#include "internal/imemo.h"
117#include "internal/vm.h"
118#include "ruby/encoding.h"
119#include "ruby/ruby.h"
120#include "ruby/thread.h"
121#include "ruby/util.h"
122#include "builtin.h"
123
124#ifndef AT_FDCWD
125# define AT_FDCWD -1
126#endif
127
128#define vm_initialized rb_cThread
129
130/* define system APIs */
131#ifdef _WIN32
132# undef chdir
133# define chdir(p) rb_w32_uchdir(p)
134# undef mkdir
135# define mkdir(p, m) rb_w32_umkdir((p), (m))
136# undef rmdir
137# define rmdir(p) rb_w32_urmdir(p)
138# undef opendir
139# define opendir(p) rb_w32_uopendir(p)
140# define ruby_getcwd() rb_w32_ugetcwd(NULL, 0)
141# define IS_WIN32 1
142#else
143# define IS_WIN32 0
144#endif
145
146#ifdef HAVE_GETATTRLIST
147struct getattrlist_args {
148 const char *path;
149 int fd;
150 struct attrlist *list;
151 void *buf;
152 size_t size;
153 unsigned int options;
154};
155
156# define GETATTRLIST_ARGS(list_, buf_, options_) (struct getattrlist_args) \
157 {.list = list_, .buf = buf_, .size = sizeof(buf_), .options = options_}
158
159static void *
160nogvl_getattrlist(void *args)
161{
162 struct getattrlist_args *arg = args;
163 return (void *)(VALUE)getattrlist(arg->path, arg->list, arg->buf, arg->size, arg->options);
164}
165
166static int
167gvl_getattrlist(struct getattrlist_args *args, const char *path)
168{
169 args->path = path;
170 return IO_WITHOUT_GVL_INT(nogvl_getattrlist, args);
171}
172
173# ifdef HAVE_FGETATTRLIST
174static void *
175nogvl_fgetattrlist(void *args)
176{
177 struct getattrlist_args *arg = args;
178 return (void *)(VALUE)fgetattrlist(arg->fd, arg->list, arg->buf, arg->size, arg->options);
179}
180
181static int
182gvl_fgetattrlist(struct getattrlist_args *args, int fd)
183{
184 args->fd = fd;
185 return IO_WITHOUT_GVL_INT(nogvl_fgetattrlist, args);
186}
187# endif
188#endif
189
190#if NORMALIZE_UTF8PATH
191# if defined HAVE_FGETATTRLIST || !defined HAVE_GETATTRLIST
192# define need_normalization(dirp, path) need_normalization(dirp)
193# else
194# define need_normalization(dirp, path) need_normalization(path)
195# endif
196static inline int
197need_normalization(DIR *dirp, const char *path)
198{
199# if defined HAVE_FGETATTRLIST || defined HAVE_GETATTRLIST
200 u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
201 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
202 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, 0);
203# if defined HAVE_FGETATTRLIST
204 int ret = gvl_fgetattrlist(&args, dirfd(dirp));
205# else
206 int ret = gvl_getattrlist(&args, path);
207# endif
208 if (!ret) {
209 const fsobj_tag_t *tag = (void *)(attrbuf+1);
210 switch (*tag) {
211 case VT_HFS:
212 case VT_CIFS:
213 return TRUE;
214 }
215 }
216# endif
217 return FALSE;
218}
219
220static inline int
221has_nonascii(const char *ptr, size_t len)
222{
223 while (len > 0) {
224 if (!ISASCII(*ptr)) return 1;
225 ptr++;
226 --len;
227 }
228 return 0;
229}
230
231# define IF_NORMALIZE_UTF8PATH(something) something
232#else
233# define IF_NORMALIZE_UTF8PATH(something) /* nothing */
234#endif
235
236#if defined(IFTODT) && defined(DT_UNKNOWN)
237# define EMULATE_IFTODT 0
238#else
239# define EMULATE_IFTODT 1
240#endif
241
242#if EMULATE_IFTODT
243# define IFTODT(m) (((m) & S_IFMT) / ((~S_IFMT & (S_IFMT-1)) + 1))
244#endif
245
246typedef enum {
247#if !EMULATE_IFTODT
248 path_exist = DT_UNKNOWN,
249 path_directory = DT_DIR,
250 path_regular = DT_REG,
251 path_symlink = DT_LNK,
252#else
253 path_exist,
254 path_directory = IFTODT(S_IFDIR),
255 path_regular = IFTODT(S_IFREG),
256 path_symlink = IFTODT(S_IFLNK),
257#endif
258 path_noent = -1,
259 path_unknown = -2
260} rb_pathtype_t;
261
262#define FNM_NOESCAPE 0x01
263#define FNM_PATHNAME 0x02
264#define FNM_DOTMATCH 0x04
265#define FNM_CASEFOLD 0x08
266#define FNM_EXTGLOB 0x10
267#if CASEFOLD_FILESYSTEM
268#define FNM_SYSCASE FNM_CASEFOLD
269#else
270#define FNM_SYSCASE 0
271#endif
272#ifdef _WIN32
273#define FNM_SHORTNAME 0x20
274#else
275#define FNM_SHORTNAME 0
276#endif
277#define FNM_GLOB_NOSORT 0x40
278#define FNM_GLOB_SKIPDOT 0x80
279
280#define FNM_NOMATCH 1
281#define FNM_ERROR 2
282
283# define Next(p, e, enc) ((p)+ rb_enc_mbclen((p), (e), (enc)))
284# define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
285
286static char *
287bracket(
288 const char *p, /* pattern (next to '[') */
289 const char *pend,
290 const char *s, /* string */
291 const char *send,
292 int flags,
293 rb_encoding *enc)
294{
295 const int nocase = flags & FNM_CASEFOLD;
296 const int escape = !(flags & FNM_NOESCAPE);
297 unsigned int c1, c2;
298 int r;
299 int ok = 0, not = 0;
300
301 if (p >= pend) return NULL;
302 if (*p == '!' || *p == '^') {
303 not = 1;
304 p++;
305 }
306
307 while (*p != ']') {
308 const char *t1 = p;
309 if (escape && *t1 == '\\')
310 t1++;
311 if (!*t1)
312 return NULL;
313 p = t1 + (r = rb_enc_mbclen(t1, pend, enc));
314 if (p >= pend) return NULL;
315 if (p[0] == '-' && p[1] != ']') {
316 const char *t2 = p + 1;
317 int r2;
318 if (escape && *t2 == '\\')
319 t2++;
320 if (!*t2)
321 return NULL;
322 p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc));
323 if (ok) continue;
324 if ((r <= (send-s) && memcmp(t1, s, r) == 0) ||
325 (r2 <= (send-s) && memcmp(t2, s, r2) == 0)) {
326 ok = 1;
327 continue;
328 }
329 c1 = rb_enc_codepoint(s, send, enc);
330 if (nocase) c1 = rb_enc_toupper(c1, enc);
331 c2 = rb_enc_codepoint(t1, pend, enc);
332 if (nocase) c2 = rb_enc_toupper(c2, enc);
333 if (c1 < c2) continue;
334 c2 = rb_enc_codepoint(t2, pend, enc);
335 if (nocase) c2 = rb_enc_toupper(c2, enc);
336 if (c1 > c2) continue;
337 }
338 else {
339 if (ok) continue;
340 if (r <= (send-s) && memcmp(t1, s, r) == 0) {
341 ok = 1;
342 continue;
343 }
344 if (!nocase) continue;
345 c1 = rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc);
346 c2 = rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc);
347 if (c1 != c2) continue;
348 }
349 ok = 1;
350 }
351
352 return ok == not ? NULL : (char *)p + 1;
353}
354
355/* If FNM_PATHNAME is set, only path element will be matched. (up to '/' or '\0')
356 Otherwise, entire string will be matched.
357 End marker itself won't be compared.
358 And if function succeeds, *pcur reaches end marker.
359*/
360#define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p))
361#define ISEND(p) (!*(p) || (pathname && *(p) == '/'))
362#define RETURN(val) return *pcur = p, *scur = s, (val);
363
364static int
365fnmatch_helper(
366 const char **pcur, /* pattern */
367 const char **scur, /* string */
368 int flags,
369 rb_encoding *enc)
370{
371 const int period = !(flags & FNM_DOTMATCH);
372 const int pathname = flags & FNM_PATHNAME;
373 const int escape = !(flags & FNM_NOESCAPE);
374 const int nocase = flags & FNM_CASEFOLD;
375
376 const char *ptmp = 0;
377 const char *stmp = 0;
378
379 const char *p = *pcur;
380 const char *pend = p + strlen(p);
381 const char *s = *scur;
382 const char *send = s + strlen(s);
383
384 int r;
385
386 if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
387 RETURN(FNM_NOMATCH);
388
389 while (1) {
390 switch (*p) {
391 case '*':
392 do { p++; } while (*p == '*');
393 if (ISEND(UNESCAPE(p))) {
394 p = UNESCAPE(p);
395 RETURN(0);
396 }
397 if (ISEND(s))
398 RETURN(FNM_NOMATCH);
399 ptmp = p;
400 stmp = s;
401 continue;
402
403 case '?':
404 if (ISEND(s))
405 RETURN(FNM_NOMATCH);
406 p++;
407 Inc(s, send, enc);
408 continue;
409
410 case '[': {
411 const char *t;
412 if (ISEND(s))
413 RETURN(FNM_NOMATCH);
414 if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) {
415 p = t;
416 Inc(s, send, enc);
417 continue;
418 }
419 goto failed;
420 }
421 }
422
423 /* ordinary */
424 p = UNESCAPE(p);
425 if (ISEND(s))
426 RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
427 if (ISEND(p))
428 goto failed;
429 r = rb_enc_precise_mbclen(p, pend, enc);
430 if (!MBCLEN_CHARFOUND_P(r))
431 goto failed;
432 if (r <= (send-s) && memcmp(p, s, r) == 0) {
433 p += r;
434 s += r;
435 continue;
436 }
437 if (!nocase) goto failed;
438 if (rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc) !=
439 rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc))
440 goto failed;
441 p += r;
442 Inc(s, send, enc);
443 continue;
444
445 failed: /* try next '*' position */
446 if (ptmp && stmp) {
447 p = ptmp;
448 Inc(stmp, send, enc); /* !ISEND(*stmp) */
449 s = stmp;
450 continue;
451 }
452 RETURN(FNM_NOMATCH);
453 }
454}
455
456static int
457fnmatch(
458 const char *pattern,
459 rb_encoding *enc,
460 const char *string,
461 int flags)
462{
463 const char *p = pattern;
464 const char *s = string;
465 const char *send = s + strlen(string);
466 const int period = !(flags & FNM_DOTMATCH);
467 const int pathname = flags & FNM_PATHNAME;
468
469 const char *ptmp = 0;
470 const char *stmp = 0;
471
472 if (pathname) {
473 while (1) {
474 if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
475 do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
476 ptmp = p;
477 stmp = s;
478 }
479 if (fnmatch_helper(&p, &s, flags, enc) == 0) {
480 while (*s && *s != '/') Inc(s, send, enc);
481 if (*p && *s) {
482 p++;
483 s++;
484 continue;
485 }
486 if (!*p && !*s)
487 return 0;
488 }
489 /* failed : try next recursion */
490 if (ptmp && stmp && !(period && *stmp == '.')) {
491 while (*stmp && *stmp != '/') Inc(stmp, send, enc);
492 if (*stmp) {
493 p = ptmp;
494 stmp++;
495 s = stmp;
496 continue;
497 }
498 }
499 return FNM_NOMATCH;
500 }
501 }
502 else
503 return fnmatch_helper(&p, &s, flags, enc);
505
507static VALUE sym_directory, sym_link, sym_file, sym_unknown;
508
509#if defined(DT_BLK) || defined(S_IFBLK)
510static VALUE sym_block_device;
511#endif
512#if defined(DT_CHR) || defined(S_IFCHR)
513static VALUE sym_character_device;
514#endif
515#if defined(DT_FIFO) || defined(S_IFIFO)
516static VALUE sym_fifo;
517#endif
518#if defined(DT_SOCK) || defined(S_IFSOCK)
519static VALUE sym_socket;
520#endif
521
522struct dir_data {
523 DIR *dir;
524 const VALUE path;
525 rb_encoding *enc;
526};
527
528static void
529dir_free(void *ptr)
530{
531 struct dir_data *dir = ptr;
532
533 if (dir->dir) closedir(dir->dir);
534}
535
536RUBY_REFERENCES(dir_refs) = {
537 RUBY_REF_EDGE(struct dir_data, path),
538 RUBY_REF_END
539};
540
541static const rb_data_type_t dir_data_type = {
542 "dir",
543 {
544 RUBY_REFS_LIST_PTR(dir_refs),
545 dir_free,
546 NULL, // Nothing allocated externally, so don't need a memsize function
547 },
548 0, NULL, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
549};
550
551static VALUE dir_close(VALUE);
552
553static VALUE
554dir_s_alloc(VALUE klass)
555{
556 struct dir_data *dirp;
557 VALUE obj = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dirp);
558
559 dirp->dir = NULL;
560 RB_OBJ_WRITE(obj, &dirp->path, Qnil);
561 dirp->enc = NULL;
562
563 return obj;
564}
565
566static void *
567nogvl_opendir(void *ptr)
568{
569 const char *path = ptr;
570
571 return opendir(path);
572}
573
574static DIR *
575opendir_without_gvl(const char *path)
576{
577 if (vm_initialized) {
578 union { const void *in; void *out; } u;
579
580 u.in = path;
581
582 return IO_WITHOUT_GVL(nogvl_opendir, u.out);
583 }
584 else
585 return opendir(path);
586}
587
588static void
589close_dir_data(struct dir_data *dp)
590{
591 if (dp->dir) {
592 if (closedir(dp->dir) < 0) {
593 dp->dir = NULL;
594 rb_sys_fail("closedir");
595 }
596 dp->dir = NULL;
597 }
598}
599
600static void
601check_closedir(DIR *dirp)
602{
603 if (closedir(dirp) < 0)
604 rb_sys_fail("closedir");
605}
606
607static VALUE
608dir_initialize(rb_execution_context_t *ec, VALUE dir, VALUE dirname, VALUE enc)
609{
610 struct dir_data *dp;
611 VALUE orig;
612 const char *path;
613 rb_encoding *fsenc = NIL_P(enc) ? rb_filesystem_encoding() : rb_to_encoding(enc);
614
615 FilePathValue(dirname);
616 orig = rb_str_dup_frozen(dirname);
617 dirname = rb_str_encode_ospath(dirname);
618 dirname = rb_str_dup_frozen(dirname);
619
620 TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp);
621 close_dir_data(dp);
622 RB_OBJ_WRITE(dir, &dp->path, Qnil);
623 dp->enc = fsenc;
624 path = RSTRING_PTR(dirname);
625 dp->dir = opendir_without_gvl(path);
626 if (dp->dir == NULL) {
627 int e = errno;
628 if (rb_gc_for_fd(e)) {
629 dp->dir = opendir_without_gvl(path);
630 }
631#ifdef HAVE_GETATTRLIST
632 else if (e == EIO) {
633 u_int32_t attrbuf[1];
634 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0};
635 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
636 if (gvl_getattrlist(&args, path) == 0) {
637 dp->dir = opendir_without_gvl(path);
638 }
639 }
640#endif
641 if (dp->dir == NULL) {
642 RB_GC_GUARD(dirname);
643 rb_syserr_fail_path(e, orig);
644 }
645 }
646 RB_OBJ_WRITE(dir, &dp->path, orig);
647
648 return dir;
649}
650
651static VALUE
652dir_s_open(rb_execution_context_t *ec, VALUE klass, VALUE dirname, VALUE enc)
653{
654 struct dir_data *dp;
655 VALUE dir = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dp);
656
657 dir_initialize(ec, dir, dirname, enc);
658
659 return dir;
660}
661
662static VALUE
663dir_s_close(rb_execution_context_t *ec, VALUE klass, VALUE dir)
664{
665 return dir_close(dir);
666}
667
668# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD)
669static void *
670nogvl_fdopendir(void *fd)
671{
672 return fdopendir((int)(VALUE)fd);
673}
674
675/*
676 * call-seq:
677 * Dir.for_fd(fd) -> dir
678 *
679 * Returns a new \Dir object representing the directory specified by the given
680 * integer directory file descriptor +fd+:
681 *
682 * d0 = Dir.new('..')
683 * d1 = Dir.for_fd(d0.fileno)
684 *
685 * Note that the returned +d1+ does not have an associated path:
686 *
687 * d0.path # => '..'
688 * d1.path # => nil
689 *
690 * This method uses the
691 * {fdopendir()}[https://www.man7.org/linux/man-pages/man3/fdopendir.3p.html]
692 * function defined by POSIX 2008;
693 * the method is not implemented on non-POSIX platforms (raises NotImplementedError).
694 */
695static VALUE
696dir_s_for_fd(VALUE klass, VALUE fd)
697{
698 struct dir_data *dp;
699 VALUE dir = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dp);
700
701 if (!(dp->dir = IO_WITHOUT_GVL(nogvl_fdopendir, (void *)(VALUE)NUM2INT(fd)))) {
702 rb_sys_fail("fdopendir");
704 }
705
706 RB_OBJ_WRITE(dir, &dp->path, Qnil);
707 return dir;
708}
709#else
710#define dir_s_for_fd rb_f_notimplement
711#endif
712
713NORETURN(static void dir_closed(void));
714
715static void
716dir_closed(void)
717{
718 rb_raise(rb_eIOError, "closed directory");
719}
720
721static struct dir_data *
722dir_get(VALUE dir)
723{
724 rb_check_frozen(dir);
725 return rb_check_typeddata(dir, &dir_data_type);
726}
727
728static struct dir_data *
729dir_check(VALUE dir)
730{
731 struct dir_data *dirp = dir_get(dir);
732 if (!dirp->dir) dir_closed();
733 return dirp;
734}
735
736#define GetDIR(obj, dirp) ((dirp) = dir_check(obj))
737
738
739/*
740 * call-seq:
741 * inspect -> string
742 *
743 * Returns a string description of +self+:
744 *
745 * Dir.new('example').inspect # => "#<Dir:example>"
746 *
747 */
748static VALUE
749dir_inspect(VALUE dir)
750{
751 struct dir_data *dirp;
752
753 TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
754 if (!NIL_P(dirp->path)) {
755 VALUE str = rb_str_new_cstr("#<");
757 rb_str_cat2(str, ":");
758 rb_str_append(str, dirp->path);
759 rb_str_cat2(str, ">");
760 return str;
761 }
762 return rb_funcallv(dir, idTo_s, 0, 0);
763}
764
765/* Workaround for Solaris 10 that does not have dirfd.
766 Note: Solaris 11 (POSIX.1-2008 compliant) has dirfd(3C).
767 */
768#if defined(__sun) && !defined(HAVE_DIRFD)
769# if defined(HAVE_DIR_D_FD)
770# define dirfd(x) ((x)->d_fd)
771# define HAVE_DIRFD 1
772# elif defined(HAVE_DIR_DD_FD)
773# define dirfd(x) ((x)->dd_fd)
774# define HAVE_DIRFD 1
775# endif
776#endif
777
778#ifdef HAVE_DIRFD
779/*
780 * call-seq:
781 * fileno -> integer
782 *
783 * Returns the file descriptor used in <em>dir</em>.
784 *
785 * d = Dir.new('..')
786 * d.fileno # => 8
787 *
788 * This method uses the
789 * {dirfd()}[https://www.man7.org/linux/man-pages/man3/dirfd.3.html]
790 * function defined by POSIX 2008;
791 * the method is not implemented on non-POSIX platforms (raises NotImplementedError).
792 */
793static VALUE
794dir_fileno(VALUE dir)
795{
796 struct dir_data *dirp;
797 int fd;
798
799 GetDIR(dir, dirp);
800 fd = dirfd(dirp->dir);
801 if (fd == -1)
802 rb_sys_fail("dirfd");
803 return INT2NUM(fd);
804}
805#else
806#define dir_fileno rb_f_notimplement
807#endif
808
809/*
810 * call-seq:
811 * path -> string or nil
812 *
813 * Returns the +dirpath+ string that was used to create +self+
814 * (or +nil+ if created by method Dir.for_fd):
815 *
816 * Dir.new('example').path # => "example"
817 *
818 */
819static VALUE
820dir_path(VALUE dir)
821{
822 struct dir_data *dirp;
823
824 TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
825 if (NIL_P(dirp->path)) return Qnil;
826 return rb_str_dup(dirp->path);
827}
828
829#if defined _WIN32
830static int
831fundamental_encoding_p(rb_encoding *enc)
832{
833 switch (rb_enc_to_index(enc)) {
834 case ENCINDEX_ASCII_8BIT:
835 case ENCINDEX_US_ASCII:
836 case ENCINDEX_UTF_8:
837 return TRUE;
838 default:
839 return FALSE;
840 }
841}
842# define READDIR(dir, enc) rb_w32_readdir((dir), (enc))
843# define READDIR_NOGVL READDIR
844#else
845NORETURN(static void *sys_failure(void *function));
846static void *
847sys_failure(void *function)
848{
849 rb_sys_fail(function);
850}
851
852static void *
853nogvl_readdir(void *dir)
854{
855 rb_errno_set(0);
856 if ((dir = readdir(dir)) == NULL) {
857 if (rb_errno())
858 rb_thread_call_with_gvl(sys_failure, (void *)"readdir");
859 }
860 return dir;
861}
862
863# define READDIR(dir, enc) IO_WITHOUT_GVL(nogvl_readdir, (void *)(dir))
864# define READDIR_NOGVL(dir, enc) nogvl_readdir((dir))
865#endif
866
867/* safe to use without GVL */
868static int
869to_be_skipped(const struct dirent *dp)
870{
871 const char *name = dp->d_name;
872 if (name[0] != '.') return FALSE;
873#ifdef HAVE_DIRENT_NAMLEN
874 switch (NAMLEN(dp)) {
875 case 2:
876 if (name[1] != '.') return FALSE;
877 case 1:
878 return TRUE;
879 default:
880 break;
881 }
882#else
883 if (!name[1]) return TRUE;
884 if (name[1] != '.') return FALSE;
885 if (!name[2]) return TRUE;
886#endif
887 return FALSE;
888}
889
890/*
891 * call-seq:
892 * read -> string or nil
893 *
894 * Reads and returns the next entry name from +self+;
895 * returns +nil+ if at end-of-stream;
896 * see {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like]:
897 *
898 * dir = Dir.new('example')
899 * dir.read # => "."
900 * dir.read # => ".."
901 * dir.read # => "config.h"
902 *
903 */
904static VALUE
905dir_read(VALUE dir)
906{
907 struct dir_data *dirp;
908 struct dirent *dp;
909
910 GetDIR(dir, dirp);
911 rb_errno_set(0);
912 if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
913 return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc);
914 }
915 else {
916 int e = errno;
917 if (e != 0) rb_syserr_fail(e, 0);
918 return Qnil; /* end of stream */
919 }
921
922struct dir_entry_args {
923 struct dir_data *dirp;
924 struct dirent *dp;
925};
926
927static VALUE dir_each_entry(VALUE, VALUE (*)(VALUE, VALUE, struct dir_entry_args *), VALUE, int);
928
929static VALUE
930dir_yield(VALUE arg, VALUE path, struct dir_entry_args *_unused)
931{
932 return rb_yield(path);
933}
934
935static int do_lstat(int fd, const char *path, struct stat *pst, int flags, rb_encoding *enc);
936
937static VALUE
938dir_yield_with_type(VALUE arg, VALUE path, struct dir_entry_args *dir_entry)
939{
940 VALUE type;
941 switch (dir_entry->dp->d_type) {
942#ifdef DT_BLK
943 case DT_BLK:
944 type = sym_block_device;
945 break;
946#endif
947#ifdef DT_CHR
948 case DT_CHR:
949 type = sym_character_device;
950 break;
951#endif
952 case DT_DIR:
953 type = sym_directory;
954 break;
955#ifdef DT_FIFO
956 case DT_FIFO:
957 type = sym_fifo;
958 break;
959#endif
960 case DT_LNK:
961 type = sym_link;
962 break;
963 case DT_REG:
964 type = sym_file;
965 break;
966#ifdef DT_SOCK
967 case DT_SOCK:
968 type = sym_socket;
969 break;
970#endif
971 default:
972 type = sym_unknown;
973 break;
974 }
975
976#ifdef HAVE_DIRFD
977 if (RUBY_DEBUG || RB_UNLIKELY(type == sym_unknown)) {
978 struct stat st;
979 if (do_lstat(dirfd(dir_entry->dirp->dir), dir_entry->dp->d_name, &st, 0, rb_filesystem_encoding()) == 0) {
980 switch (st.st_mode & S_IFMT) {
981 case S_IFDIR:
982 type = sym_directory;
983 break;
984 case S_IFLNK:
985 type = sym_link;
986 break;
987 case S_IFREG:
988 type = sym_file;
989 break;
990#ifdef S_IFSOCK
991 case S_IFSOCK:
992 type = sym_socket;
993 break;
994#endif
995#ifdef S_IFIFO
996 case S_IFIFO:
997 type = sym_fifo;
998 break;
999#endif
1000#ifdef S_IFBLK
1001 case S_IFBLK:
1002 type = sym_block_device;
1003 break;
1004#endif
1005#ifdef S_IFCHR
1006 case S_IFCHR:
1007 type = sym_character_device;
1008 break;
1009#endif
1010 default:
1011 break;
1012 }
1013 }
1014 }
1015#endif // HAVE_DIRFD
1016
1017 if (NIL_P(arg)) {
1018 return rb_yield_values(2, path, type);
1019 }
1020 else {
1021 return rb_ary_push(arg, rb_assoc_new(path, type));
1022 }
1023}
1024
1025/*
1026 * call-seq:
1027 * each {|entry_name| ... } -> self
1028 *
1029 * Calls the block with each entry name in +self+:
1030 *
1031 * Dir.new('example').each {|entry_name| p entry_name }
1032 *
1033 * Output:
1034
1035 * "."
1036 * ".."
1037 * "config.h"
1038 * "lib"
1039 * "main.rb"
1040 *
1041 * With no block given, returns an Enumerator.
1042 *
1043 */
1044static VALUE
1045dir_each(VALUE dir)
1046{
1047 RETURN_ENUMERATOR(dir, 0, 0);
1048 return dir_each_entry(dir, dir_yield, Qnil, FALSE);
1049}
1050
1051static VALUE
1052dir_each_entry(VALUE dir, VALUE (*each)(VALUE, VALUE, struct dir_entry_args *), VALUE arg, int children_only)
1053{
1054 struct dir_data *dirp;
1055 struct dirent *dp;
1056 IF_NORMALIZE_UTF8PATH(int norm_p);
1057
1058 GetDIR(dir, dirp);
1059 rewinddir(dirp->dir);
1060 IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp->dir, RSTRING_PTR(dirp->path)));
1061 while ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
1062 const char *name = dp->d_name;
1063 size_t namlen = NAMLEN(dp);
1064 VALUE path;
1065
1066 if (children_only && name[0] == '.') {
1067 if (namlen == 1) continue; /* current directory */
1068 if (namlen == 2 && name[1] == '.') continue; /* parent directory */
1069 }
1070#if NORMALIZE_UTF8PATH
1071 if (norm_p && has_nonascii(name, namlen) &&
1072 !NIL_P(path = rb_str_normalize_ospath(name, namlen))) {
1073 path = rb_external_str_with_enc(path, dirp->enc);
1074 }
1075 else
1076#endif
1077 path = rb_external_str_new_with_enc(name, namlen, dirp->enc);
1078 struct dir_entry_args each_args = {
1079 .dirp = dirp,
1080 .dp = dp,
1081 };
1082 (*each)(arg, path, &each_args);
1083 }
1084 return dir;
1085}
1086
1087#ifdef HAVE_TELLDIR
1088/*
1089 * call-seq:
1090 * tell -> integer
1091 *
1092 * Returns the current position of +self+;
1093 * see {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like]:
1094 *
1095 * dir = Dir.new('example')
1096 * dir.tell # => 0
1097 * dir.read # => "."
1098 * dir.tell # => 1
1099 *
1100 */
1101static VALUE
1102dir_tell(VALUE dir)
1103{
1104 struct dir_data *dirp;
1105 long pos;
1106
1107 GetDIR(dir, dirp);
1108 if((pos = telldir(dirp->dir)) < 0)
1109 rb_sys_fail("telldir");
1110 return rb_int2inum(pos);
1111}
1112#else
1113#define dir_tell rb_f_notimplement
1114#endif
1115
1116#ifdef HAVE_SEEKDIR
1117/*
1118 * call-seq:
1119 * seek(position) -> self
1120 *
1121 * Sets the position in +self+ and returns +self+.
1122 * The value of +position+ should have been returned from an earlier call to #tell;
1123 * if not, the return values from subsequent calls to #read are unspecified.
1124 *
1125 * See {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like].
1126 *
1127 * Examples:
1128 *
1129 * dir = Dir.new('example')
1130 * dir.pos # => 0
1131 * dir.seek(3) # => #<Dir:example>
1132 * dir.pos # => 3
1133 * dir.seek(30) # => #<Dir:example>
1134 * dir.pos # => 5
1135 *
1136 */
1137static VALUE
1138dir_seek(VALUE dir, VALUE pos)
1139{
1140 struct dir_data *dirp;
1141 long p = NUM2LONG(pos);
1142
1143 GetDIR(dir, dirp);
1144 seekdir(dirp->dir, p);
1145 return dir;
1146}
1147#else
1148#define dir_seek rb_f_notimplement
1149#endif
1150
1151#ifdef HAVE_SEEKDIR
1152/*
1153 * call-seq:
1154 * pos = position -> integer
1155 *
1156 * Sets the position in +self+ and returns +position+.
1157 * The value of +position+ should have been returned from an earlier call to #tell;
1158 * if not, the return values from subsequent calls to #read are unspecified.
1159 *
1160 * See {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like].
1161 *
1162 * Examples:
1163 *
1164 * dir = Dir.new('example')
1165 * dir.pos # => 0
1166 * dir.pos = 3 # => 3
1167 * dir.pos # => 3
1168 * dir.pos = 30 # => 30
1169 * dir.pos # => 5
1170 *
1171 */
1172static VALUE
1173dir_set_pos(VALUE dir, VALUE pos)
1174{
1175 dir_seek(dir, pos);
1176 return pos;
1177}
1178#else
1179#define dir_set_pos rb_f_notimplement
1180#endif
1181
1182/*
1183 * call-seq:
1184 * rewind -> self
1185 *
1186 * Sets the position in +self+ to zero;
1187 * see {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like]:
1188 *
1189 * dir = Dir.new('example')
1190 * dir.read # => "."
1191 * dir.read # => ".."
1192 * dir.pos # => 2
1193 * dir.rewind # => #<Dir:example>
1194 * dir.pos # => 0
1195 *
1196 */
1197static VALUE
1198dir_rewind(VALUE dir)
1199{
1200 struct dir_data *dirp;
1201
1202 GetDIR(dir, dirp);
1203 rewinddir(dirp->dir);
1204 return dir;
1205}
1206
1207/*
1208 * call-seq:
1209 * close -> nil
1210 *
1211 * Closes the stream in +self+, if it is open, and returns +nil+;
1212 * ignored if +self+ is already closed:
1213 *
1214 * dir = Dir.new('example')
1215 * dir.read # => "."
1216 * dir.close # => nil
1217 * dir.close # => nil
1218 * dir.read # Raises IOError.
1219 *
1220 */
1221static VALUE
1222dir_close(VALUE dir)
1223{
1224 struct dir_data *dirp;
1225
1226 dirp = dir_get(dir);
1227 if (!dirp->dir) return Qnil;
1228 close_dir_data(dirp);
1229
1230 return Qnil;
1231}
1232
1233static void *
1234nogvl_chdir(void *ptr)
1235{
1236 const char *path = ptr;
1237
1238 return (void *)(VALUE)chdir(path);
1239}
1240
1241static void
1242dir_chdir0(VALUE path)
1243{
1244 if (IO_WITHOUT_GVL_INT(nogvl_chdir, (void*)RSTRING_PTR(path)) < 0)
1245 rb_sys_fail_path(path);
1246}
1247
1248static struct {
1249 VALUE thread;
1250 VALUE path;
1251 int line;
1252 int blocking;
1253} chdir_lock = {
1254 .blocking = 0, .thread = Qnil,
1255 .path = Qnil, .line = 0,
1256};
1257
1258static void
1259chdir_enter(void)
1260{
1261 if (chdir_lock.blocking == 0) {
1262 chdir_lock.path = rb_source_location(&chdir_lock.line);
1263 }
1264 chdir_lock.blocking++;
1265 if (NIL_P(chdir_lock.thread)) {
1266 chdir_lock.thread = rb_thread_current();
1267 }
1268}
1269
1270static void
1271chdir_leave(void)
1272{
1273 chdir_lock.blocking--;
1274 if (chdir_lock.blocking == 0) {
1275 chdir_lock.thread = Qnil;
1276 chdir_lock.path = Qnil;
1277 chdir_lock.line = 0;
1278 }
1279}
1280
1281static int
1282chdir_alone_block_p(void)
1283{
1284 int block_given = rb_block_given_p();
1285 if (chdir_lock.blocking > 0) {
1286 if (rb_thread_current() != chdir_lock.thread)
1287 rb_raise(rb_eRuntimeError, "conflicting chdir during another chdir block");
1288 if (!block_given) {
1289 if (!NIL_P(chdir_lock.path)) {
1290 rb_warn("conflicting chdir during another chdir block\n"
1291 "%" PRIsVALUE ":%d: note: previous chdir was here",
1292 chdir_lock.path, chdir_lock.line);
1293 }
1294 else {
1295 rb_warn("conflicting chdir during another chdir block");
1296 }
1297 }
1298 }
1299 return block_given;
1301
1302struct chdir_data {
1303 VALUE old_path, new_path;
1304 int done;
1305 bool yield_path;
1306};
1307
1308static VALUE
1309chdir_yield(VALUE v)
1310{
1311 struct chdir_data *args = (void *)v;
1312 dir_chdir0(args->new_path);
1313 args->done = TRUE;
1314 chdir_enter();
1315 return args->yield_path ? rb_yield(args->new_path) : rb_yield_values2(0, NULL);
1316}
1317
1318static VALUE
1319chdir_restore(VALUE v)
1320{
1321 struct chdir_data *args = (void *)v;
1322 if (args->done) {
1323 chdir_leave();
1324 dir_chdir0(args->old_path);
1325 }
1326 return Qnil;
1327}
1328
1329static VALUE
1330chdir_path(VALUE path, bool yield_path)
1331{
1332 if (chdir_alone_block_p()) {
1333 struct chdir_data args;
1334
1335 args.old_path = rb_str_encode_ospath(rb_dir_getwd());
1336 args.new_path = path;
1337 args.done = FALSE;
1338 args.yield_path = yield_path;
1339 return rb_ensure(chdir_yield, (VALUE)&args, chdir_restore, (VALUE)&args);
1340 }
1341 else {
1342 char *p = RSTRING_PTR(path);
1343 int r = IO_WITHOUT_GVL_INT(nogvl_chdir, p);
1344 if (r < 0)
1345 rb_sys_fail_path(path);
1346 }
1347
1348 return INT2FIX(0);
1349}
1350
1351/*
1352 * call-seq:
1353 * Dir.chdir(new_dirpath) -> 0
1354 * Dir.chdir -> 0
1355 * Dir.chdir(new_dirpath) {|new_dirpath| ... } -> object
1356 * Dir.chdir {|cur_dirpath| ... } -> object
1357 *
1358 * Changes the current working directory.
1359 *
1360 * With argument +new_dirpath+ and no block,
1361 * changes to the given +dirpath+:
1362 *
1363 * Dir.pwd # => "/example"
1364 * Dir.chdir('..') # => 0
1365 * Dir.pwd # => "/"
1366 *
1367 * With no argument and no block:
1368 *
1369 * - Changes to the value of environment variable +HOME+ if defined.
1370 * - Otherwise changes to the value of environment variable +LOGDIR+ if defined.
1371 * - Otherwise makes no change.
1372 *
1373 * With argument +new_dirpath+ and a block, temporarily changes the working directory:
1374 *
1375 * - Calls the block with the argument.
1376 * - Changes to the given directory.
1377 * - Executes the block (yielding the new path).
1378 * - Restores the previous working directory.
1379 * - Returns the block's return value.
1380 *
1381 * Example:
1382 *
1383 * Dir.chdir('/var/spool/mail')
1384 * Dir.pwd # => "/var/spool/mail"
1385 * Dir.chdir('/tmp') do
1386 * Dir.pwd # => "/tmp"
1387 * end
1388 * Dir.pwd # => "/var/spool/mail"
1389 *
1390 * With no argument and a block,
1391 * calls the block with the current working directory (string)
1392 * and returns the block's return value.
1393 *
1394 * Calls to \Dir.chdir with blocks may be nested:
1395 *
1396 * Dir.chdir('/var/spool/mail')
1397 * Dir.pwd # => "/var/spool/mail"
1398 * Dir.chdir('/tmp') do
1399 * Dir.pwd # => "/tmp"
1400 * Dir.chdir('/usr') do
1401 * Dir.pwd # => "/usr"
1402 * end
1403 * Dir.pwd # => "/tmp"
1404 * end
1405 * Dir.pwd # => "/var/spool/mail"
1406 *
1407 * In a multi-threaded program an error is raised if a thread attempts
1408 * to open a +chdir+ block while another thread has one open,
1409 * or a call to +chdir+ without a block occurs inside
1410 * a block passed to +chdir+ (even in the same thread).
1411 *
1412 * Raises an exception if the target directory does not exist.
1413 */
1414static VALUE
1415dir_s_chdir(int argc, VALUE *argv, VALUE obj)
1416{
1417 VALUE path = Qnil;
1418
1419 if (rb_check_arity(argc, 0, 1) == 1) {
1420 path = rb_str_encode_ospath(rb_get_path(argv[0]));
1421 }
1422 else {
1423 const char *dist = getenv("HOME");
1424 if (!dist) {
1425 dist = getenv("LOGDIR");
1426 if (!dist) rb_raise(rb_eArgError, "HOME/LOGDIR not set");
1427 }
1428 path = rb_str_new2(dist);
1429 }
1430
1431 return chdir_path(path, true);
1432}
1433
1434#if defined(HAVE_FCHDIR) && defined(HAVE_DIRFD) && HAVE_FCHDIR && HAVE_DIRFD
1435static void *
1436nogvl_fchdir(void *ptr)
1437{
1438 const int *fd = ptr;
1439
1440 return (void *)(VALUE)fchdir(*fd);
1441}
1442
1443static void
1444dir_fchdir(int fd)
1445{
1446 if (IO_WITHOUT_GVL_INT(nogvl_fchdir, (void *)&fd) < 0)
1447 rb_sys_fail("fchdir");
1448}
1449
1450struct fchdir_data {
1451 VALUE old_dir;
1452 int fd;
1453 int done;
1454};
1455
1456static VALUE
1457fchdir_yield(VALUE v)
1458{
1459 struct fchdir_data *args = (void *)v;
1460 dir_fchdir(args->fd);
1461 args->done = TRUE;
1462 chdir_enter();
1463 return rb_yield_values(0);
1464}
1465
1466static VALUE
1467fchdir_restore(VALUE v)
1468{
1469 struct fchdir_data *args = (void *)v;
1470 if (args->done) {
1471 chdir_leave();
1472 dir_fchdir(RB_NUM2INT(dir_fileno(args->old_dir)));
1473 }
1474 dir_close(args->old_dir);
1475 return Qnil;
1476}
1477
1478/*
1479 * call-seq:
1480 * Dir.fchdir(fd) -> 0
1481 * Dir.fchdir(fd) { ... } -> object
1482 *
1483 * Changes the current working directory to the directory
1484 * specified by the integer file descriptor +fd+.
1485 *
1486 * When passing a file descriptor over a UNIX socket or to a child process,
1487 * using +fchdir+ instead of +chdir+ avoids the
1488 * {time-of-check to time-of-use vulnerability}[https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use]
1489 *
1490 * With no block, changes to the directory given by +fd+:
1491 *
1492 * Dir.chdir('/var/spool/mail')
1493 * Dir.pwd # => "/var/spool/mail"
1494 * dir = Dir.new('/usr')
1495 * fd = dir.fileno
1496 * Dir.fchdir(fd)
1497 * Dir.pwd # => "/usr"
1498 *
1499 * With a block, temporarily changes the working directory:
1500 *
1501 * - Calls the block with the argument.
1502 * - Changes to the given directory.
1503 * - Executes the block (yields no args).
1504 * - Restores the previous working directory.
1505 * - Returns the block's return value.
1506 *
1507 * Example:
1508 *
1509 * Dir.chdir('/var/spool/mail')
1510 * Dir.pwd # => "/var/spool/mail"
1511 * dir = Dir.new('/tmp')
1512 * fd = dir.fileno
1513 * Dir.fchdir(fd) do
1514 * Dir.pwd # => "/tmp"
1515 * end
1516 * Dir.pwd # => "/var/spool/mail"
1517 *
1518 * This method uses the
1519 * {fchdir()}[https://www.man7.org/linux/man-pages/man3/fchdir.3p.html]
1520 * function defined by POSIX 2008;
1521 * the method is not implemented on non-POSIX platforms (raises NotImplementedError).
1522 *
1523 * Raises an exception if the file descriptor is not valid.
1524 *
1525 * In a multi-threaded program an error is raised if a thread attempts
1526 * to open a +chdir+ block while another thread has one open,
1527 * or a call to +chdir+ without a block occurs inside
1528 * a block passed to +chdir+ (even in the same thread).
1529 */
1530static VALUE
1531dir_s_fchdir(VALUE klass, VALUE fd_value)
1532{
1533 int fd = RB_NUM2INT(fd_value);
1534
1535 if (chdir_alone_block_p()) {
1536 struct fchdir_data args;
1537 args.old_dir = dir_s_alloc(klass);
1538 dir_initialize(NULL, args.old_dir, rb_fstring_cstr("."), Qnil);
1539 args.fd = fd;
1540 args.done = FALSE;
1541 return rb_ensure(fchdir_yield, (VALUE)&args, fchdir_restore, (VALUE)&args);
1542 }
1543 else {
1544 int r = IO_WITHOUT_GVL_INT(nogvl_fchdir, &fd);
1545 if (r < 0)
1546 rb_sys_fail("fchdir");
1547 }
1548
1549 return INT2FIX(0);
1550}
1551#else
1552#define dir_s_fchdir rb_f_notimplement
1553#endif
1554
1555/*
1556 * call-seq:
1557 * chdir -> 0
1558 * chdir { ... } -> object
1559 *
1560 * Changes the current working directory to +self+:
1561 *
1562 * Dir.pwd # => "/"
1563 * dir = Dir.new('example')
1564 * dir.chdir
1565 * Dir.pwd # => "/example"
1566 *
1567 * With a block, temporarily changes the working directory:
1568 *
1569 * - Calls the block.
1570 * - Changes to the given directory.
1571 * - Executes the block (yields no args).
1572 * - Restores the previous working directory.
1573 * - Returns the block's return value.
1574 *
1575 * Uses Dir.fchdir if available, and Dir.chdir if not, see those
1576 * methods for caveats.
1577 */
1578static VALUE
1579dir_chdir(VALUE dir)
1580{
1581#if defined(HAVE_FCHDIR) && defined(HAVE_DIRFD) && HAVE_FCHDIR && HAVE_DIRFD
1582 return dir_s_fchdir(rb_cDir, dir_fileno(dir));
1583#else
1584 return chdir_path(dir_get(dir)->path, false);
1585#endif
1586}
1587
1588#ifndef _WIN32
1589static VALUE
1590getcwd_to_str(VALUE arg)
1591{
1592 const char *path = (const char *)arg;
1593#ifdef __APPLE__
1594 return rb_str_normalize_ospath(path, strlen(path));
1595#else
1596 return rb_str_new2(path);
1597#endif
1598}
1599
1600static VALUE
1601getcwd_xfree(VALUE arg)
1602{
1603 xfree((void *)arg);
1604 return Qnil;
1605}
1606
1607VALUE
1608rb_dir_getwd_ospath(void)
1609{
1610 char *path = ruby_getcwd();
1611 return rb_ensure(getcwd_to_str, (VALUE)path, getcwd_xfree, (VALUE)path);
1612}
1613#endif
1615VALUE
1616rb_dir_getwd(void)
1617{
1618 rb_encoding *fs = rb_filesystem_encoding();
1619 int fsenc = rb_enc_to_index(fs);
1620 VALUE cwd = rb_dir_getwd_ospath();
1621
1622 switch (fsenc) {
1623 case ENCINDEX_US_ASCII:
1624 fsenc = ENCINDEX_ASCII_8BIT;
1625 case ENCINDEX_ASCII_8BIT:
1626 break;
1627#if defined _WIN32 || defined __APPLE__
1628 default:
1629 return rb_str_conv_enc(cwd, NULL, fs);
1630#endif
1631 }
1632 return rb_enc_associate_index(cwd, fsenc);
1633}
1634
1635/*
1636 * call-seq:
1637 * Dir.pwd -> string
1638 *
1639 * Returns the path to the current working directory:
1640 *
1641 * Dir.chdir("/tmp") # => 0
1642 * Dir.pwd # => "/tmp"
1643 *
1644 */
1645static VALUE
1646dir_s_getwd(VALUE dir)
1647{
1648 return rb_dir_getwd();
1649}
1650
1651static VALUE
1652check_dirname(VALUE dir)
1653{
1654 VALUE d = dir;
1655 char *path, *pend;
1656 long len;
1657 rb_encoding *enc;
1658
1659 FilePathValue(d);
1660 enc = rb_enc_get(d);
1661 RSTRING_GETMEM(d, path, len);
1662 pend = path + len;
1663 pend = rb_enc_path_end(rb_enc_path_skip_prefix(path, pend, enc), pend, enc);
1664 if (pend - path < len) {
1665 d = rb_str_subseq(d, 0, pend - path);
1666 StringValueCStr(d);
1667 }
1668 return rb_str_encode_ospath(d);
1669}
1670
1671#if defined(HAVE_CHROOT)
1672static void *
1673nogvl_chroot(void *dirname)
1674{
1675 return (void *)(VALUE)chroot((const char *)dirname);
1676}
1677
1678/*
1679 * call-seq:
1680 * Dir.chroot(dirpath) -> 0
1681 *
1682 * Changes the root directory of the calling process to that specified in +dirpath+.
1683 * The new root directory is used for pathnames beginning with <tt>'/'</tt>.
1684 * The root directory is inherited by all children of the calling process.
1685 *
1686 * Only a privileged process may call +chroot+.
1687 *
1688 * See {Linux chroot}[https://man7.org/linux/man-pages/man2/chroot.2.html].
1689 */
1690static VALUE
1691dir_s_chroot(VALUE dir, VALUE path)
1692{
1693 path = check_dirname(path);
1694 if (IO_WITHOUT_GVL_INT(nogvl_chroot, (void *)RSTRING_PTR(path)) == -1)
1695 rb_sys_fail_path(path);
1696
1697 return INT2FIX(0);
1698}
1699#else
1700#define dir_s_chroot rb_f_notimplement
1701#endif
1702
1703struct mkdir_arg {
1704 const char *path;
1705 mode_t mode;
1706};
1707
1708static void *
1709nogvl_mkdir(void *ptr)
1710{
1711 struct mkdir_arg *m = ptr;
1712
1713 return (void *)(VALUE)mkdir(m->path, m->mode);
1714}
1715
1716/*
1717 * call-seq:
1718 * Dir.mkdir(dirpath, permissions = 0775) -> 0
1719 *
1720 * Creates a directory in the underlying file system
1721 * at +dirpath+ with the given +permissions+;
1722 * returns zero:
1723 *
1724 * Dir.mkdir('foo')
1725 * File.stat(Dir.new('foo')).mode.to_s(8)[1..4] # => "0755"
1726 * Dir.mkdir('bar', 0644)
1727 * File.stat(Dir.new('bar')).mode.to_s(8)[1..4] # => "0644"
1728 *
1729 * See {File Permissions}[rdoc-ref:File@File+Permissions].
1730 * Note that argument +permissions+ is ignored on Windows.
1731 */
1732static VALUE
1733dir_s_mkdir(int argc, VALUE *argv, VALUE obj)
1734{
1735 struct mkdir_arg m;
1736 VALUE path, vmode;
1737 int r;
1738
1739 if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
1740 m.mode = NUM2MODET(vmode);
1741 }
1742 else {
1743 m.mode = 0777;
1744 }
1745
1746 path = check_dirname(path);
1747 m.path = RSTRING_PTR(path);
1748 r = IO_WITHOUT_GVL_INT(nogvl_mkdir, &m);
1749 if (r < 0)
1750 rb_sys_fail_path(path);
1751
1752 return INT2FIX(0);
1753}
1754
1755static void *
1756nogvl_rmdir(void *ptr)
1757{
1758 const char *path = ptr;
1759
1760 return (void *)(VALUE)rmdir(path);
1761}
1762
1763/*
1764 * call-seq:
1765 * Dir.rmdir(dirpath) -> 0
1766 *
1767 * Removes the directory at +dirpath+ from the underlying file system:
1768 *
1769 * Dir.rmdir('foo') # => 0
1770 *
1771 * Raises an exception if the directory is not empty.
1772 */
1773static VALUE
1774dir_s_rmdir(VALUE obj, VALUE dir)
1775{
1776 const char *p;
1777 int r;
1778
1779 dir = check_dirname(dir);
1780 p = RSTRING_PTR(dir);
1781 r = IO_WITHOUT_GVL_INT(nogvl_rmdir, (void *)p);
1782 if (r < 0)
1783 rb_sys_fail_path(dir);
1784
1785 return INT2FIX(0);
1787
1788struct warning_args {
1789#ifdef RUBY_FUNCTION_NAME_STRING
1790 const char *func;
1791#endif
1792 const char *mesg;
1793 rb_encoding *enc;
1794};
1795
1796#ifndef RUBY_FUNCTION_NAME_STRING
1797#define sys_enc_warning_in(func, mesg, enc) sys_enc_warning(mesg, enc)
1798#endif
1799
1800static VALUE
1801sys_warning_1(VALUE mesg)
1802{
1803 const struct warning_args *arg = (struct warning_args *)mesg;
1804#ifdef RUBY_FUNCTION_NAME_STRING
1805 rb_sys_enc_warning(arg->enc, "%s: %s", arg->func, arg->mesg);
1806#else
1807 rb_sys_enc_warning(arg->enc, "%s", arg->mesg);
1808#endif
1809 return Qnil;
1810}
1811
1812static void
1813sys_enc_warning_in(const char *func, const char *mesg, rb_encoding *enc)
1814{
1815 struct warning_args arg;
1816#ifdef RUBY_FUNCTION_NAME_STRING
1817 arg.func = func;
1818#endif
1819 arg.mesg = mesg;
1820 arg.enc = enc;
1821 rb_protect(sys_warning_1, (VALUE)&arg, 0);
1822}
1823
1824#define GLOB_VERBOSE (1U << (sizeof(int) * CHAR_BIT - 1))
1825#define sys_warning(val, enc) \
1826 ((flags & GLOB_VERBOSE) ? sys_enc_warning_in(RUBY_FUNCTION_NAME_STRING, (val), (enc)) :(void)0)
1827
1828static inline size_t
1829glob_alloc_size(size_t x, size_t y)
1830{
1831 size_t z;
1832 if (rb_mul_size_overflow(x, y, SSIZE_MAX, &z)) {
1833 rb_memerror(); /* or...? */
1834 }
1835 else {
1836 return z;
1837 }
1838}
1839
1840static inline void *
1841glob_alloc_n(size_t x, size_t y)
1842{
1843 return malloc(glob_alloc_size(x, y));
1844}
1845
1846static inline void *
1847glob_realloc_n(void *p, size_t x, size_t y)
1848{
1849 return realloc(p, glob_alloc_size(x, y));
1850}
1851
1852#define GLOB_ALLOC(type) ((type *)malloc(sizeof(type)))
1853#define GLOB_ALLOC_N(type, n) ((type *)glob_alloc_n(sizeof(type), n))
1854#define GLOB_REALLOC(ptr, size) realloc((ptr), (size))
1855#define GLOB_REALLOC_N(ptr, n) glob_realloc_n(ptr, sizeof(*(ptr)), n)
1856#define GLOB_FREE(ptr) free(ptr)
1857#define GLOB_JUMP_TAG(status) (((status) == -1) ? rb_memerror() : rb_jump_tag(status))
1858
1859/*
1860 * ENOTDIR can be returned by stat(2) if a non-leaf element of the path
1861 * is not a directory.
1862 */
1863ALWAYS_INLINE(static int to_be_ignored(int e));
1864static inline int
1865to_be_ignored(int e)
1866{
1867 return e == ENOENT || e == ENOTDIR;
1868}
1869
1870#ifdef _WIN32
1871#define STAT(args) (int)(VALUE)nogvl_stat(&(args))
1872#define LSTAT(args) (int)(VALUE)nogvl_lstat(&(args))
1873#else
1874#define STAT(args) IO_WITHOUT_GVL_INT(nogvl_stat, (void *)&(args))
1875#define LSTAT(args) IO_WITHOUT_GVL_INT(nogvl_lstat, (void *)&(args))
1876#endif
1878typedef int ruby_glob_errfunc(const char*, VALUE, const void*, int);
1879typedef struct {
1880 ruby_glob_func *match;
1881 ruby_glob_errfunc *error;
1883
1884static const char *
1885at_subpath(int fd, size_t baselen, const char *path)
1886{
1887#if USE_OPENDIR_AT
1888 if (fd != (int)AT_FDCWD && baselen > 0) {
1889 path += baselen;
1890 if (*path == '/') ++path;
1891 }
1892#endif
1893 return *path ? path : ".";
1894}
1895
1896#if USE_OPENDIR_AT
1897struct fstatat_args {
1898 int fd;
1899 int flag;
1900 const char *path;
1901 struct stat *pst;
1902};
1903
1904static void *
1905nogvl_fstatat(void *args)
1906{
1907 struct fstatat_args *arg = (struct fstatat_args *)args;
1908 return (void *)(VALUE)fstatat(arg->fd, arg->path, arg->pst, arg->flag);
1910#else
1911struct stat_args {
1912 const char *path;
1913 struct stat *pst;
1914};
1915
1916static void *
1917nogvl_stat(void *args)
1918{
1919 struct stat_args *arg = (struct stat_args *)args;
1920 return (void *)(VALUE)stat(arg->path, arg->pst);
1921}
1922#endif
1923
1924/* System call with warning */
1925static int
1926do_stat(int fd, const char *path, struct stat *pst, int flags, rb_encoding *enc)
1927{
1928#if USE_OPENDIR_AT
1929 struct fstatat_args args;
1930 args.fd = fd;
1931 args.path = path;
1932 args.pst = pst;
1933 args.flag = 0;
1934 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (void *)&args);
1935#else
1936 struct stat_args args;
1937 args.path = path;
1938 args.pst = pst;
1939 int ret = STAT(args);
1940#endif
1941 if (ret < 0 && !to_be_ignored(errno))
1942 sys_warning(path, enc);
1943
1944 return ret;
1945}
1946
1947#if defined HAVE_LSTAT || defined lstat || USE_OPENDIR_AT
1948#if !USE_OPENDIR_AT
1949static void *
1950nogvl_lstat(void *args)
1951{
1952 struct stat_args *arg = (struct stat_args *)args;
1953 return (void *)(VALUE)lstat(arg->path, arg->pst);
1954}
1955#endif
1956
1957static int
1958do_lstat(int fd, const char *path, struct stat *pst, int flags, rb_encoding *enc)
1959{
1960#if USE_OPENDIR_AT
1961 struct fstatat_args args;
1962 args.fd = fd;
1963 args.path = path;
1964 args.pst = pst;
1965 args.flag = AT_SYMLINK_NOFOLLOW;
1966 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (void *)&args);
1967#else
1968 struct stat_args args;
1969 args.path = path;
1970 args.pst = pst;
1971 int ret = LSTAT(args);
1972#endif
1973 if (ret < 0 && !to_be_ignored(errno))
1974 sys_warning(path, enc);
1975
1976 return ret;
1977}
1978#else
1979#define do_lstat do_stat
1980#endif
1981
1982struct opendir_at_arg {
1983 int basefd;
1984 const char *path;
1985};
1986
1987static void *
1988with_gvl_gc_for_fd(void *ptr)
1989{
1990 int *e = ptr;
1991
1992 return (void *)RBOOL(rb_gc_for_fd(*e));
1993}
1994
1995static int
1996gc_for_fd_with_gvl(int e)
1997{
1998 if (vm_initialized)
1999 return (int)(VALUE)rb_thread_call_with_gvl(with_gvl_gc_for_fd, &e);
2000 else
2001 return RBOOL(rb_gc_for_fd(e));
2002}
2003
2004static void *
2005nogvl_opendir_at(void *ptr)
2006{
2007 const struct opendir_at_arg *oaa = ptr;
2008 DIR *dirp;
2009
2010#if USE_OPENDIR_AT
2011 const int opendir_flags = (O_RDONLY|O_CLOEXEC|
2012# ifdef O_DIRECTORY
2013 O_DIRECTORY|
2014# endif /* O_DIRECTORY */
2015 0);
2016 int fd = openat(oaa->basefd, oaa->path, opendir_flags);
2017
2018 dirp = fd >= 0 ? fdopendir(fd) : 0;
2019 if (!dirp) {
2020 int e = errno;
2021
2022 switch (gc_for_fd_with_gvl(e)) {
2023 default:
2024 if (fd < 0) fd = openat(oaa->basefd, oaa->path, opendir_flags);
2025 if (fd >= 0) dirp = fdopendir(fd);
2026 if (dirp) return dirp;
2027
2028 e = errno;
2029 /* fallthrough*/
2030 case 0:
2031 if (fd >= 0) close(fd);
2032 rb_errno_set(e);
2033 }
2034 }
2035#else /* !USE_OPENDIR_AT */
2036 dirp = opendir(oaa->path);
2037 if (!dirp && gc_for_fd_with_gvl(errno))
2038 dirp = opendir(oaa->path);
2039#endif /* !USE_OPENDIR_AT */
2040
2041 return dirp;
2042}
2043
2044static DIR *
2045opendir_at(int basefd, const char *path)
2046{
2047 struct opendir_at_arg oaa;
2048
2049 oaa.basefd = basefd;
2050 oaa.path = path;
2051
2052 if (vm_initialized)
2053 return IO_WITHOUT_GVL(nogvl_opendir_at, &oaa);
2054 else
2055 return nogvl_opendir_at(&oaa);
2056}
2057
2058static DIR *
2059do_opendir(const int basefd, size_t baselen, const char *path, int flags, rb_encoding *enc,
2060 ruby_glob_errfunc *errfunc, VALUE arg, int *status)
2061{
2062 DIR *dirp;
2063#ifdef _WIN32
2064 VALUE tmp = 0;
2065 if (!fundamental_encoding_p(enc)) {
2066 tmp = rb_enc_str_new(path, strlen(path), enc);
2067 tmp = rb_str_encode_ospath(tmp);
2068 path = RSTRING_PTR(tmp);
2069 }
2070#endif
2071 dirp = opendir_at(basefd, at_subpath(basefd, baselen, path));
2072 if (!dirp) {
2073 int e = errno;
2074
2075 *status = 0;
2076 if (!to_be_ignored(e)) {
2077 if (errfunc) {
2078 *status = (*errfunc)(path, arg, enc, e);
2079 }
2080 else {
2081 sys_warning(path, enc);
2082 }
2083 }
2084 }
2085#ifdef _WIN32
2086 if (tmp) rb_str_resize(tmp, 0); /* GC guard */
2087#endif
2088
2089 return dirp;
2090}
2091
2092/* Globing pattern */
2093enum glob_pattern_type { PLAIN, ALPHA, BRACE, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR };
2094
2095/* Return nonzero if S has any special globbing chars in it. */
2096static enum glob_pattern_type
2097has_magic(const char *p, const char *pend, int flags, rb_encoding *enc)
2098{
2099 const int escape = !(flags & FNM_NOESCAPE);
2100 int hasalpha = 0;
2101 int hasmagical = 0;
2102
2103 register char c;
2104
2105 while (p < pend && (c = *p++) != 0) {
2106 switch (c) {
2107 case '{':
2108 return BRACE;
2109
2110 case '*':
2111 case '?':
2112 case '[':
2113 hasmagical = 1;
2114 break;
2115
2116 case '\\':
2117 if (escape && p++ >= pend)
2118 continue;
2119 break;
2120
2121#ifdef _WIN32
2122 case '.':
2123 break;
2124
2125 case '~':
2126 hasalpha = 1;
2127 break;
2128#endif
2129 default:
2130 if (IS_WIN32 || ISALPHA(c)) {
2131 hasalpha = 1;
2132 }
2133 break;
2134 }
2135
2136 p = Next(p-1, pend, enc);
2137 }
2138
2139 return hasmagical ? MAGICAL : hasalpha ? ALPHA : PLAIN;
2140}
2141
2142/* Find separator in globbing pattern. */
2143static char *
2144find_dirsep(const char *p, const char *pend, int flags, rb_encoding *enc)
2145{
2146 const int escape = !(flags & FNM_NOESCAPE);
2147
2148 register char c;
2149 int open = 0;
2150
2151 while ((c = *p++) != 0) {
2152 switch (c) {
2153 case '[':
2154 open = 1;
2155 continue;
2156 case ']':
2157 open = 0;
2158 continue;
2159
2160 case '{':
2161 open = 1;
2162 continue;
2163 case '}':
2164 open = 0;
2165 continue;
2166
2167 case '/':
2168 if (!open)
2169 return (char *)p-1;
2170 continue;
2171
2172 case '\\':
2173 if (escape && !(c = *p++))
2174 return (char *)p-1;
2175 continue;
2176 }
2177
2178 p = Next(p-1, pend, enc);
2179 }
2180
2181 return (char *)p-1;
2182}
2183
2184/* Remove escaping backslashes */
2185static char *
2186remove_backslashes(char *p, register const char *pend, rb_encoding *enc)
2187{
2188 char *t = p;
2189 char *s = p;
2190
2191 while (*p) {
2192 if (*p == '\\') {
2193 if (t != s)
2194 memmove(t, s, p - s);
2195 t += p - s;
2196 s = ++p;
2197 if (!*p) break;
2198 }
2199 Inc(p, pend, enc);
2200 }
2201
2202 while (*p++);
2203
2204 if (t != s)
2205 memmove(t, s, p - s); /* move '\0' too */
2206
2207 return p;
2209
2210struct glob_pattern {
2211 char *str;
2212 enum glob_pattern_type type;
2213 struct glob_pattern *next;
2214};
2215
2216static void glob_free_pattern(struct glob_pattern *list);
2217
2218static struct glob_pattern *
2219glob_make_pattern(const char *p, const char *e, int flags, rb_encoding *enc)
2220{
2221 struct glob_pattern *list, *tmp, **tail = &list;
2222 int dirsep = 0; /* pattern is terminated with '/' */
2223 int recursive = 0;
2224
2225 while (p < e && *p) {
2226 tmp = GLOB_ALLOC(struct glob_pattern);
2227 if (!tmp) goto error;
2228 if (p + 2 < e && p[0] == '*' && p[1] == '*' && p[2] == '/') {
2229 /* fold continuous RECURSIVEs (needed in glob_helper) */
2230 do { p += 3; while (*p == '/') p++; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
2231 tmp->type = RECURSIVE;
2232 tmp->str = 0;
2233 dirsep = 1;
2234 recursive = 1;
2235 }
2236 else {
2237 const char *m = find_dirsep(p, e, flags, enc);
2238 const enum glob_pattern_type magic = has_magic(p, m, flags, enc);
2239 const enum glob_pattern_type non_magic = (USE_NAME_ON_FS || FNM_SYSCASE) ? PLAIN : ALPHA;
2240 char *buf;
2241
2242 if (!(FNM_SYSCASE || magic > non_magic) && !recursive && *m) {
2243 const char *m2;
2244 while (has_magic(m+1, m2 = find_dirsep(m+1, e, flags, enc), flags, enc) <= non_magic &&
2245 *m2) {
2246 m = m2;
2247 }
2248 }
2249 buf = GLOB_ALLOC_N(char, m-p+1);
2250 if (!buf) {
2251 GLOB_FREE(tmp);
2252 goto error;
2253 }
2254 memcpy(buf, p, m-p);
2255 buf[m-p] = '\0';
2256 tmp->type = magic > MAGICAL ? MAGICAL : magic > non_magic ? magic : PLAIN;
2257 tmp->str = buf;
2258 if (*m) {
2259 dirsep = 1;
2260 p = m + 1;
2261 }
2262 else {
2263 dirsep = 0;
2264 p = m;
2265 }
2266 }
2267 *tail = tmp;
2268 tail = &tmp->next;
2269 }
2270
2271 tmp = GLOB_ALLOC(struct glob_pattern);
2272 if (!tmp) {
2273 goto error;
2274 }
2275 tmp->type = dirsep ? MATCH_DIR : MATCH_ALL;
2276 tmp->str = 0;
2277 *tail = tmp;
2278 tmp->next = 0;
2279
2280 return list;
2281
2282 error:
2283 *tail = 0;
2284 glob_free_pattern(list);
2285 return 0;
2286}
2287
2288static void
2289glob_free_pattern(struct glob_pattern *list)
2290{
2291 while (list) {
2292 struct glob_pattern *tmp = list;
2293 list = list->next;
2294 if (tmp->str)
2295 GLOB_FREE(tmp->str);
2296 GLOB_FREE(tmp);
2297 }
2298}
2299
2300static char *
2301join_path(const char *path, size_t len, int dirsep, const char *name, size_t namlen)
2302{
2303 char *buf = GLOB_ALLOC_N(char, len+namlen+(dirsep?1:0)+1);
2304
2305 if (!buf) return 0;
2306 memcpy(buf, path, len);
2307 if (dirsep) {
2308 buf[len++] = '/';
2309 }
2310 memcpy(buf+len, name, namlen);
2311 buf[len+namlen] = '\0';
2312 return buf;
2313}
2314
2315#ifdef HAVE_GETATTRLIST
2316# if defined HAVE_FGETATTRLIST
2317# define is_case_sensitive(dirp, path) is_case_sensitive(dirp)
2318# else
2319# define is_case_sensitive(dirp, path) is_case_sensitive(path)
2320# endif
2321static int
2322is_case_sensitive(DIR *dirp, const char *path)
2323{
2324 struct {
2325 u_int32_t length;
2326 vol_capabilities_attr_t cap[1];
2327 } __attribute__((aligned(4), packed)) attrbuf[1];
2328 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, 0, ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES};
2329 const vol_capabilities_attr_t *const cap = attrbuf[0].cap;
2330 const int idx = VOL_CAPABILITIES_FORMAT;
2331 const uint32_t mask = VOL_CAP_FMT_CASE_SENSITIVE;
2332 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2333# if defined HAVE_FGETATTRLIST
2334 int ret = gvl_fgetattrlist(&args, dirfd(dirp));
2335# else
2336 int ret = gvl_getattrlist(&args, path);
2337# endif
2338 if (ret)
2339 return -1;
2340
2341 if (!(cap->valid[idx] & mask))
2342 return -1;
2343 return (cap->capabilities[idx] & mask) != 0;
2344}
2345
2346static char *
2347replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int flags, rb_pathtype_t *type)
2348{
2349 struct {
2350 u_int32_t length;
2351 attrreference_t ref[1];
2352 fsobj_type_t objtype;
2353 char path[MAXPATHLEN * 3];
2354 } __attribute__((aligned(4), packed)) attrbuf[1];
2355 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_NAME|ATTR_CMN_OBJTYPE};
2356 const attrreference_t *const ar = attrbuf[0].ref;
2357 const char *name;
2358 long len;
2359 char *tmp;
2360 IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil);
2361
2362 *type = path_noent;
2363 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2364 if (gvl_getattrlist(&args, path)) {
2365 if (!to_be_ignored(errno))
2366 sys_warning(path, enc);
2367 return path;
2368 }
2369
2370 switch (attrbuf[0].objtype) {
2371 case VREG: *type = path_regular; break;
2372 case VDIR: *type = path_directory; break;
2373 case VLNK: *type = path_symlink; break;
2374 default: *type = path_exist; break;
2375 }
2376 name = (char *)ar + ar->attr_dataoffset;
2377 len = (long)ar->attr_length - 1;
2378 if (name + len > (char *)attrbuf + sizeof(attrbuf))
2379 return path;
2380
2381# if NORMALIZE_UTF8PATH
2382 if (norm_p && has_nonascii(name, len)) {
2383 if (!NIL_P(utf8str = rb_str_normalize_ospath(name, len))) {
2384 RSTRING_GETMEM(utf8str, name, len);
2385 }
2386 }
2387# endif
2388
2389 tmp = GLOB_REALLOC(path, base + len + 1);
2390 if (tmp) {
2391 path = tmp;
2392 memcpy(path + base, name, len);
2393 path[base + len] = '\0';
2394 }
2395 IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0));
2396 return path;
2397}
2398#elif defined _WIN32
2399VALUE rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc);
2400int rb_w32_reparse_symlink_p(const WCHAR *path);
2401
2402static char *
2403replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int flags, rb_pathtype_t *type)
2404{
2405 char *plainname = path;
2406 volatile VALUE tmp = 0;
2407 WIN32_FIND_DATAW fd;
2408 WIN32_FILE_ATTRIBUTE_DATA fa;
2409 WCHAR *wplain;
2410 HANDLE h = INVALID_HANDLE_VALUE;
2411 long wlen;
2412 int e = 0;
2413 if (!fundamental_encoding_p(enc)) {
2414 tmp = rb_enc_str_new_cstr(plainname, enc);
2415 tmp = rb_str_encode_ospath(tmp);
2416 plainname = RSTRING_PTR(tmp);
2417 }
2418 wplain = rb_w32_mbstr_to_wstr(CP_UTF8, plainname, -1, &wlen);
2419 if (tmp) rb_str_resize(tmp, 0);
2420 if (!wplain) return path;
2421 if (GetFileAttributesExW(wplain, GetFileExInfoStandard, &fa)) {
2422 h = FindFirstFileW(wplain, &fd);
2423 e = rb_w32_map_errno(GetLastError());
2424 }
2425 if (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2426 if (!rb_w32_reparse_symlink_p(wplain))
2427 fa.dwFileAttributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
2428 }
2429 free(wplain);
2430 if (h == INVALID_HANDLE_VALUE) {
2431 *type = path_noent;
2432 if (e && !to_be_ignored(e)) {
2433 errno = e;
2434 sys_warning(path, enc);
2435 }
2436 return path;
2437 }
2438 FindClose(h);
2439 *type =
2440 (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? path_symlink :
2441 (fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? path_directory :
2442 path_regular;
2443 if (tmp) {
2444 char *buf;
2445 tmp = rb_w32_conv_from_wchar(fd.cFileName, enc);
2446 wlen = RSTRING_LEN(tmp);
2447 buf = GLOB_REALLOC(path, base + wlen + 1);
2448 if (buf) {
2449 path = buf;
2450 memcpy(path + base, RSTRING_PTR(tmp), wlen);
2451 path[base + wlen] = 0;
2452 }
2453 rb_str_resize(tmp, 0);
2454 }
2455 else {
2456 char *utf8filename;
2457 wlen = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, NULL, 0, NULL, NULL);
2458 utf8filename = GLOB_REALLOC(0, wlen);
2459 if (utf8filename) {
2460 char *buf;
2461 WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, utf8filename, wlen, NULL, NULL);
2462 buf = GLOB_REALLOC(path, base + wlen + 1);
2463 if (buf) {
2464 path = buf;
2465 memcpy(path + base, utf8filename, wlen);
2466 path[base + wlen] = 0;
2467 }
2468 GLOB_FREE(utf8filename);
2469 }
2470 }
2471 return path;
2472}
2473#elif USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2474# error not implemented
2475#endif
2476
2477#ifndef S_ISDIR
2478# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
2479#endif
2480
2481#ifndef S_ISLNK
2482# ifndef S_IFLNK
2483# define S_ISLNK(m) (0)
2484# else
2485# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
2486# endif
2487#endif
2488
2489struct glob_args {
2490 void (*func)(const char *, VALUE, void *);
2491 const char *path;
2492 const char *base;
2493 size_t baselen;
2494 VALUE value;
2495 rb_encoding *enc;
2496};
2497
2498#define glob_call_func(func, path, arg, enc) (*(func))((path), (arg), (void *)(enc))
2499
2500static VALUE
2501glob_func_caller(VALUE val)
2502{
2503 struct glob_args *args = (struct glob_args *)val;
2504
2505 glob_call_func(args->func, args->path, args->value, args->enc);
2506 return Qnil;
2508
2509struct glob_error_args {
2510 const char *path;
2511 rb_encoding *enc;
2512 int error;
2513};
2514
2515static VALUE
2516glob_func_warning(VALUE val)
2517{
2518 struct glob_error_args *arg = (struct glob_error_args *)val;
2519 rb_syserr_enc_warning(arg->error, arg->enc, "%s", arg->path);
2520 return Qnil;
2521}
2522
2523#if 0
2524static int
2525rb_glob_warning(const char *path, VALUE a, const void *enc, int error)
2526{
2527 int status;
2528 struct glob_error_args args;
2529
2530 args.path = path;
2531 args.enc = enc;
2532 args.error = error;
2533 rb_protect(glob_func_warning, (VALUE)&args, &status);
2534 return status;
2535}
2536#endif
2537
2538NORETURN(static VALUE glob_func_error(VALUE val));
2539
2540static VALUE
2541glob_func_error(VALUE val)
2542{
2543 struct glob_error_args *arg = (struct glob_error_args *)val;
2544 VALUE path = rb_enc_str_new_cstr(arg->path, arg->enc);
2545 rb_syserr_fail_str(arg->error, path);
2547}
2548
2549static int
2550rb_glob_error(const char *path, VALUE a, const void *enc, int error)
2551{
2552 int status;
2553 struct glob_error_args args;
2554 VALUE (*errfunc)(VALUE) = glob_func_error;
2555
2556 switch (error) {
2557 case EACCES:
2558#ifdef ENOTCAPABLE
2559 case ENOTCAPABLE:
2560#endif
2561 errfunc = glob_func_warning;
2562 }
2563 args.path = path;
2564 args.enc = enc;
2565 args.error = error;
2566 rb_protect(errfunc, (VALUE)&args, &status);
2567 return status;
2569
2570typedef struct rb_dirent {
2571 long d_namlen;
2572 const char *d_name;
2573#ifdef _WIN32
2574 const char *d_altname;
2575#endif
2576 uint8_t d_type;
2577} rb_dirent_t;
2578
2579static inline int
2580dirent_match(const char *pat, rb_encoding *enc, const char *name, const rb_dirent_t *dp, int flags)
2581{
2582 if (fnmatch(pat, enc, name, flags) == 0) return 1;
2583#ifdef _WIN32
2584 if (dp->d_altname && (flags & FNM_SHORTNAME)) {
2585 if (fnmatch(pat, enc, dp->d_altname, flags) == 0) return 1;
2586 }
2587#endif
2588 return 0;
2590
2591struct push_glob_args {
2592 int fd;
2593 const char *path;
2594 size_t baselen;
2595 size_t namelen;
2596 int dirsep; /* '/' should be placed before appending child entry's name to 'path'. */
2597 rb_pathtype_t pathtype; /* type of 'path' */
2598 int flags;
2599 const ruby_glob_funcs_t *funcs;
2600 VALUE arg;
2602
2603struct dirent_brace_args {
2604 const char *name;
2605 const rb_dirent_t *dp;
2606 int flags;
2607};
2608
2609static int
2610dirent_match_brace(const char *pattern, VALUE val, void *enc)
2611{
2612 struct dirent_brace_args *arg = (struct dirent_brace_args *)val;
2613
2614 return dirent_match(pattern, enc, arg->name, arg->dp, arg->flags);
2615}
2616
2617/* join paths from pattern list of glob_make_pattern() */
2618static char*
2619join_path_from_pattern(struct glob_pattern **beg)
2620{
2621 struct glob_pattern *p;
2622 char *path = NULL;
2623 size_t path_len = 0;
2624
2625 for (p = *beg; p; p = p->next) {
2626 const char *str;
2627 switch (p->type) {
2628 case RECURSIVE:
2629 str = "**";
2630 break;
2631 case MATCH_DIR:
2632 /* append last slash */
2633 str = "";
2634 break;
2635 default:
2636 str = p->str;
2637 if (!str) continue;
2638 }
2639 if (!path) {
2640 path_len = strlen(str);
2641 path = GLOB_ALLOC_N(char, path_len + 1);
2642 if (path) {
2643 memcpy(path, str, path_len);
2644 path[path_len] = '\0';
2645 }
2646 }
2647 else {
2648 size_t len = strlen(str);
2649 char *tmp;
2650 tmp = GLOB_REALLOC(path, path_len + len + 2);
2651 if (tmp) {
2652 path = tmp;
2653 path[path_len++] = '/';
2654 memcpy(path + path_len, str, len);
2655 path_len += len;
2656 path[path_len] = '\0';
2657 }
2658 }
2659 }
2660 return path;
2661}
2662
2663static int push_caller(const char *path, VALUE val, void *enc);
2664
2665static int ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg,
2666 rb_encoding *enc, VALUE var);
2667
2668static const size_t rb_dirent_name_offset =
2669 offsetof(rb_dirent_t, d_type) + sizeof(uint8_t);
2670
2671static rb_dirent_t *
2672dirent_copy(const struct dirent *dp, rb_dirent_t *rdp)
2673{
2674 if (!dp) return NULL;
2675 size_t namlen = NAMLEN(dp);
2676 const size_t altlen =
2677#ifdef _WIN32
2678 dp->d_altlen ? dp->d_altlen + 1 :
2679#endif
2680 0;
2681 rb_dirent_t *newrdp = rdp;
2682 if (!rdp && !(newrdp = malloc(rb_dirent_name_offset + namlen + 1 + altlen)))
2683 return NULL;
2684 newrdp->d_namlen = namlen;
2685 if (!rdp) {
2686 char *name = (char *)newrdp + rb_dirent_name_offset;
2687 memcpy(name, dp->d_name, namlen);
2688 name[namlen] = '\0';
2689#ifdef _WIN32
2690 newrdp->d_altname = NULL;
2691 if (altlen) {
2692 char *const altname = name + namlen + 1;
2693 memcpy(altname, dp->d_altname, altlen - 1);
2694 altname[altlen - 1] = '\0';
2695 newrdp->d_altname = altname;
2696 }
2697#endif
2698 newrdp->d_name = name;
2699 }
2700 else {
2701 newrdp->d_name = dp->d_name;
2702#ifdef _WIN32
2703 newrdp->d_altname = dp->d_altname;
2704#endif
2705 }
2706#if !EMULATE_IFTODT
2707 newrdp->d_type = dp->d_type;
2708#else
2709 newrdp->d_type = 0;
2710#endif
2711 return newrdp;
2713
2714typedef union {
2715 struct {
2716 DIR *dirp;
2717 rb_dirent_t ent;
2718 } nosort;
2719 struct {
2720 size_t count, idx;
2721 rb_dirent_t **entries;
2722 } sort;
2724
2725static int
2726glob_sort_cmp(const void *a, const void *b, void *e)
2727{
2728 const rb_dirent_t *ent1 = *(void **)a;
2729 const rb_dirent_t *ent2 = *(void **)b;
2730 return strcmp(ent1->d_name, ent2->d_name);
2731}
2732
2733static void
2734glob_dir_finish(ruby_glob_entries_t *ent, int flags)
2735{
2736 if (flags & FNM_GLOB_NOSORT) {
2737 check_closedir(ent->nosort.dirp);
2738 ent->nosort.dirp = NULL;
2739 }
2740 else if (ent->sort.entries) {
2741 for (size_t i = 0, count = ent->sort.count; i < count;) {
2742 GLOB_FREE(ent->sort.entries[i++]);
2743 }
2744 GLOB_FREE(ent->sort.entries);
2745 ent->sort.entries = NULL;
2746 ent->sort.count = ent->sort.idx = 0;
2747 }
2748}
2749
2750static ruby_glob_entries_t *
2751glob_opendir(ruby_glob_entries_t *ent, DIR *dirp, int flags, rb_encoding *enc)
2752{
2754 if (flags & FNM_GLOB_NOSORT) {
2755 ent->nosort.dirp = dirp;
2756 return ent;
2757 }
2758 else {
2759 void *newp;
2760 struct dirent *dp;
2761 size_t count = 0, capacity = 0;
2762 ent->sort.count = 0;
2763 ent->sort.idx = 0;
2764 ent->sort.entries = 0;
2765#ifdef _WIN32
2766 if ((capacity = dirp->nfiles) > 0) {
2767 if (!(newp = GLOB_ALLOC_N(rb_dirent_t, capacity))) {
2768 check_closedir(dirp);
2769 return NULL;
2770 }
2771 ent->sort.entries = newp;
2772 }
2773#endif
2774 while ((dp = READDIR(dirp, enc)) != NULL) {
2775 rb_dirent_t *rdp = dirent_copy(dp, NULL);
2776 if (!rdp) {
2777 goto nomem;
2778 }
2779 if (count >= capacity) {
2780 capacity += 256;
2781 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, capacity)))
2782 goto nomem;
2783 ent->sort.entries = newp;
2784 }
2785 ent->sort.entries[count++] = rdp;
2786 ent->sort.count = count;
2787 }
2788 check_closedir(dirp);
2789 if (count < capacity) {
2790 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, count))) {
2791 glob_dir_finish(ent, 0);
2792 return NULL;
2793 }
2794 ent->sort.entries = newp;
2795 }
2796 ruby_qsort(ent->sort.entries, ent->sort.count, sizeof(ent->sort.entries[0]),
2797 glob_sort_cmp, NULL);
2798 return ent;
2799 }
2800
2801 nomem:
2802 glob_dir_finish(ent, 0);
2803 check_closedir(dirp);
2804 return NULL;
2805}
2806
2807static rb_dirent_t *
2808glob_getent(ruby_glob_entries_t *ent, int flags, rb_encoding *enc)
2809{
2810 if (flags & FNM_GLOB_NOSORT) {
2811 return dirent_copy(READDIR(ent->nosort.dirp, enc), &ent->nosort.ent);
2812 }
2813 else if (ent->sort.idx < ent->sort.count) {
2814 return ent->sort.entries[ent->sort.idx++];
2815 }
2816 else {
2817 return NULL;
2818 }
2819}
2820
2821static int
2822glob_helper(
2823 int fd,
2824 const char *path,
2825 size_t baselen,
2826 size_t namelen,
2827 int dirsep, /* '/' should be placed before appending child entry's name to 'path'. */
2828 rb_pathtype_t pathtype, /* type of 'path' */
2829 struct glob_pattern **beg,
2830 struct glob_pattern **end,
2831 int flags,
2832 const ruby_glob_funcs_t *funcs,
2833 VALUE arg,
2834 rb_encoding *enc)
2835{
2836 struct stat st;
2837 int status = 0;
2838 struct glob_pattern **cur, **new_beg, **new_end;
2839 int plain = 0, brace = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0;
2840 int escape = !(flags & FNM_NOESCAPE);
2841 size_t pathlen = baselen + namelen;
2842
2843 rb_check_stack_overflow();
2844
2845 for (cur = beg; cur < end; ++cur) {
2846 struct glob_pattern *p = *cur;
2847 if (p->type == RECURSIVE) {
2848 recursive = 1;
2849 p = p->next;
2850 }
2851 switch (p->type) {
2852 case PLAIN:
2853 plain = 1;
2854 break;
2855 case ALPHA:
2856#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2857 plain = 1;
2858#else
2859 magical = 1;
2860#endif
2861 break;
2862 case BRACE:
2863 if (!recursive || strchr(p->str, '/')) {
2864 brace = 1;
2865 }
2866 break;
2867 case MAGICAL:
2868 magical = 2;
2869 break;
2870 case MATCH_ALL:
2871 match_all = 1;
2872 break;
2873 case MATCH_DIR:
2874 match_dir = 1;
2875 break;
2876 case RECURSIVE:
2877 rb_bug("continuous RECURSIVEs");
2878 }
2879 }
2880
2881 if (brace) {
2882 struct push_glob_args args;
2883 char* brace_path = join_path_from_pattern(beg);
2884 if (!brace_path) return -1;
2885 args.fd = fd;
2886 args.path = path;
2887 args.baselen = baselen;
2888 args.namelen = namelen;
2889 args.dirsep = dirsep;
2890 args.pathtype = pathtype;
2891 args.flags = flags;
2892 args.funcs = funcs;
2893 args.arg = arg;
2894 status = ruby_brace_expand(brace_path, flags, push_caller, (VALUE)&args, enc, Qfalse);
2895 GLOB_FREE(brace_path);
2896 return status;
2897 }
2898
2899 if (*path) {
2900 if (match_all && pathtype == path_unknown) {
2901 if (do_lstat(fd, path, &st, flags, enc) == 0) {
2902 pathtype = IFTODT(st.st_mode);
2903 }
2904 else {
2905 pathtype = path_noent;
2906 }
2907 }
2908 if (match_dir && (pathtype == path_unknown || pathtype == path_symlink)) {
2909 if (do_stat(fd, path, &st, flags, enc) == 0) {
2910 pathtype = IFTODT(st.st_mode);
2911 }
2912 else {
2913 pathtype = path_noent;
2914 }
2915 }
2916 if (match_all && pathtype > path_noent) {
2917 const char *subpath = path + baselen + (baselen && path[baselen] == '/');
2918 status = glob_call_func(funcs->match, subpath, arg, enc);
2919 if (status) return status;
2920 }
2921 if (match_dir && pathtype == path_directory) {
2922 int seplen = (baselen && path[baselen] == '/');
2923 const char *subpath = path + baselen + seplen;
2924 char *tmp = join_path(subpath, namelen - seplen, dirsep, "", 0);
2925 if (!tmp) return -1;
2926 status = glob_call_func(funcs->match, tmp, arg, enc);
2927 GLOB_FREE(tmp);
2928 if (status) return status;
2929 }
2930 }
2931
2932 if (pathtype == path_noent) return 0;
2933
2934 if (magical || recursive) {
2935 rb_dirent_t *dp;
2936 DIR *dirp;
2937# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2938 char *plainname = 0;
2939# endif
2940 IF_NORMALIZE_UTF8PATH(int norm_p);
2941# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2942 if (cur + 1 == end && (*cur)->type <= ALPHA) {
2943 plainname = join_path(path, pathlen, dirsep, (*cur)->str, strlen((*cur)->str));
2944 if (!plainname) return -1;
2945 dirp = do_opendir(fd, basename, plainname, flags, enc, funcs->error, arg, &status);
2946 GLOB_FREE(plainname);
2947 }
2948 else
2949# else
2950 ;
2951# endif
2952 dirp = do_opendir(fd, baselen, path, flags, enc, funcs->error, arg, &status);
2953 if (dirp == NULL) {
2954# if FNM_SYSCASE || NORMALIZE_UTF8PATH
2955 if ((magical < 2) && !recursive && (errno == EACCES)) {
2956 /* no read permission, fallback */
2957 goto literally;
2958 }
2959# endif
2960 return status;
2961 }
2962 IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp, *path ? path : "."));
2963
2964# if NORMALIZE_UTF8PATH
2965 if (!(norm_p || magical || recursive)) {
2966 check_closedir(dirp);
2967 goto literally;
2968 }
2969# endif
2970# ifdef HAVE_GETATTRLIST
2971 if (is_case_sensitive(dirp, path) == 0)
2972 flags |= FNM_CASEFOLD;
2973# endif
2974 ruby_glob_entries_t globent;
2975 if (!glob_opendir(&globent, dirp, flags, enc)) {
2976 status = 0;
2977 if (funcs->error) {
2978 status = (*funcs->error)(path, arg, enc, ENOMEM);
2979 }
2980 else {
2981 sys_warning(path, enc);
2982 }
2983 return status;
2984 }
2985
2986 int skipdot = (flags & FNM_GLOB_SKIPDOT);
2987 flags |= FNM_GLOB_SKIPDOT;
2988
2989 while ((dp = glob_getent(&globent, flags, enc)) != NULL) {
2990 char *buf;
2991 rb_pathtype_t new_pathtype = path_unknown;
2992 const char *name;
2993 size_t namlen;
2994 int dotfile = 0;
2995 IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil);
2996
2997 name = dp->d_name;
2998 namlen = dp->d_namlen;
2999 if (name[0] == '.') {
3000 ++dotfile;
3001 if (namlen == 1) {
3002 /* unless DOTMATCH, skip current directories not to recurse infinitely */
3003 if (recursive && !(flags & FNM_DOTMATCH)) continue;
3004 if (skipdot) continue;
3005 ++dotfile;
3006 new_pathtype = path_directory; /* force to skip stat/lstat */
3007 }
3008 else if (namlen == 2 && name[1] == '.') {
3009 /* always skip parent directories not to recurse infinitely */
3010 continue;
3011 }
3012 }
3013
3014# if NORMALIZE_UTF8PATH
3015 if (norm_p && has_nonascii(name, namlen)) {
3016 if (!NIL_P(utf8str = rb_str_normalize_ospath(name, namlen))) {
3017 RSTRING_GETMEM(utf8str, name, namlen);
3018 }
3019 }
3020# endif
3021 buf = join_path(path, pathlen, dirsep, name, namlen);
3022 IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0));
3023 if (!buf) {
3024 status = -1;
3025 break;
3026 }
3027 name = buf + pathlen + (dirsep != 0);
3028#if !EMULATE_IFTODT
3029 if (dp->d_type != DT_UNKNOWN) {
3030 /* Got it. We need no more lstat. */
3031 new_pathtype = dp->d_type;
3032 }
3033#endif
3034 if (recursive && dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1) &&
3035 new_pathtype == path_unknown) {
3036 /* RECURSIVE never match dot files unless FNM_DOTMATCH is set */
3037 if (do_lstat(fd, buf, &st, flags, enc) == 0)
3038 new_pathtype = IFTODT(st.st_mode);
3039 else
3040 new_pathtype = path_noent;
3041 }
3042
3043 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2);
3044 if (!new_beg) {
3045 GLOB_FREE(buf);
3046 status = -1;
3047 break;
3048 }
3049
3050 for (cur = beg; cur < end; ++cur) {
3051 struct glob_pattern *p = *cur;
3052 struct dirent_brace_args args;
3053 if (p->type == RECURSIVE) {
3054 if (new_pathtype == path_directory || /* not symlink but real directory */
3055 new_pathtype == path_exist) {
3056 if (dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1))
3057 *new_end++ = p; /* append recursive pattern */
3058 }
3059 p = p->next; /* 0 times recursion */
3060 }
3061 switch (p->type) {
3062 case BRACE:
3063 args.name = name;
3064 args.dp = dp;
3065 args.flags = flags;
3066 if (ruby_brace_expand(p->str, flags, dirent_match_brace,
3067 (VALUE)&args, enc, Qfalse) > 0)
3068 *new_end++ = p->next;
3069 break;
3070 case ALPHA:
3071# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
3072 if (plainname) {
3073 *new_end++ = p->next;
3074 break;
3075 }
3076# endif
3077 case PLAIN:
3078 case MAGICAL:
3079 if (dirent_match(p->str, enc, name, dp, flags))
3080 *new_end++ = p->next;
3081 default:
3082 break;
3083 }
3084 }
3085
3086 status = glob_helper(fd, buf, baselen, name - buf - baselen + namlen, 1,
3087 new_pathtype, new_beg, new_end,
3088 flags, funcs, arg, enc);
3089 GLOB_FREE(buf);
3090 GLOB_FREE(new_beg);
3091 if (status) break;
3092 }
3093
3094 glob_dir_finish(&globent, flags);
3095 }
3096 else if (plain) {
3097 struct glob_pattern **copy_beg, **copy_end, **cur2;
3098
3099# if FNM_SYSCASE || NORMALIZE_UTF8PATH
3100 literally:
3101# endif
3102 copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
3103 if (!copy_beg) return -1;
3104 for (cur = beg; cur < end; ++cur)
3105 *copy_end++ = (*cur)->type <= ALPHA ? *cur : 0;
3106
3107 for (cur = copy_beg; cur < copy_end; ++cur) {
3108 if (*cur) {
3109 rb_pathtype_t new_pathtype = path_unknown;
3110 char *buf;
3111 char *name;
3112 size_t len = strlen((*cur)->str) + 1;
3113 name = GLOB_ALLOC_N(char, len);
3114 if (!name) {
3115 status = -1;
3116 break;
3117 }
3118 memcpy(name, (*cur)->str, len);
3119 if (escape)
3120 len = remove_backslashes(name, name+len-1, enc) - name;
3121
3122 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
3123 if (!new_beg) {
3124 GLOB_FREE(name);
3125 status = -1;
3126 break;
3127 }
3128 *new_end++ = (*cur)->next;
3129 for (cur2 = cur + 1; cur2 < copy_end; ++cur2) {
3130 if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) {
3131 *new_end++ = (*cur2)->next;
3132 *cur2 = 0;
3133 }
3134 }
3135
3136 buf = join_path(path, pathlen, dirsep, name, len);
3137 GLOB_FREE(name);
3138 if (!buf) {
3139 GLOB_FREE(new_beg);
3140 status = -1;
3141 break;
3142 }
3143#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
3144 if ((*cur)->type == ALPHA) {
3145 buf = replace_real_basename(buf, pathlen + (dirsep != 0), enc,
3146 IF_NORMALIZE_UTF8PATH(1)+0,
3147 flags, &new_pathtype);
3148 if (!buf) break;
3149 }
3150#endif
3151 status = glob_helper(fd, buf, baselen,
3152 namelen + strlen(buf + pathlen), 1,
3153 new_pathtype, new_beg, new_end,
3154 flags, funcs, arg, enc);
3155 GLOB_FREE(buf);
3156 GLOB_FREE(new_beg);
3157 if (status) break;
3158 }
3159 }
3160
3161 GLOB_FREE(copy_beg);
3162 }
3163
3164 return status;
3165}
3166
3167static int
3168push_caller(const char *path, VALUE val, void *enc)
3169{
3170 struct push_glob_args *arg = (struct push_glob_args *)val;
3171 struct glob_pattern *list;
3172 int status;
3173
3174 list = glob_make_pattern(path, path + strlen(path), arg->flags, enc);
3175 if (!list) {
3176 return -1;
3177 }
3178 status = glob_helper(arg->fd, arg->path, arg->baselen, arg->namelen, arg->dirsep,
3179 arg->pathtype, &list, &list + 1, arg->flags, arg->funcs,
3180 arg->arg, enc);
3181 glob_free_pattern(list);
3182 return status;
3183}
3184
3185static int ruby_glob0(const char *path, int fd, const char *base, int flags,
3186 const ruby_glob_funcs_t *funcs, VALUE arg, rb_encoding *enc);
3187
3188struct push_glob0_args {
3189 int fd;
3190 const char *base;
3191 int flags;
3192 const ruby_glob_funcs_t *funcs;
3193 VALUE arg;
3194};
3195
3196static int
3197push_glob0_caller(const char *path, VALUE val, void *enc)
3198{
3199 struct push_glob0_args *arg = (struct push_glob0_args *)val;
3200 return ruby_glob0(path, arg->fd, arg->base, arg->flags, arg->funcs, arg->arg, enc);
3201}
3202
3203static int
3204ruby_glob0(const char *path, int fd, const char *base, int flags,
3205 const ruby_glob_funcs_t *funcs, VALUE arg,
3206 rb_encoding *enc)
3207{
3208 struct glob_pattern *list;
3209 const char *root, *start;
3210 char *buf;
3211 size_t n, baselen = 0;
3212 int status, dirsep = FALSE;
3213
3214 start = root = path;
3215
3216 if (*root == '{') {
3217 struct push_glob0_args args;
3218 args.fd = fd;
3219 args.base = base;
3220 args.flags = flags;
3221 args.funcs = funcs;
3222 args.arg = arg;
3223 return ruby_brace_expand(path, flags, push_glob0_caller, (VALUE)&args, enc, Qfalse);
3224 }
3225
3226 flags |= FNM_SYSCASE;
3227#if defined DOSISH
3228 root = rb_enc_path_skip_prefix(root, root + strlen(root), enc);
3229#endif
3230
3231 if (*root == '/') root++;
3232
3233 n = root - start;
3234 if (!n && base) {
3235 n = strlen(base);
3236 baselen = n;
3237 start = base;
3238 dirsep = TRUE;
3239 }
3240 buf = GLOB_ALLOC_N(char, n + 1);
3241 if (!buf) return -1;
3242 MEMCPY(buf, start, char, n);
3243 buf[n] = '\0';
3244
3245 list = glob_make_pattern(root, root + strlen(root), flags, enc);
3246 if (!list) {
3247 GLOB_FREE(buf);
3248 return -1;
3249 }
3250 status = glob_helper(fd, buf, baselen, n-baselen, dirsep,
3251 path_unknown, &list, &list + 1,
3252 flags, funcs, arg, enc);
3253 glob_free_pattern(list);
3254 GLOB_FREE(buf);
3255
3256 return status;
3257}
3259int
3260ruby_glob(const char *path, int flags, ruby_glob_func *func, VALUE arg)
3261{
3262 ruby_glob_funcs_t funcs;
3263 funcs.match = func;
3264 funcs.error = 0;
3265 return ruby_glob0(path, AT_FDCWD, 0, flags & ~GLOB_VERBOSE,
3266 &funcs, arg, rb_ascii8bit_encoding());
3267}
3268
3269static int
3270rb_glob_caller(const char *path, VALUE a, void *enc)
3271{
3272 int status;
3273 struct glob_args *args = (struct glob_args *)a;
3274
3275 args->path = path;
3276 rb_protect(glob_func_caller, a, &status);
3277 return status;
3278}
3279
3280static const ruby_glob_funcs_t rb_glob_funcs = {
3281 rb_glob_caller, rb_glob_error,
3282};
3283
3284void
3285rb_glob(const char *path, void (*func)(const char *, VALUE, void *), VALUE arg)
3286{
3287 struct glob_args args;
3288 int status;
3289
3290 args.func = func;
3291 args.value = arg;
3292 args.enc = rb_ascii8bit_encoding();
3293
3294 status = ruby_glob0(path, AT_FDCWD, 0, GLOB_VERBOSE, &rb_glob_funcs,
3295 (VALUE)&args, args.enc);
3296 if (status) GLOB_JUMP_TAG(status);
3297}
3298
3299static void
3300push_pattern(const char *path, VALUE ary, void *enc)
3301{
3302#if defined _WIN32 || defined __APPLE__
3303 VALUE name = rb_utf8_str_new_cstr(path);
3304 rb_encoding *eenc = rb_default_internal_encoding();
3305 name = rb_str_conv_enc(name, NULL, eenc ? eenc : enc);
3306#else
3307 VALUE name = rb_external_str_new_with_enc(path, strlen(path), enc);
3308#endif
3309 rb_ary_push(ary, name);
3310}
3311
3312static int
3313ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg,
3314 rb_encoding *enc, VALUE var)
3315{
3316 const int escape = !(flags & FNM_NOESCAPE);
3317 const char *p = str;
3318 const char *pend = p + strlen(p);
3319 const char *s = p;
3320 const char *lbrace = 0, *rbrace = 0;
3321 int nest = 0, status = 0;
3322
3323 while (*p) {
3324 if (*p == '{' && nest++ == 0) {
3325 lbrace = p;
3326 }
3327 if (*p == '}' && lbrace && --nest == 0) {
3328 rbrace = p;
3329 break;
3330 }
3331 if (*p == '\\' && escape) {
3332 if (!*++p) break;
3333 }
3334 Inc(p, pend, enc);
3335 }
3336
3337 if (lbrace && rbrace) {
3338 size_t len = strlen(s) + 1;
3339 char *buf = GLOB_ALLOC_N(char, len);
3340 long shift;
3341
3342 if (!buf) return -1;
3343 memcpy(buf, s, lbrace-s);
3344 shift = (lbrace-s);
3345 p = lbrace;
3346 while (p < rbrace) {
3347 const char *t = ++p;
3348 nest = 0;
3349 while (p < rbrace && !(*p == ',' && nest == 0)) {
3350 if (*p == '{') nest++;
3351 if (*p == '}') nest--;
3352 if (*p == '\\' && escape) {
3353 if (++p == rbrace) break;
3354 }
3355 Inc(p, pend, enc);
3356 }
3357 memcpy(buf+shift, t, p-t);
3358 strlcpy(buf+shift+(p-t), rbrace+1, len-(shift+(p-t)));
3359 status = ruby_brace_expand(buf, flags, func, arg, enc, var);
3360 if (status) break;
3361 }
3362 GLOB_FREE(buf);
3363 }
3364 else if (!lbrace && !rbrace) {
3365 status = glob_call_func(func, s, arg, enc);
3366 }
3367
3368 RB_GC_GUARD(var);
3369 return status;
3371
3372struct brace_args {
3373 ruby_glob_funcs_t funcs;
3374 VALUE value;
3375 int flags;
3376};
3377
3378static int
3379glob_brace(const char *path, VALUE val, void *enc)
3380{
3381 struct brace_args *arg = (struct brace_args *)val;
3382
3383 return ruby_glob0(path, AT_FDCWD, 0, arg->flags, &arg->funcs, arg->value, enc);
3384}
3385
3386int
3387ruby_brace_glob_with_enc(const char *str, int flags, ruby_glob_func *func, VALUE arg, rb_encoding *enc)
3388{
3389 struct brace_args args;
3390
3391 flags &= ~GLOB_VERBOSE;
3392 args.funcs.match = func;
3393 args.funcs.error = 0;
3394 args.value = arg;
3395 args.flags = flags;
3396 return ruby_brace_expand(str, flags, glob_brace, (VALUE)&args, enc, Qfalse);
3397}
3399int
3400ruby_brace_glob(const char *str, int flags, ruby_glob_func *func, VALUE arg)
3401{
3402 return ruby_brace_glob_with_enc(str, flags, func, arg, rb_ascii8bit_encoding());
3403}
3404
3405static int
3406push_glob(VALUE ary, VALUE str, VALUE base, int flags)
3407{
3408 struct glob_args args;
3409 int fd;
3410 rb_encoding *enc = rb_enc_get(str);
3411
3412#if defined _WIN32 || defined __APPLE__
3413 str = rb_str_encode_ospath(str);
3414#endif
3415 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3416 enc = rb_filesystem_encoding();
3417 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3418 enc = rb_ascii8bit_encoding();
3419 flags |= GLOB_VERBOSE;
3420 args.func = push_pattern;
3421 args.value = ary;
3422 args.enc = enc;
3423 args.base = 0;
3424 fd = AT_FDCWD;
3425 if (!NIL_P(base)) {
3426 if (!RB_TYPE_P(base, T_STRING) || !rb_enc_check(str, base)) {
3427 struct dir_data *dirp = RTYPEDDATA_GET_DATA(base);
3428 if (!dirp->dir) dir_closed();
3429#ifdef HAVE_DIRFD
3430 if ((fd = dirfd(dirp->dir)) == -1)
3431 rb_sys_fail_path(dir_inspect(base));
3432#endif
3433 base = dirp->path;
3434 }
3435 args.base = RSTRING_PTR(base);
3436 }
3437#if defined _WIN32 || defined __APPLE__
3438 enc = rb_utf8_encoding();
3439#endif
3440
3441 return ruby_glob0(RSTRING_PTR(str), fd, args.base, flags, &rb_glob_funcs,
3442 (VALUE)&args, enc);
3443}
3444
3445static VALUE
3446rb_push_glob(VALUE str, VALUE base, int flags) /* '\0' is delimiter */
3447{
3448 VALUE ary;
3449 int status;
3450
3451 /* can contain null bytes as separators */
3452 if (!RB_TYPE_P(str, T_STRING)) {
3453 FilePathValue(str);
3454 }
3455 else if (!rb_str_to_cstr(str)) {
3456 rb_raise(rb_eArgError, "nul-separated glob pattern is deprecated");
3457 }
3458 else {
3459 rb_enc_check(str, rb_enc_from_encoding(rb_usascii_encoding()));
3460 }
3461 ary = rb_ary_new();
3462
3463 status = push_glob(ary, str, base, flags);
3464 if (status) GLOB_JUMP_TAG(status);
3465
3466 return ary;
3467}
3468
3469static VALUE
3470dir_globs(VALUE args, VALUE base, int flags)
3471{
3472 VALUE ary = rb_ary_new();
3473 long i;
3474
3475 for (i = 0; i < RARRAY_LEN(args); ++i) {
3476 int status;
3477 VALUE str = RARRAY_AREF(args, i);
3478 FilePathValue(str);
3479 status = push_glob(ary, str, base, flags);
3480 if (status) GLOB_JUMP_TAG(status);
3481 }
3482 RB_GC_GUARD(args);
3483
3484 return ary;
3485}
3486
3487static VALUE
3488dir_glob_option_base(VALUE base)
3489{
3490 if (NIL_OR_UNDEF_P(base)) {
3491 return Qnil;
3492 }
3493#if USE_OPENDIR_AT
3494 if (rb_typeddata_is_kind_of(base, &dir_data_type)) {
3495 return base;
3496 }
3497#endif
3498 FilePathValue(base);
3499 if (!RSTRING_LEN(base)) return Qnil;
3500 return base;
3501}
3502
3503static int
3504dir_glob_option_sort(VALUE sort)
3505{
3506 return (rb_bool_expected(sort, "sort", TRUE) ? 0 : FNM_GLOB_NOSORT);
3507}
3508
3509static VALUE
3510dir_s_aref(rb_execution_context_t *ec, VALUE obj, VALUE args, VALUE base, VALUE sort)
3511{
3512 const int flags = dir_glob_option_sort(sort);
3513 base = dir_glob_option_base(base);
3514 if (RARRAY_LEN(args) == 1) {
3515 return rb_push_glob(RARRAY_AREF(args, 0), base, flags);
3516 }
3517 return dir_globs(args, base, flags);
3518}
3519
3520static VALUE
3521dir_s_glob(rb_execution_context_t *ec, VALUE obj, VALUE str, VALUE rflags, VALUE base, VALUE sort)
3522{
3523 VALUE ary = rb_check_array_type(str);
3524 const int flags = (NUM2INT(rflags) | dir_glob_option_sort(sort)) & ~FNM_CASEFOLD;
3525 base = dir_glob_option_base(base);
3526 if (NIL_P(ary)) {
3527 ary = rb_push_glob(str, base, flags);
3528 }
3529 else {
3530 ary = dir_globs(ary, base, flags);
3531 }
3532
3533 if (rb_block_given_p()) {
3534 rb_ary_each(ary);
3535 return Qnil;
3536 }
3537 return ary;
3538}
3539
3540static VALUE
3541dir_open_dir(int argc, VALUE *argv)
3542{
3543 VALUE dir = rb_funcallv_kw(rb_cDir, rb_intern("open"), argc, argv, RB_PASS_CALLED_KEYWORDS);
3544
3545 rb_check_typeddata(dir, &dir_data_type);
3546 return dir;
3547}
3548
3549
3550/*
3551 * call-seq:
3552 * Dir.foreach(dirpath, encoding: 'UTF-8') {|entry_name| ... } -> nil
3553 *
3554 * Calls the block with each entry name in the directory at +dirpath+;
3555 * sets the given encoding onto each passed +entry_name+:
3556 *
3557 * Dir.foreach('/example') {|entry_name| p entry_name }
3558 *
3559 * Output:
3560 *
3561 * "config.h"
3562 * "lib"
3563 * "main.rb"
3564 * ".."
3565 * "."
3566 *
3567 * Encoding:
3568 *
3569 * Dir.foreach('/example') {|entry_name| p entry_name.encoding; break }
3570 * Dir.foreach('/example', encoding: 'US-ASCII') {|entry_name| p entry_name.encoding; break }
3571 *
3572 * Output:
3573 *
3574 * #<Encoding:UTF-8>
3575 * #<Encoding:US-ASCII>
3576 *
3577 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3578 *
3579 * Returns an enumerator if no block is given.
3580 */
3581static VALUE
3582dir_foreach(int argc, VALUE *argv, VALUE io)
3583{
3584 VALUE dir;
3585
3586 RETURN_ENUMERATOR(io, argc, argv);
3587 dir = dir_open_dir(argc, argv);
3588 rb_ensure(dir_each, dir, dir_close, dir);
3589 return Qnil;
3590}
3591
3592static VALUE
3593dir_entry_ary_push(VALUE ary, VALUE entry, struct dir_entry_args *_unused)
3594{
3595 return rb_ary_push(ary, entry);
3596}
3597
3598static VALUE
3599dir_collect(VALUE dir)
3600{
3601 VALUE ary = rb_ary_new();
3602 dir_each_entry(dir, dir_entry_ary_push, ary, FALSE);
3603 return ary;
3604}
3605
3606/*
3607 * call-seq:
3608 * Dir.entries(dirname, encoding: 'UTF-8') -> array
3609 *
3610 * Returns an array of the entry names in the directory at +dirpath+;
3611 * sets the given encoding onto each returned entry name:
3612 *
3613 * Dir.entries('/example') # => ["config.h", "lib", "main.rb", "..", "."]
3614 * Dir.entries('/example').first.encoding
3615 * # => #<Encoding:UTF-8>
3616 * Dir.entries('/example', encoding: 'US-ASCII').first.encoding
3617 * # => #<Encoding:US-ASCII>
3618 *
3619 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3620 *
3621 * Raises an exception if the directory does not exist.
3622 */
3623static VALUE
3624dir_entries(int argc, VALUE *argv, VALUE io)
3625{
3626 VALUE dir;
3627
3628 dir = dir_open_dir(argc, argv);
3629 return rb_ensure(dir_collect, dir, dir_close, dir);
3630}
3631
3632static VALUE
3633dir_each_child(VALUE dir)
3634{
3635 return dir_each_entry(dir, dir_yield, Qnil, TRUE);
3636}
3637
3638/*
3639 * call-seq:
3640 * Dir.each_child(dirpath) {|entry_name| ... } -> nil
3641 * Dir.each_child(dirpath, encoding: 'UTF-8') {|entry_name| ... } -> nil
3642 *
3643 * Like Dir.foreach, except that entries <tt>'.'</tt> and <tt>'..'</tt>
3644 * are not included.
3645 */
3646static VALUE
3647dir_s_each_child(int argc, VALUE *argv, VALUE io)
3648{
3649 VALUE dir;
3650
3651 RETURN_ENUMERATOR(io, argc, argv);
3652 dir = dir_open_dir(argc, argv);
3653 rb_ensure(dir_each_child, dir, dir_close, dir);
3654 return Qnil;
3655}
3656
3657/*
3658 * call-seq:
3659 * each_child {|entry_name| ... } -> self
3660 *
3661 * Calls the block with each entry name in +self+
3662 * except <tt>'.'</tt> and <tt>'..'</tt>:
3663 *
3664 * dir = Dir.new('/example')
3665 * dir.each_child {|entry_name| p entry_name }
3666 *
3667 * Output:
3668 *
3669 * "config.h"
3670 * "lib"
3671 * "main.rb"
3672 *
3673 * If no block is given, returns an enumerator.
3674 */
3675static VALUE
3676dir_each_child_m(VALUE dir)
3677{
3678 RETURN_ENUMERATOR(dir, 0, 0);
3679 return dir_each_entry(dir, dir_yield, Qnil, TRUE);
3680}
3681
3682/*
3683 * call-seq:
3684 * children -> array
3685 *
3686 * Returns an array of the entry names in +self+
3687 * except for <tt>'.'</tt> and <tt>'..'</tt>:
3688 *
3689 * dir = Dir.new('/example')
3690 * dir.children # => ["config.h", "lib", "main.rb"]
3691 *
3692 */
3693static VALUE
3694dir_collect_children(VALUE dir)
3695{
3696 VALUE ary = rb_ary_new();
3697 dir_each_entry(dir, dir_entry_ary_push, ary, TRUE);
3698 return ary;
3699}
3700
3701/*
3702 * call-seq:
3703 * children -> array
3704 *
3705 * Returns an array of the entry names in +self+ along with their type
3706 * except for <tt>'.'</tt> and <tt>'..'</tt>:
3707 *
3708 * dir = Dir.new('/example')
3709 * dir.scan # => [["config.h", :file], ["lib", :directory], ["main.rb", :file]]
3710 *
3711 */
3712static VALUE
3713dir_scan_children(VALUE dir)
3714{
3715 if (rb_block_given_p()) {
3716 dir_each_entry(dir, dir_yield_with_type, Qnil, TRUE);
3717 return Qnil;
3718 }
3719 else {
3720 VALUE ary = rb_ary_new();
3721 dir_each_entry(dir, dir_yield_with_type, ary, TRUE);
3722 return ary;
3723 }
3724}
3725
3726/*
3727 * call-seq:
3728 * Dir.children(dirpath) -> array
3729 * Dir.children(dirpath, encoding: 'UTF-8') -> array
3730 *
3731 * Returns an array of the entry names in the directory at +dirpath+
3732 * except for <tt>'.'</tt> and <tt>'..'</tt>;
3733 * sets the given encoding onto each returned entry name:
3734 *
3735 * Dir.children('/example') # => ["config.h", "lib", "main.rb"]
3736 * Dir.children('/example').first.encoding
3737 * # => #<Encoding:UTF-8>
3738 * Dir.children('/example', encoding: 'US-ASCII').first.encoding
3739 * # => #<Encoding:US-ASCII>
3740 *
3741 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3742 *
3743 * Raises an exception if the directory does not exist.
3744 */
3745static VALUE
3746dir_s_children(int argc, VALUE *argv, VALUE io)
3747{
3748 VALUE dir;
3749
3750 dir = dir_open_dir(argc, argv);
3751 return rb_ensure(dir_collect_children, dir, dir_close, dir);
3752}
3753
3754/*
3755 * call-seq:
3756 * Dir.scan(dirpath) {|entry_name, entry_type| ... } -> nil
3757 * Dir.scan(dirpath, encoding: 'UTF-8') {|entry_name, entry_type| ... } -> nil
3758 * Dir.scan(dirpath) -> [[entry_name, entry_type], ...]
3759 * Dir.scan(dirpath, encoding: 'UTF-8') -> [[entry_name, entry_type], ...]
3760 *
3761 * Yields or returns an array of the entry names in the directory at +dirpath+
3762 * associated with their type, except for <tt>'.'</tt> and <tt>'..'</tt>;
3763 * sets the given encoding onto each returned entry name.
3764 *
3765 * The type symbol is one of:
3766 * ``<code>:file</code>'', ``<code>:directory</code>'',
3767 * ``<code>:characterSpecial</code>'', ``<code>:blockSpecial</code>'',
3768 * ``<code>:fifo</code>'', ``<code>:link</code>'',
3769 * or ``<code>:socket</code>'':
3770 *
3771 * Dir.children('/example') # => [["config.h", :file], ["lib", :directory], ["main.rb", :file]]
3772 * Dir.children('/example').first.first.encoding
3773 * # => #<Encoding:UTF-8>
3774 * Dir.children('/example', encoding: 'US-ASCII').first.encoding
3775 * # => #<Encoding:US-ASCII>
3776 *
3777 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3778 *
3779 * Raises an exception if the directory does not exist.
3780 */
3781static VALUE
3782dir_s_scan(int argc, VALUE *argv, VALUE klass)
3783{
3784 VALUE dir = dir_open_dir(argc, argv);
3785 return rb_ensure(dir_scan_children, dir, dir_close, dir);
3786}
3787
3788static int
3789fnmatch_brace(const char *pattern, VALUE val, void *enc)
3790{
3791 struct brace_args *arg = (struct brace_args *)val;
3792 VALUE path = arg->value;
3793 rb_encoding *enc_pattern = enc;
3794 rb_encoding *enc_path = rb_enc_get(path);
3795
3796 if (enc_pattern != enc_path) {
3797 if (!rb_enc_asciicompat(enc_pattern))
3798 return FNM_NOMATCH;
3799 if (!rb_enc_asciicompat(enc_path))
3800 return FNM_NOMATCH;
3801 if (!rb_enc_str_asciionly_p(path)) {
3802 int cr = ENC_CODERANGE_7BIT;
3803 long len = strlen(pattern);
3804 if (rb_str_coderange_scan_restartable(pattern, pattern + len,
3805 enc_pattern, &cr) != len)
3806 return FNM_NOMATCH;
3807 if (cr != ENC_CODERANGE_7BIT)
3808 return FNM_NOMATCH;
3809 }
3810 }
3811 return (fnmatch(pattern, enc, RSTRING_PTR(path), arg->flags) == 0);
3812}
3813
3814/* :nodoc: */
3815static VALUE
3816file_s_fnmatch(int argc, VALUE *argv, VALUE obj)
3817{
3818 VALUE pattern, path;
3819 VALUE rflags;
3820 int flags;
3821
3822 if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
3823 flags = NUM2INT(rflags);
3824 else
3825 flags = 0;
3826
3827 StringValueCStr(pattern);
3828 FilePathStringValue(path);
3829
3830 if (flags & FNM_EXTGLOB) {
3831 struct brace_args args;
3832
3833 args.value = path;
3834 args.flags = flags;
3835 if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
3836 (VALUE)&args, rb_enc_get(pattern), pattern) > 0)
3837 return Qtrue;
3838 }
3839 else {
3840 rb_encoding *enc = rb_enc_compatible(pattern, path);
3841 if (!enc) return Qfalse;
3842 if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
3843 return Qtrue;
3844 }
3845 RB_GC_GUARD(pattern);
3846
3847 return Qfalse;
3848}
3849
3850/*
3851 * call-seq:
3852 * Dir.home(user_name = nil) -> dirpath
3853 *
3854 * Returns the home directory path of the user specified with +user_name+
3855 * if it is not +nil+, or the current login user:
3856 *
3857 * Dir.home # => "/home/me"
3858 * Dir.home('root') # => "/root"
3859 *
3860 * Raises ArgumentError if +user_name+ is not a user name.
3861 */
3862static VALUE
3863dir_s_home(int argc, VALUE *argv, VALUE obj)
3864{
3865 VALUE user;
3866 const char *u = 0;
3867
3868 rb_check_arity(argc, 0, 1);
3869 user = (argc > 0) ? argv[0] : Qnil;
3870 if (!NIL_P(user)) {
3871 StringValue(user);
3872 rb_must_asciicompat(user);
3873 u = StringValueCStr(user);
3874 if (*u) {
3875 return rb_home_dir_of(user, rb_str_new(0, 0));
3876 }
3877 }
3878 return rb_default_home_dir(rb_str_new(0, 0));
3879
3880}
3881
3882#if 0
3883/*
3884 * call-seq:
3885 * Dir.exist?(dirpath) -> true or false
3886 *
3887 * Returns whether +dirpath+ is a directory in the underlying file system:
3888 *
3889 * Dir.exist?('/example') # => true
3890 * Dir.exist?('/nosuch') # => false
3891 * Dir.exist?('/example/main.rb') # => false
3892 *
3893 * Same as File.directory?.
3894 *
3895 */
3896VALUE
3897rb_file_directory_p(void)
3898{
3899}
3900#endif
3901
3902static void *
3903nogvl_dir_empty_p(void *ptr)
3904{
3905 const char *path = ptr;
3906 DIR *dir = opendir(path);
3907 struct dirent *dp;
3908 VALUE result = Qtrue;
3909
3910 if (!dir) {
3911 int e = errno;
3912 switch (gc_for_fd_with_gvl(e)) {
3913 default:
3914 dir = opendir(path);
3915 if (dir) break;
3916 e = errno;
3917 /* fall through */
3918 case 0:
3919 if (e == ENOTDIR) return (void *)Qfalse;
3920 return (void *)INT2FIX(e);
3921 }
3922 }
3923 while ((dp = READDIR_NOGVL(dir, NULL)) != NULL) {
3924 if (!to_be_skipped(dp)) {
3925 result = Qfalse;
3926 break;
3927 }
3928 }
3929 check_closedir(dir);
3930 return (void *)result;
3931}
3932
3933/*
3934 * call-seq:
3935 * Dir.empty?(dirpath) -> true or false
3936 *
3937 * Returns whether +dirpath+ specifies an empty directory:
3938 *
3939 * dirpath = '/tmp/foo'
3940 * Dir.mkdir(dirpath)
3941 * Dir.empty?(dirpath) # => true
3942 * Dir.empty?('/example') # => false
3943 * Dir.empty?('/example/main.rb') # => false
3944 *
3945 * Raises an exception if +dirpath+ does not specify a directory or file
3946 * in the underlying file system.
3947 */
3948static VALUE
3949rb_dir_s_empty_p(VALUE obj, VALUE dirname)
3950{
3951 VALUE result, orig;
3952 const char *path;
3953 enum {false_on_notdir = 1};
3954
3955 FilePathValue(dirname);
3956 orig = rb_str_dup_frozen(dirname);
3957 dirname = rb_str_encode_ospath(dirname);
3958 dirname = rb_str_dup_frozen(dirname);
3959 path = RSTRING_PTR(dirname);
3960
3961#if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT
3962 {
3963 u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
3964 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
3965 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, 0);
3966 if (gvl_getattrlist(&args, path) != 0)
3967 rb_sys_fail_path(orig);
3968 if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) {
3969 al.commonattr = 0;
3970 al.dirattr = ATTR_DIR_ENTRYCOUNT;
3971 if (gvl_getattrlist(&args, path) == 0) {
3972 if (attrbuf[0] >= 2 * sizeof(u_int32_t))
3973 return RBOOL(attrbuf[1] == 0);
3974 if (false_on_notdir) return Qfalse;
3975 }
3976 rb_sys_fail_path(orig);
3977 }
3978 }
3979#endif
3980
3981 result = (VALUE)IO_WITHOUT_GVL(nogvl_dir_empty_p, (void *)path);
3982 if (FIXNUM_P(result)) {
3983 rb_syserr_fail_path((int)FIX2LONG(result), orig);
3984 }
3985 return result;
3986}
3987
3988void
3989Init_Dir(void)
3990{
3991 sym_directory = ID2SYM(rb_intern("directory"));
3992 sym_link = ID2SYM(rb_intern("link"));
3993 sym_file = ID2SYM(rb_intern("file"));
3994 sym_unknown = ID2SYM(rb_intern("unknown"));
3995
3996#if defined(DT_BLK) || defined(S_IFBLK)
3997 sym_block_device = ID2SYM(rb_intern("blockSpecial"));
3998#endif
3999#if defined(DT_CHR) || defined(S_IFCHR)
4000 sym_character_device = ID2SYM(rb_intern("characterSpecial"));
4001#endif
4002#if defined(DT_FIFO) || defined(S_IFIFO)
4003 sym_fifo = ID2SYM(rb_intern("fifo"));
4004#endif
4005#if defined(DT_SOCK) || defined(S_IFSOCK)
4006 sym_socket = ID2SYM(rb_intern("socket"));
4007#endif
4008
4009 rb_gc_register_address(&chdir_lock.path);
4010 rb_gc_register_address(&chdir_lock.thread);
4011
4013
4015
4016 rb_define_alloc_func(rb_cDir, dir_s_alloc);
4017 rb_define_singleton_method(rb_cDir,"for_fd", dir_s_for_fd, 1);
4018 rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, -1);
4019 rb_define_singleton_method(rb_cDir, "entries", dir_entries, -1);
4020 rb_define_singleton_method(rb_cDir, "each_child", dir_s_each_child, -1);
4021 rb_define_singleton_method(rb_cDir, "children", dir_s_children, -1);
4022 rb_define_singleton_method(rb_cDir, "scan", dir_s_scan, -1);
4023
4024 rb_define_method(rb_cDir,"fileno", dir_fileno, 0);
4025 rb_define_method(rb_cDir,"path", dir_path, 0);
4026 rb_define_method(rb_cDir,"to_path", dir_path, 0);
4027 rb_define_method(rb_cDir,"inspect", dir_inspect, 0);
4028 rb_define_method(rb_cDir,"read", dir_read, 0);
4029 rb_define_method(rb_cDir,"each", dir_each, 0);
4030 rb_define_method(rb_cDir,"each_child", dir_each_child_m, 0);
4031 rb_define_method(rb_cDir,"children", dir_collect_children, 0);
4032 rb_define_method(rb_cDir,"scan", dir_scan_children, 0);
4033 rb_define_method(rb_cDir,"rewind", dir_rewind, 0);
4034 rb_define_method(rb_cDir,"tell", dir_tell, 0);
4035 rb_define_method(rb_cDir,"seek", dir_seek, 1);
4036 rb_define_method(rb_cDir,"pos", dir_tell, 0);
4037 rb_define_method(rb_cDir,"pos=", dir_set_pos, 1);
4038 rb_define_method(rb_cDir,"close", dir_close, 0);
4039 rb_define_method(rb_cDir,"chdir", dir_chdir, 0);
4040
4041 rb_define_singleton_method(rb_cDir,"fchdir", dir_s_fchdir, 1);
4042 rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1);
4043 rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0);
4044 rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0);
4045 rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1);
4046 rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1);
4047 rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1);
4048 rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1);
4049 rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1);
4050 rb_define_singleton_method(rb_cDir,"home", dir_s_home, -1);
4051
4052 rb_define_singleton_method(rb_cDir,"exist?", rb_file_directory_p, 1);
4053 rb_define_singleton_method(rb_cDir,"empty?", rb_dir_s_empty_p, 1);
4054
4055 rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1);
4056 rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1);
4057
4058 /* {File::FNM_NOESCAPE}[rdoc-ref:File::Constants@File-3A-3AFNM_NOESCAPE] */
4059 rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE));
4060 /* {File::FNM_PATHNAME}[rdoc-ref:File::Constants@File-3A-3AFNM_PATHNAME] */
4061 rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME));
4062 /* {File::FNM_DOTMATCH}[rdoc-ref:File::Constants@File-3A-3AFNM_DOTMATCH] */
4063 rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH));
4064 /* {File::FNM_CASEFOLD}[rdoc-ref:File::Constants@File-3A-3AFNM_CASEFOLD] */
4065 rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD));
4066 /* {File::FNM_EXTGLOB}[rdoc-ref:File::Constants@File-3A-3AFNM_EXTGLOB] */
4067 rb_file_const("FNM_EXTGLOB", INT2FIX(FNM_EXTGLOB));
4068 /* {File::FNM_SYSCASE}[rdoc-ref:File::Constants@File-3A-3AFNM_SYSCASE] */
4069 rb_file_const("FNM_SYSCASE", INT2FIX(FNM_SYSCASE));
4070 /* {File::FNM_SHORTNAME}[rdoc-ref:File::Constants@File-3A-3AFNM_SHORTNAME] */
4071 rb_file_const("FNM_SHORTNAME", INT2FIX(FNM_SHORTNAME));
4072}
4073
4074#include "dir.rbinc"
#define RUBY_DEBUG
Define this macro when you want assertions.
Definition assert.h:88
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
Definition glob.h:49
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1803
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1596
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:3255
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1017
#define rb_str_new2
Old name of rb_str_new_cstr.
Definition string.h:1676
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
Definition coderange.h:180
#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 INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define rb_str_cat2
Old name of rb_str_cat_cstr.
Definition string.h:1684
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define ISALPHA
Old name of rb_isalpha.
Definition ctype.h:92
#define ISASCII
Old name of rb_isascii.
Definition ctype.h:85
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define NIL_P
Old name of RB_NIL_P.
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
Definition encoding.h:516
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
void rb_syserr_fail(int e, const char *mesg)
Raises appropriate exception that represents a C errno.
Definition error.c:3958
VALUE rb_eIOError
IOError exception.
Definition io.c:189
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:3964
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1416
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
Definition error.c:1404
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:466
VALUE rb_cDir
Dir class.
Definition dir.c:504
VALUE rb_cObject
Object class.
Definition object.c:61
VALUE rb_mEnumerable
Enumerable module.
Definition enum.c:27
VALUE rb_cFile
File class.
Definition file.c:192
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
Definition gc.h:603
Encoding relates APIs.
static unsigned int rb_enc_codepoint(const char *p, const char *e, rb_encoding *enc)
Queries the code point of character pointed by the passed pointer.
Definition encoding.h:571
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
Definition string.c:1325
VALUE rb_enc_str_new_cstr(const char *ptr, rb_encoding *enc)
Identical to rb_enc_str_new(), except it assumes the passed pointer is a pointer to a C string.
Definition string.c:1138
VALUE rb_external_str_new_with_enc(const char *ptr, long len, rb_encoding *enc)
Identical to rb_external_str_new(), except it additionally takes an encoding.
Definition string.c:1331
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:949
long rb_str_coderange_scan_restartable(const char *str, const char *end, rb_encoding *enc, int *cr)
Scans the passed string until it finds something odd.
Definition string.c:814
VALUE rb_funcallv_kw(VALUE recv, ID mid, int argc, const VALUE *argv, int kw_splat)
Identical to rb_funcallv(), except you can specify how to handle the last element of the given array.
Definition vm_eval.c:1084
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_ary_each(VALUE ary)
Iteratively yields each element of the passed array to the implicitly passed block if any.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_new(void)
Allocates a new, empty array.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
VALUE rb_assoc_new(VALUE car, VALUE cdr)
Identical to rb_ary_new_from_values(), except it expects exactly two parameters.
#define RETURN_ENUMERATOR(obj, argc, argv)
Identical to RETURN_SIZED_ENUMERATOR(), except its size is unknown.
Definition enumerator.h:242
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
#define rb_utf8_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "UTF-8" encoding.
Definition string.h:1584
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:3816
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:3169
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:1979
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2773
#define rb_str_dup_frozen
Just another name of rb_str_new_frozen.
Definition string.h:632
#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:1515
VALUE rb_thread_current(void)
Obtains the "current" thread.
Definition thread.c:3193
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
Definition variable.c:500
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
int len
Length of the buffer.
Definition io.h:8
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
Definition thread.c:2062
void ruby_qsort(void *, const size_t, const size_t, int(*)(const void *, const void *, void *), void *)
Reentrant implementation of quick sort.
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:579
#define RB_NUM2INT
Just another name of rb_num2int_inline.
Definition int.h:38
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
Definition vm_eval.c:1395
VALUE rb_yield_values2(int n, const VALUE *argv)
Identical to rb_yield_values(), except it takes the parameters as a C array instead of variadic argum...
Definition vm_eval.c:1417
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1372
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition memory.h:372
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
Definition memory.h:360
static int rb_mul_size_overflow(size_t a, size_t b, size_t max, size_t *c)
Definition memory.h:544
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
Definition mode_t.h:28
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#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 RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
Definition rstring.h:450
#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_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
Definition rtypeddata.h:119
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:736
#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:561
#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 RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
Definition scan_args.h:78
Definition dir.h:21
Definition dir.c:920
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:211
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