Ruby 4.1.0dev (2026-05-15 revision a8bcae043f931d9b79f1cb1fe2c021985d07b984)
dir.c (a8bcae043f931d9b79f1cb1fe2c021985d07b984)
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
1588static VALUE last_cwd;
1589
1590#ifndef _WIN32
1591static VALUE
1592getcwd_to_str(VALUE arg)
1593{
1594 const char *path = (const char *)arg;
1595#ifdef __APPLE__
1596 return rb_str_normalize_ospath(path, strlen(path));
1597#else
1598 return rb_str_new2(path);
1599#endif
1600}
1601
1602static VALUE
1603getcwd_xfree(VALUE arg)
1604{
1605 xfree((void *)arg);
1606 return Qnil;
1607}
1608
1609static VALUE
1610rb_dir_getwd_ospath_slowpath(void)
1611{
1612 char *path = ruby_getcwd();
1613 return rb_ensure(getcwd_to_str, (VALUE)path, getcwd_xfree, (VALUE)path);
1614}
1615
1616VALUE
1617rb_dir_getwd_ospath(void)
1618{
1619 char buf[PATH_MAX];
1620 char *path = getcwd(buf, PATH_MAX);
1621 if (!path) {
1622 return rb_dir_getwd_ospath_slowpath();
1623 }
1624
1625 VALUE cached_cwd = RUBY_ATOMIC_VALUE_LOAD(last_cwd);
1626
1627 if (!cached_cwd || strcmp(RSTRING_PTR(cached_cwd), path) != 0) {
1628#ifdef __APPLE__
1629 cached_cwd = rb_str_normalize_ospath(path, strlen(path));
1630#else
1631 cached_cwd = rb_str_new2(path);
1632#endif
1633 rb_str_freeze(cached_cwd);
1634 RUBY_ATOMIC_VALUE_SET(last_cwd, cached_cwd);
1635 }
1636 return cached_cwd;
1637}
1638#endif
1640VALUE
1641rb_dir_getwd(void)
1642{
1643 rb_encoding *fs = rb_filesystem_encoding();
1644 int fsenc = rb_enc_to_index(fs);
1645 VALUE cwd = rb_str_new_shared(rb_dir_getwd_ospath());
1646
1647 switch (fsenc) {
1648 case ENCINDEX_US_ASCII:
1649 fsenc = ENCINDEX_ASCII_8BIT;
1650 case ENCINDEX_ASCII_8BIT:
1651 break;
1652#if defined _WIN32 || defined __APPLE__
1653 default:
1654 return rb_str_conv_enc(cwd, NULL, fs);
1655#endif
1656 }
1657 return rb_enc_associate_index(cwd, fsenc);
1658}
1659
1660/*
1661 * call-seq:
1662 * Dir.pwd -> string
1663 *
1664 * Returns the path to the current working directory:
1665 *
1666 * Dir.chdir("/tmp") # => 0
1667 * Dir.pwd # => "/tmp"
1668 *
1669 */
1670static VALUE
1671dir_s_getwd(VALUE dir)
1672{
1673 return rb_dir_getwd();
1674}
1675
1676static VALUE
1677check_dirname(VALUE dir)
1678{
1679 VALUE d = dir;
1680 char *path, *pend;
1681 long len;
1682 rb_encoding *enc;
1683
1684 FilePathValue(d);
1685 enc = rb_enc_get(d);
1686 RSTRING_GETMEM(d, path, len);
1687 pend = path + len;
1688 pend = rb_enc_path_end(rb_enc_path_skip_prefix(path, pend, enc), pend, enc);
1689 if (pend - path < len) {
1690 d = rb_str_subseq(d, 0, pend - path);
1691 StringValueCStr(d);
1692 }
1693 return rb_str_encode_ospath(d);
1694}
1695
1696#if defined(HAVE_CHROOT)
1697static void *
1698nogvl_chroot(void *dirname)
1699{
1700 return (void *)(VALUE)chroot((const char *)dirname);
1701}
1702
1703/*
1704 * call-seq:
1705 * Dir.chroot(dirpath) -> 0
1706 *
1707 * Changes the root directory of the calling process to that specified in +dirpath+.
1708 * The new root directory is used for pathnames beginning with <tt>'/'</tt>.
1709 * The root directory is inherited by all children of the calling process.
1710 *
1711 * Only a privileged process may call +chroot+.
1712 *
1713 * See {Linux chroot}[https://man7.org/linux/man-pages/man2/chroot.2.html].
1714 */
1715static VALUE
1716dir_s_chroot(VALUE dir, VALUE path)
1717{
1718 path = check_dirname(path);
1719 if (IO_WITHOUT_GVL_INT(nogvl_chroot, (void *)RSTRING_PTR(path)) == -1)
1720 rb_sys_fail_path(path);
1721
1722 return INT2FIX(0);
1723}
1724#else
1725#define dir_s_chroot rb_f_notimplement
1726#endif
1727
1728struct mkdir_arg {
1729 const char *path;
1730 mode_t mode;
1731};
1732
1733static void *
1734nogvl_mkdir(void *ptr)
1735{
1736 struct mkdir_arg *m = ptr;
1737
1738 return (void *)(VALUE)mkdir(m->path, m->mode);
1739}
1740
1741/*
1742 * call-seq:
1743 * Dir.mkdir(dirpath, permissions = 0775) -> 0
1744 *
1745 * Creates a directory in the underlying file system
1746 * at +dirpath+ with the given +permissions+;
1747 * returns zero:
1748 *
1749 * Dir.mkdir('foo')
1750 * File.stat(Dir.new('foo')).mode.to_s(8)[1..4] # => "0755"
1751 * Dir.mkdir('bar', 0644)
1752 * File.stat(Dir.new('bar')).mode.to_s(8)[1..4] # => "0644"
1753 *
1754 * See {File Permissions}[rdoc-ref:File@File+Permissions].
1755 * Note that argument +permissions+ is ignored on Windows.
1756 */
1757static VALUE
1758dir_s_mkdir(int argc, VALUE *argv, VALUE obj)
1759{
1760 struct mkdir_arg m;
1761 VALUE path, vmode;
1762 int r;
1763
1764 if (rb_scan_args(argc, argv, "11", &path, &vmode) == 2) {
1765 m.mode = NUM2MODET(vmode);
1766 }
1767 else {
1768 m.mode = 0777;
1769 }
1770
1771 path = check_dirname(path);
1772 m.path = RSTRING_PTR(path);
1773 r = IO_WITHOUT_GVL_INT(nogvl_mkdir, &m);
1774 if (r < 0)
1775 rb_sys_fail_path(path);
1776
1777 return INT2FIX(0);
1778}
1779
1780static void *
1781nogvl_rmdir(void *ptr)
1782{
1783 const char *path = ptr;
1784
1785 return (void *)(VALUE)rmdir(path);
1786}
1787
1788/*
1789 * call-seq:
1790 * Dir.rmdir(dirpath) -> 0
1791 *
1792 * Removes the directory at +dirpath+ from the underlying file system:
1793 *
1794 * Dir.rmdir('foo') # => 0
1795 *
1796 * Raises an exception if the directory is not empty.
1797 */
1798static VALUE
1799dir_s_rmdir(VALUE obj, VALUE dir)
1800{
1801 const char *p;
1802 int r;
1803
1804 dir = check_dirname(dir);
1805 p = RSTRING_PTR(dir);
1806 r = IO_WITHOUT_GVL_INT(nogvl_rmdir, (void *)p);
1807 if (r < 0)
1808 rb_sys_fail_path(dir);
1809
1810 return INT2FIX(0);
1812
1813struct warning_args {
1814#ifdef RUBY_FUNCTION_NAME_STRING
1815 const char *func;
1816#endif
1817 const char *mesg;
1818 rb_encoding *enc;
1819};
1820
1821#ifndef RUBY_FUNCTION_NAME_STRING
1822#define sys_enc_warning_in(func, mesg, enc) sys_enc_warning(mesg, enc)
1823#endif
1824
1825static VALUE
1826sys_warning_1(VALUE mesg)
1827{
1828 const struct warning_args *arg = (struct warning_args *)mesg;
1829#ifdef RUBY_FUNCTION_NAME_STRING
1830 rb_sys_enc_warning(arg->enc, "%s: %s", arg->func, arg->mesg);
1831#else
1832 rb_sys_enc_warning(arg->enc, "%s", arg->mesg);
1833#endif
1834 return Qnil;
1835}
1836
1837static void
1838sys_enc_warning_in(const char *func, const char *mesg, rb_encoding *enc)
1839{
1840 struct warning_args arg;
1841#ifdef RUBY_FUNCTION_NAME_STRING
1842 arg.func = func;
1843#endif
1844 arg.mesg = mesg;
1845 arg.enc = enc;
1846 rb_protect(sys_warning_1, (VALUE)&arg, 0);
1847}
1848
1849#define GLOB_VERBOSE (1U << (sizeof(int) * CHAR_BIT - 1))
1850#define sys_warning(val, enc) \
1851 ((flags & GLOB_VERBOSE) ? sys_enc_warning_in(RUBY_FUNCTION_NAME_STRING, (val), (enc)) :(void)0)
1852
1853static inline size_t
1854glob_alloc_size(size_t x, size_t y)
1855{
1856 size_t z;
1857 if (rb_mul_size_overflow(x, y, SSIZE_MAX, &z)) {
1858 rb_memerror(); /* or...? */
1859 }
1860 else {
1861 return z;
1862 }
1863}
1864
1865static inline void *
1866glob_alloc_n(size_t x, size_t y)
1867{
1868 return malloc(glob_alloc_size(x, y));
1869}
1870
1871static inline void *
1872glob_realloc_n(void *p, size_t x, size_t y)
1873{
1874 return realloc(p, glob_alloc_size(x, y));
1875}
1876
1877#define GLOB_ALLOC(type) ((type *)malloc(sizeof(type)))
1878#define GLOB_ALLOC_N(type, n) ((type *)glob_alloc_n(sizeof(type), n))
1879#define GLOB_REALLOC(ptr, size) realloc((ptr), (size))
1880#define GLOB_REALLOC_N(ptr, n) glob_realloc_n(ptr, sizeof(*(ptr)), n)
1881#define GLOB_FREE(ptr) free(ptr)
1882#define GLOB_JUMP_TAG(status) (((status) == -1) ? rb_memerror() : rb_jump_tag(status))
1883
1884/*
1885 * ENOTDIR can be returned by stat(2) if a non-leaf element of the path
1886 * is not a directory.
1887 */
1888ALWAYS_INLINE(static int to_be_ignored(int e));
1889static inline int
1890to_be_ignored(int e)
1891{
1892 return e == ENOENT || e == ENOTDIR;
1893}
1894
1895#ifdef _WIN32
1896#define STAT(args) (int)(VALUE)nogvl_stat(&(args))
1897#define LSTAT(args) (int)(VALUE)nogvl_lstat(&(args))
1898#else
1899#define STAT(args) IO_WITHOUT_GVL_INT(nogvl_stat, (void *)&(args))
1900#define LSTAT(args) IO_WITHOUT_GVL_INT(nogvl_lstat, (void *)&(args))
1901#endif
1903typedef int ruby_glob_errfunc(const char*, VALUE, const void*, int);
1904typedef struct {
1905 ruby_glob_func *match;
1906 ruby_glob_errfunc *error;
1908
1909static const char *
1910at_subpath(int fd, size_t baselen, const char *path)
1911{
1912#if USE_OPENDIR_AT
1913 if (fd != (int)AT_FDCWD && baselen > 0) {
1914 path += baselen;
1915 if (*path == '/') ++path;
1916 }
1917#endif
1918 return *path ? path : ".";
1919}
1920
1921#if USE_OPENDIR_AT
1922struct fstatat_args {
1923 int fd;
1924 int flag;
1925 const char *path;
1926 struct stat *pst;
1927};
1928
1929static void *
1930nogvl_fstatat(void *args)
1931{
1932 struct fstatat_args *arg = (struct fstatat_args *)args;
1933 return (void *)(VALUE)fstatat(arg->fd, arg->path, arg->pst, arg->flag);
1935#else
1936struct stat_args {
1937 const char *path;
1938 struct stat *pst;
1939};
1940
1941static void *
1942nogvl_stat(void *args)
1943{
1944 struct stat_args *arg = (struct stat_args *)args;
1945 return (void *)(VALUE)stat(arg->path, arg->pst);
1946}
1947#endif
1948
1949/* System call with warning */
1950static int
1951do_stat(int fd, const char *path, struct stat *pst, int flags, rb_encoding *enc)
1952{
1953#if USE_OPENDIR_AT
1954 struct fstatat_args args;
1955 args.fd = fd;
1956 args.path = path;
1957 args.pst = pst;
1958 args.flag = 0;
1959 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (void *)&args);
1960#else
1961 struct stat_args args;
1962 args.path = path;
1963 args.pst = pst;
1964 int ret = STAT(args);
1965#endif
1966 if (ret < 0 && !to_be_ignored(errno))
1967 sys_warning(path, enc);
1968
1969 return ret;
1970}
1971
1972#if defined HAVE_LSTAT || defined lstat || USE_OPENDIR_AT
1973#if !USE_OPENDIR_AT
1974static void *
1975nogvl_lstat(void *args)
1976{
1977 struct stat_args *arg = (struct stat_args *)args;
1978 return (void *)(VALUE)lstat(arg->path, arg->pst);
1979}
1980#endif
1981
1982static int
1983do_lstat(int fd, const char *path, struct stat *pst, int flags, rb_encoding *enc)
1984{
1985#if USE_OPENDIR_AT
1986 struct fstatat_args args;
1987 args.fd = fd;
1988 args.path = path;
1989 args.pst = pst;
1990 args.flag = AT_SYMLINK_NOFOLLOW;
1991 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (void *)&args);
1992#else
1993 struct stat_args args;
1994 args.path = path;
1995 args.pst = pst;
1996 int ret = LSTAT(args);
1997#endif
1998 if (ret < 0 && !to_be_ignored(errno))
1999 sys_warning(path, enc);
2000
2001 return ret;
2002}
2003#else
2004#define do_lstat do_stat
2005#endif
2006
2007struct opendir_at_arg {
2008 int basefd;
2009 const char *path;
2010};
2011
2012static void *
2013with_gvl_gc_for_fd(void *ptr)
2014{
2015 int *e = ptr;
2016
2017 return (void *)RBOOL(rb_gc_for_fd(*e));
2018}
2019
2020static int
2021gc_for_fd_with_gvl(int e)
2022{
2023 if (vm_initialized)
2024 return (int)(VALUE)rb_thread_call_with_gvl(with_gvl_gc_for_fd, &e);
2025 else
2026 return RBOOL(rb_gc_for_fd(e));
2027}
2028
2029static void *
2030nogvl_opendir_at(void *ptr)
2031{
2032 const struct opendir_at_arg *oaa = ptr;
2033 DIR *dirp;
2034
2035#if USE_OPENDIR_AT
2036 const int opendir_flags = (O_RDONLY|O_CLOEXEC|
2037# ifdef O_DIRECTORY
2038 O_DIRECTORY|
2039# endif /* O_DIRECTORY */
2040 0);
2041 int fd = openat(oaa->basefd, oaa->path, opendir_flags);
2042
2043 dirp = fd >= 0 ? fdopendir(fd) : 0;
2044 if (!dirp) {
2045 int e = errno;
2046
2047 switch (gc_for_fd_with_gvl(e)) {
2048 default:
2049 if (fd < 0) fd = openat(oaa->basefd, oaa->path, opendir_flags);
2050 if (fd >= 0) dirp = fdopendir(fd);
2051 if (dirp) return dirp;
2052
2053 e = errno;
2054 /* fallthrough*/
2055 case 0:
2056 if (fd >= 0) close(fd);
2057 rb_errno_set(e);
2058 }
2059 }
2060#else /* !USE_OPENDIR_AT */
2061 dirp = opendir(oaa->path);
2062 if (!dirp && gc_for_fd_with_gvl(errno))
2063 dirp = opendir(oaa->path);
2064#endif /* !USE_OPENDIR_AT */
2065
2066 return dirp;
2067}
2068
2069static DIR *
2070opendir_at(int basefd, const char *path)
2071{
2072 struct opendir_at_arg oaa;
2073
2074 oaa.basefd = basefd;
2075 oaa.path = path;
2076
2077 if (vm_initialized)
2078 return IO_WITHOUT_GVL(nogvl_opendir_at, &oaa);
2079 else
2080 return nogvl_opendir_at(&oaa);
2081}
2082
2083static DIR *
2084do_opendir(const int basefd, size_t baselen, const char *path, int flags, rb_encoding *enc,
2085 ruby_glob_errfunc *errfunc, VALUE arg, int *status)
2086{
2087 DIR *dirp;
2088#ifdef _WIN32
2089 VALUE tmp = 0;
2090 if (!fundamental_encoding_p(enc)) {
2091 tmp = rb_enc_str_new(path, strlen(path), enc);
2092 tmp = rb_str_encode_ospath(tmp);
2093 path = RSTRING_PTR(tmp);
2094 }
2095#endif
2096 dirp = opendir_at(basefd, at_subpath(basefd, baselen, path));
2097 if (!dirp) {
2098 int e = errno;
2099
2100 *status = 0;
2101 if (!to_be_ignored(e)) {
2102 if (errfunc) {
2103 *status = (*errfunc)(path, arg, enc, e);
2104 }
2105 else {
2106 sys_warning(path, enc);
2107 }
2108 }
2109 }
2110#ifdef _WIN32
2111 if (tmp) rb_str_resize(tmp, 0); /* GC guard */
2112#endif
2113
2114 return dirp;
2115}
2116
2117/* Globing pattern */
2118enum glob_pattern_type { PLAIN, ALPHA, BRACE, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR };
2119
2120/* Return nonzero if S has any special globbing chars in it. */
2121static enum glob_pattern_type
2122has_magic(const char *p, const char *pend, int flags, rb_encoding *enc)
2123{
2124 const int escape = !(flags & FNM_NOESCAPE);
2125 int hasalpha = 0;
2126 int hasmagical = 0;
2127
2128 register char c;
2129
2130 while (p < pend && (c = *p++) != 0) {
2131 switch (c) {
2132 case '{':
2133 return BRACE;
2134
2135 case '*':
2136 case '?':
2137 case '[':
2138 hasmagical = 1;
2139 break;
2140
2141 case '\\':
2142 if (escape && p++ >= pend)
2143 continue;
2144 break;
2145
2146#ifdef _WIN32
2147 case '.':
2148 break;
2149
2150 case '~':
2151 hasalpha = 1;
2152 break;
2153#endif
2154 default:
2155 if (IS_WIN32 || ISALPHA(c)) {
2156 hasalpha = 1;
2157 }
2158 break;
2159 }
2160
2161 p = Next(p-1, pend, enc);
2162 }
2163
2164 return hasmagical ? MAGICAL : hasalpha ? ALPHA : PLAIN;
2165}
2166
2167/* Find separator in globbing pattern. */
2168static char *
2169find_dirsep(const char *p, const char *pend, int flags, rb_encoding *enc)
2170{
2171 const int escape = !(flags & FNM_NOESCAPE);
2172
2173 register char c;
2174 int open = 0;
2175
2176 while ((c = *p++) != 0) {
2177 switch (c) {
2178 case '[':
2179 open = 1;
2180 continue;
2181 case ']':
2182 open = 0;
2183 continue;
2184
2185 case '{':
2186 open = 1;
2187 continue;
2188 case '}':
2189 open = 0;
2190 continue;
2191
2192 case '/':
2193 if (!open)
2194 return (char *)p-1;
2195 continue;
2196
2197 case '\\':
2198 if (escape && !(c = *p++))
2199 return (char *)p-1;
2200 continue;
2201 }
2202
2203 p = Next(p-1, pend, enc);
2204 }
2205
2206 return (char *)p-1;
2207}
2208
2209/* Remove escaping backslashes */
2210static char *
2211remove_backslashes(char *p, register const char *pend, rb_encoding *enc)
2212{
2213 char *t = p;
2214 char *s = p;
2215
2216 while (*p) {
2217 if (*p == '\\') {
2218 if (t != s)
2219 memmove(t, s, p - s);
2220 t += p - s;
2221 s = ++p;
2222 if (!*p) break;
2223 }
2224 Inc(p, pend, enc);
2225 }
2226
2227 while (*p++);
2228
2229 if (t != s)
2230 memmove(t, s, p - s); /* move '\0' too */
2231
2232 return p;
2234
2235struct glob_pattern {
2236 char *str;
2237 enum glob_pattern_type type;
2238 struct glob_pattern *next;
2239};
2240
2241static void glob_free_pattern(struct glob_pattern *list);
2242
2243static struct glob_pattern *
2244glob_make_pattern(const char *p, const char *e, int flags, rb_encoding *enc)
2245{
2246 struct glob_pattern *list, *tmp, **tail = &list;
2247 int dirsep = 0; /* pattern is terminated with '/' */
2248 int recursive = 0;
2249
2250 while (p < e && *p) {
2251 tmp = GLOB_ALLOC(struct glob_pattern);
2252 if (!tmp) goto error;
2253 if (p + 2 < e && p[0] == '*' && p[1] == '*' && p[2] == '/') {
2254 /* fold continuous RECURSIVEs (needed in glob_helper) */
2255 do { p += 3; while (*p == '/') p++; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
2256 tmp->type = RECURSIVE;
2257 tmp->str = 0;
2258 dirsep = 1;
2259 recursive = 1;
2260 }
2261 else {
2262 const char *m = find_dirsep(p, e, flags, enc);
2263 const enum glob_pattern_type magic = has_magic(p, m, flags, enc);
2264 const enum glob_pattern_type non_magic = (USE_NAME_ON_FS || FNM_SYSCASE) ? PLAIN : ALPHA;
2265 char *buf;
2266
2267 if (!(FNM_SYSCASE || magic > non_magic) && !recursive && *m) {
2268 const char *m2;
2269 while (has_magic(m+1, m2 = find_dirsep(m+1, e, flags, enc), flags, enc) <= non_magic &&
2270 *m2) {
2271 m = m2;
2272 }
2273 }
2274 buf = GLOB_ALLOC_N(char, m-p+1);
2275 if (!buf) {
2276 GLOB_FREE(tmp);
2277 goto error;
2278 }
2279 memcpy(buf, p, m-p);
2280 buf[m-p] = '\0';
2281 tmp->type = magic > MAGICAL ? MAGICAL : magic > non_magic ? magic : PLAIN;
2282 tmp->str = buf;
2283 if (*m) {
2284 dirsep = 1;
2285 p = m + 1;
2286 }
2287 else {
2288 dirsep = 0;
2289 p = m;
2290 }
2291 }
2292 *tail = tmp;
2293 tail = &tmp->next;
2294 }
2295
2296 tmp = GLOB_ALLOC(struct glob_pattern);
2297 if (!tmp) {
2298 goto error;
2299 }
2300 tmp->type = dirsep ? MATCH_DIR : MATCH_ALL;
2301 tmp->str = 0;
2302 *tail = tmp;
2303 tmp->next = 0;
2304
2305 return list;
2306
2307 error:
2308 *tail = 0;
2309 glob_free_pattern(list);
2310 return 0;
2311}
2312
2313static void
2314glob_free_pattern(struct glob_pattern *list)
2315{
2316 while (list) {
2317 struct glob_pattern *tmp = list;
2318 list = list->next;
2319 if (tmp->str)
2320 GLOB_FREE(tmp->str);
2321 GLOB_FREE(tmp);
2322 }
2323}
2324
2325static char *
2326join_path(const char *path, size_t len, int dirsep, const char *name, size_t namlen)
2327{
2328 char *buf = GLOB_ALLOC_N(char, len+namlen+(dirsep?1:0)+1);
2329
2330 if (!buf) return 0;
2331 memcpy(buf, path, len);
2332 if (dirsep) {
2333 buf[len++] = '/';
2334 }
2335 memcpy(buf+len, name, namlen);
2336 buf[len+namlen] = '\0';
2337 return buf;
2338}
2339
2340#ifdef HAVE_GETATTRLIST
2341# if defined HAVE_FGETATTRLIST
2342# define is_case_sensitive(dirp, path) is_case_sensitive(dirp)
2343# else
2344# define is_case_sensitive(dirp, path) is_case_sensitive(path)
2345# endif
2346static int
2347is_case_sensitive(DIR *dirp, const char *path)
2348{
2349 struct {
2350 u_int32_t length;
2351 vol_capabilities_attr_t cap[1];
2352 } __attribute__((aligned(4), packed)) attrbuf[1];
2353 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, 0, ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES};
2354 const vol_capabilities_attr_t *const cap = attrbuf[0].cap;
2355 const int idx = VOL_CAPABILITIES_FORMAT;
2356 const uint32_t mask = VOL_CAP_FMT_CASE_SENSITIVE;
2357 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2358# if defined HAVE_FGETATTRLIST
2359 int ret = gvl_fgetattrlist(&args, dirfd(dirp));
2360# else
2361 int ret = gvl_getattrlist(&args, path);
2362# endif
2363 if (ret)
2364 return -1;
2365
2366 if (!(cap->valid[idx] & mask))
2367 return -1;
2368 return (cap->capabilities[idx] & mask) != 0;
2369}
2370
2371static char *
2372replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int flags, rb_pathtype_t *type)
2373{
2374 struct {
2375 u_int32_t length;
2376 attrreference_t ref[1];
2377 fsobj_type_t objtype;
2378 char path[MAXPATHLEN * 3];
2379 } __attribute__((aligned(4), packed)) attrbuf[1];
2380 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_NAME|ATTR_CMN_OBJTYPE};
2381 const attrreference_t *const ar = attrbuf[0].ref;
2382 const char *name;
2383 long len;
2384 char *tmp;
2385 IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil);
2386
2387 *type = path_noent;
2388 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2389 if (gvl_getattrlist(&args, path)) {
2390 if (!to_be_ignored(errno))
2391 sys_warning(path, enc);
2392 return path;
2393 }
2394
2395 switch (attrbuf[0].objtype) {
2396 case VREG: *type = path_regular; break;
2397 case VDIR: *type = path_directory; break;
2398 case VLNK: *type = path_symlink; break;
2399 default: *type = path_exist; break;
2400 }
2401 name = (char *)ar + ar->attr_dataoffset;
2402 len = (long)ar->attr_length - 1;
2403 if (name + len > (char *)attrbuf + sizeof(attrbuf))
2404 return path;
2405
2406# if NORMALIZE_UTF8PATH
2407 if (norm_p && has_nonascii(name, len)) {
2408 if (!NIL_P(utf8str = rb_str_normalize_ospath(name, len))) {
2409 RSTRING_GETMEM(utf8str, name, len);
2410 }
2411 }
2412# endif
2413
2414 tmp = GLOB_REALLOC(path, base + len + 1);
2415 if (tmp) {
2416 path = tmp;
2417 memcpy(path + base, name, len);
2418 path[base + len] = '\0';
2419 }
2420 IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0));
2421 return path;
2422}
2423#elif defined _WIN32
2424VALUE rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc);
2425int rb_w32_reparse_symlink_p(const WCHAR *path);
2426
2427static char *
2428replace_real_basename(char *path, long base, rb_encoding *enc, int norm_p, int flags, rb_pathtype_t *type)
2429{
2430 char *plainname = path;
2431 volatile VALUE tmp = 0;
2432 WIN32_FIND_DATAW fd;
2433 WIN32_FILE_ATTRIBUTE_DATA fa;
2434 WCHAR *wplain;
2435 HANDLE h = INVALID_HANDLE_VALUE;
2436 long wlen;
2437 int e = 0;
2438 if (!fundamental_encoding_p(enc)) {
2439 tmp = rb_enc_str_new_cstr(plainname, enc);
2440 tmp = rb_str_encode_ospath(tmp);
2441 plainname = RSTRING_PTR(tmp);
2442 }
2443 wplain = rb_w32_mbstr_to_wstr(CP_UTF8, plainname, -1, &wlen);
2444 if (tmp) rb_str_resize(tmp, 0);
2445 if (!wplain) return path;
2446 if (GetFileAttributesExW(wplain, GetFileExInfoStandard, &fa)) {
2447 h = FindFirstFileW(wplain, &fd);
2448 e = rb_w32_map_errno(GetLastError());
2449 }
2450 if (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2451 if (!rb_w32_reparse_symlink_p(wplain))
2452 fa.dwFileAttributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
2453 }
2454 free(wplain);
2455 if (h == INVALID_HANDLE_VALUE) {
2456 *type = path_noent;
2457 if (e && !to_be_ignored(e)) {
2458 errno = e;
2459 sys_warning(path, enc);
2460 }
2461 return path;
2462 }
2463 FindClose(h);
2464 *type =
2465 (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? path_symlink :
2466 (fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? path_directory :
2467 path_regular;
2468 if (tmp) {
2469 char *buf;
2470 tmp = rb_w32_conv_from_wchar(fd.cFileName, enc);
2471 wlen = RSTRING_LEN(tmp);
2472 buf = GLOB_REALLOC(path, base + wlen + 1);
2473 if (buf) {
2474 path = buf;
2475 memcpy(path + base, RSTRING_PTR(tmp), wlen);
2476 path[base + wlen] = 0;
2477 }
2478 rb_str_resize(tmp, 0);
2479 }
2480 else {
2481 char *utf8filename;
2482 wlen = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, NULL, 0, NULL, NULL);
2483 utf8filename = GLOB_REALLOC(0, wlen);
2484 if (utf8filename) {
2485 char *buf;
2486 WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, utf8filename, wlen, NULL, NULL);
2487 buf = GLOB_REALLOC(path, base + wlen + 1);
2488 if (buf) {
2489 path = buf;
2490 memcpy(path + base, utf8filename, wlen);
2491 path[base + wlen] = 0;
2492 }
2493 GLOB_FREE(utf8filename);
2494 }
2495 }
2496 return path;
2497}
2498#elif USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2499# error not implemented
2500#endif
2501
2502#ifndef S_ISDIR
2503# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
2504#endif
2505
2506#ifndef S_ISLNK
2507# ifndef S_IFLNK
2508# define S_ISLNK(m) (0)
2509# else
2510# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
2511# endif
2512#endif
2513
2514struct glob_args {
2515 void (*func)(const char *, VALUE, void *);
2516 const char *path;
2517 const char *base;
2518 size_t baselen;
2519 VALUE value;
2520 rb_encoding *enc;
2521};
2522
2523#define glob_call_func(func, path, arg, enc) (*(func))((path), (arg), (void *)(enc))
2524
2525static VALUE
2526glob_func_caller(VALUE val)
2527{
2528 struct glob_args *args = (struct glob_args *)val;
2529
2530 glob_call_func(args->func, args->path, args->value, args->enc);
2531 return Qnil;
2533
2534struct glob_error_args {
2535 const char *path;
2536 rb_encoding *enc;
2537 int error;
2538};
2539
2540static VALUE
2541glob_func_warning(VALUE val)
2542{
2543 struct glob_error_args *arg = (struct glob_error_args *)val;
2544 rb_syserr_enc_warning(arg->error, arg->enc, "%s", arg->path);
2545 return Qnil;
2546}
2547
2548#if 0
2549static int
2550rb_glob_warning(const char *path, VALUE a, const void *enc, int error)
2551{
2552 int status;
2553 struct glob_error_args args;
2554
2555 args.path = path;
2556 args.enc = enc;
2557 args.error = error;
2558 rb_protect(glob_func_warning, (VALUE)&args, &status);
2559 return status;
2560}
2561#endif
2562
2563NORETURN(static VALUE glob_func_error(VALUE val));
2564
2565static VALUE
2566glob_func_error(VALUE val)
2567{
2568 struct glob_error_args *arg = (struct glob_error_args *)val;
2569 VALUE path = rb_enc_str_new_cstr(arg->path, arg->enc);
2570 rb_syserr_fail_str(arg->error, path);
2572}
2573
2574static int
2575rb_glob_error(const char *path, VALUE a, const void *enc, int error)
2576{
2577 int status;
2578 struct glob_error_args args;
2579 VALUE (*errfunc)(VALUE) = glob_func_error;
2580
2581 switch (error) {
2582 case EACCES:
2583#ifdef ENOTCAPABLE
2584 case ENOTCAPABLE:
2585#endif
2586 errfunc = glob_func_warning;
2587 }
2588 args.path = path;
2589 args.enc = enc;
2590 args.error = error;
2591 rb_protect(errfunc, (VALUE)&args, &status);
2592 return status;
2594
2595typedef struct rb_dirent {
2596 long d_namlen;
2597 const char *d_name;
2598#ifdef _WIN32
2599 const char *d_altname;
2600#endif
2601 uint8_t d_type;
2602} rb_dirent_t;
2603
2604static inline int
2605dirent_match(const char *pat, rb_encoding *enc, const char *name, const rb_dirent_t *dp, int flags)
2606{
2607 if (fnmatch(pat, enc, name, flags) == 0) return 1;
2608#ifdef _WIN32
2609 if (dp->d_altname && (flags & FNM_SHORTNAME)) {
2610 if (fnmatch(pat, enc, dp->d_altname, flags) == 0) return 1;
2611 }
2612#endif
2613 return 0;
2615
2616struct push_glob_args {
2617 int fd;
2618 const char *path;
2619 size_t baselen;
2620 size_t namelen;
2621 int dirsep; /* '/' should be placed before appending child entry's name to 'path'. */
2622 rb_pathtype_t pathtype; /* type of 'path' */
2623 int flags;
2624 const ruby_glob_funcs_t *funcs;
2625 VALUE arg;
2627
2628struct dirent_brace_args {
2629 const char *name;
2630 const rb_dirent_t *dp;
2631 int flags;
2632};
2633
2634static int
2635dirent_match_brace(const char *pattern, VALUE val, void *enc)
2636{
2637 struct dirent_brace_args *arg = (struct dirent_brace_args *)val;
2638
2639 return dirent_match(pattern, enc, arg->name, arg->dp, arg->flags);
2640}
2641
2642/* join paths from pattern list of glob_make_pattern() */
2643static char*
2644join_path_from_pattern(struct glob_pattern **beg)
2645{
2646 struct glob_pattern *p;
2647 char *path = NULL;
2648 size_t path_len = 0;
2649
2650 for (p = *beg; p; p = p->next) {
2651 const char *str;
2652 switch (p->type) {
2653 case RECURSIVE:
2654 str = "**";
2655 break;
2656 case MATCH_DIR:
2657 /* append last slash */
2658 str = "";
2659 break;
2660 default:
2661 str = p->str;
2662 if (!str) continue;
2663 }
2664 if (!path) {
2665 path_len = strlen(str);
2666 path = GLOB_ALLOC_N(char, path_len + 1);
2667 if (path) {
2668 memcpy(path, str, path_len);
2669 path[path_len] = '\0';
2670 }
2671 }
2672 else {
2673 size_t len = strlen(str);
2674 char *tmp;
2675 tmp = GLOB_REALLOC(path, path_len + len + 2);
2676 if (tmp) {
2677 path = tmp;
2678 path[path_len++] = '/';
2679 memcpy(path + path_len, str, len);
2680 path_len += len;
2681 path[path_len] = '\0';
2682 }
2683 }
2684 }
2685 return path;
2686}
2687
2688static int push_caller(const char *path, VALUE val, void *enc);
2689
2690static int ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg,
2691 rb_encoding *enc, VALUE var);
2692
2693static const size_t rb_dirent_name_offset =
2694 offsetof(rb_dirent_t, d_type) + sizeof(uint8_t);
2695
2696static rb_dirent_t *
2697dirent_copy(const struct dirent *dp, rb_dirent_t *rdp)
2698{
2699 if (!dp) return NULL;
2700 size_t namlen = NAMLEN(dp);
2701 const size_t altlen =
2702#ifdef _WIN32
2703 dp->d_altlen ? dp->d_altlen + 1 :
2704#endif
2705 0;
2706 rb_dirent_t *newrdp = rdp;
2707 if (!rdp && !(newrdp = malloc(rb_dirent_name_offset + namlen + 1 + altlen)))
2708 return NULL;
2709 newrdp->d_namlen = namlen;
2710 if (!rdp) {
2711 char *name = (char *)newrdp + rb_dirent_name_offset;
2712 memcpy(name, dp->d_name, namlen);
2713 name[namlen] = '\0';
2714#ifdef _WIN32
2715 newrdp->d_altname = NULL;
2716 if (altlen) {
2717 char *const altname = name + namlen + 1;
2718 memcpy(altname, dp->d_altname, altlen - 1);
2719 altname[altlen - 1] = '\0';
2720 newrdp->d_altname = altname;
2721 }
2722#endif
2723 newrdp->d_name = name;
2724 }
2725 else {
2726 newrdp->d_name = dp->d_name;
2727#ifdef _WIN32
2728 newrdp->d_altname = dp->d_altname;
2729#endif
2730 }
2731#if !EMULATE_IFTODT
2732 newrdp->d_type = dp->d_type;
2733#else
2734 newrdp->d_type = 0;
2735#endif
2736 return newrdp;
2738
2739typedef union {
2740 struct {
2741 DIR *dirp;
2742 rb_dirent_t ent;
2743 } nosort;
2744 struct {
2745 size_t count, idx;
2746 rb_dirent_t **entries;
2747 } sort;
2749
2750static int
2751glob_sort_cmp(const void *a, const void *b, void *e)
2752{
2753 const rb_dirent_t *ent1 = *(void **)a;
2754 const rb_dirent_t *ent2 = *(void **)b;
2755 return strcmp(ent1->d_name, ent2->d_name);
2756}
2757
2758static void
2759glob_dir_finish(ruby_glob_entries_t *ent, int flags)
2760{
2761 if (flags & FNM_GLOB_NOSORT) {
2762 check_closedir(ent->nosort.dirp);
2763 ent->nosort.dirp = NULL;
2764 }
2765 else if (ent->sort.entries) {
2766 for (size_t i = 0, count = ent->sort.count; i < count;) {
2767 GLOB_FREE(ent->sort.entries[i++]);
2768 }
2769 GLOB_FREE(ent->sort.entries);
2770 ent->sort.entries = NULL;
2771 ent->sort.count = ent->sort.idx = 0;
2772 }
2773}
2774
2775static ruby_glob_entries_t *
2776glob_opendir(ruby_glob_entries_t *ent, DIR *dirp, int flags, rb_encoding *enc)
2777{
2779 if (flags & FNM_GLOB_NOSORT) {
2780 ent->nosort.dirp = dirp;
2781 return ent;
2782 }
2783 else {
2784 void *newp;
2785 struct dirent *dp;
2786 size_t count = 0, capacity = 0;
2787 ent->sort.count = 0;
2788 ent->sort.idx = 0;
2789 ent->sort.entries = 0;
2790#ifdef _WIN32
2791 if ((capacity = dirp->nfiles) > 0) {
2792 if (!(newp = GLOB_ALLOC_N(rb_dirent_t, capacity))) {
2793 check_closedir(dirp);
2794 return NULL;
2795 }
2796 ent->sort.entries = newp;
2797 }
2798#endif
2799 while ((dp = READDIR(dirp, enc)) != NULL) {
2800 rb_dirent_t *rdp = dirent_copy(dp, NULL);
2801 if (!rdp) {
2802 goto nomem;
2803 }
2804 if (count >= capacity) {
2805 capacity += 256;
2806 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, capacity))) {
2807 GLOB_FREE(rdp);
2808 goto nomem;
2809 }
2810 ent->sort.entries = newp;
2811 }
2812 ent->sort.entries[count++] = rdp;
2813 ent->sort.count = count;
2814 }
2815 check_closedir(dirp);
2816 if (count < capacity) {
2817 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, count))) {
2818 glob_dir_finish(ent, 0);
2819 return NULL;
2820 }
2821 ent->sort.entries = newp;
2822 }
2823 ruby_qsort(ent->sort.entries, ent->sort.count, sizeof(ent->sort.entries[0]),
2824 glob_sort_cmp, NULL);
2825 return ent;
2826 }
2827
2828 nomem:
2829 glob_dir_finish(ent, 0);
2830 check_closedir(dirp);
2831 return NULL;
2832}
2833
2834static rb_dirent_t *
2835glob_getent(ruby_glob_entries_t *ent, int flags, rb_encoding *enc)
2836{
2837 if (flags & FNM_GLOB_NOSORT) {
2838 return dirent_copy(READDIR(ent->nosort.dirp, enc), &ent->nosort.ent);
2839 }
2840 else if (ent->sort.idx < ent->sort.count) {
2841 return ent->sort.entries[ent->sort.idx++];
2842 }
2843 else {
2844 return NULL;
2845 }
2846}
2847
2848static int
2849glob_helper(
2850 int fd,
2851 const char *path,
2852 size_t baselen,
2853 size_t namelen,
2854 int dirsep, /* '/' should be placed before appending child entry's name to 'path'. */
2855 rb_pathtype_t pathtype, /* type of 'path' */
2856 struct glob_pattern **beg,
2857 struct glob_pattern **end,
2858 int flags,
2859 const ruby_glob_funcs_t *funcs,
2860 VALUE arg,
2861 rb_encoding *enc)
2862{
2863 struct stat st;
2864 int status = 0;
2865 struct glob_pattern **cur, **new_beg, **new_end;
2866 int plain = 0, brace = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0;
2867 int escape = !(flags & FNM_NOESCAPE);
2868 size_t pathlen = baselen + namelen;
2869
2870 rb_check_stack_overflow();
2871
2872 for (cur = beg; cur < end; ++cur) {
2873 struct glob_pattern *p = *cur;
2874 if (p->type == RECURSIVE) {
2875 recursive = 1;
2876 p = p->next;
2877 }
2878 switch (p->type) {
2879 case PLAIN:
2880 plain = 1;
2881 break;
2882 case ALPHA:
2883#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2884 plain = 1;
2885#else
2886 magical = 1;
2887#endif
2888 break;
2889 case BRACE:
2890 if (!recursive || strchr(p->str, '/')) {
2891 brace = 1;
2892 }
2893 break;
2894 case MAGICAL:
2895 magical = 2;
2896 break;
2897 case MATCH_ALL:
2898 match_all = 1;
2899 break;
2900 case MATCH_DIR:
2901 match_dir = 1;
2902 break;
2903 case RECURSIVE:
2904 rb_bug("continuous RECURSIVEs");
2905 }
2906 }
2907
2908 if (brace) {
2909 struct push_glob_args args;
2910 char* brace_path = join_path_from_pattern(beg);
2911 if (!brace_path) return -1;
2912 args.fd = fd;
2913 args.path = path;
2914 args.baselen = baselen;
2915 args.namelen = namelen;
2916 args.dirsep = dirsep;
2917 args.pathtype = pathtype;
2918 args.flags = flags;
2919 args.funcs = funcs;
2920 args.arg = arg;
2921 status = ruby_brace_expand(brace_path, flags, push_caller, (VALUE)&args, enc, Qfalse);
2922 GLOB_FREE(brace_path);
2923 return status;
2924 }
2925
2926 if (*path) {
2927 if (match_all && pathtype == path_unknown) {
2928 if (do_lstat(fd, path, &st, flags, enc) == 0) {
2929 pathtype = IFTODT(st.st_mode);
2930 }
2931 else {
2932 pathtype = path_noent;
2933 }
2934 }
2935 if (match_dir && (pathtype == path_unknown || pathtype == path_symlink)) {
2936 if (do_stat(fd, path, &st, flags, enc) == 0) {
2937 pathtype = IFTODT(st.st_mode);
2938 }
2939 else {
2940 pathtype = path_noent;
2941 }
2942 }
2943 if (match_all && pathtype > path_noent) {
2944 const char *subpath = path + baselen + (baselen && path[baselen] == '/');
2945 status = glob_call_func(funcs->match, subpath, arg, enc);
2946 if (status) return status;
2947 }
2948 if (match_dir && pathtype == path_directory) {
2949 int seplen = (baselen && path[baselen] == '/');
2950 const char *subpath = path + baselen + seplen;
2951 char *tmp = join_path(subpath, namelen - seplen, dirsep, "", 0);
2952 if (!tmp) return -1;
2953 status = glob_call_func(funcs->match, tmp, arg, enc);
2954 GLOB_FREE(tmp);
2955 if (status) return status;
2956 }
2957 }
2958
2959 if (pathtype == path_noent) return 0;
2960
2961 if (magical || recursive) {
2962 rb_dirent_t *dp;
2963 DIR *dirp;
2964# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2965 char *plainname = 0;
2966# endif
2967 IF_NORMALIZE_UTF8PATH(int norm_p);
2968# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2969 if (cur + 1 == end && (*cur)->type <= ALPHA) {
2970 plainname = join_path(path, pathlen, dirsep, (*cur)->str, strlen((*cur)->str));
2971 if (!plainname) return -1;
2972 dirp = do_opendir(fd, basename, plainname, flags, enc, funcs->error, arg, &status);
2973 GLOB_FREE(plainname);
2974 }
2975 else
2976# else
2977 ;
2978# endif
2979 dirp = do_opendir(fd, baselen, path, flags, enc, funcs->error, arg, &status);
2980 if (dirp == NULL) {
2981# if FNM_SYSCASE || NORMALIZE_UTF8PATH
2982 if ((magical < 2) && !recursive && (errno == EACCES)) {
2983 /* no read permission, fallback */
2984 goto literally;
2985 }
2986# endif
2987 return status;
2988 }
2989 IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp, *path ? path : "."));
2990
2991# if NORMALIZE_UTF8PATH
2992 if (!(norm_p || magical || recursive)) {
2993 check_closedir(dirp);
2994 goto literally;
2995 }
2996# endif
2997# ifdef HAVE_GETATTRLIST
2998 if (is_case_sensitive(dirp, path) == 0)
2999 flags |= FNM_CASEFOLD;
3000# endif
3001 ruby_glob_entries_t globent;
3002 if (!glob_opendir(&globent, dirp, flags, enc)) {
3003 status = 0;
3004 if (funcs->error) {
3005 status = (*funcs->error)(path, arg, enc, ENOMEM);
3006 }
3007 else {
3008 sys_warning(path, enc);
3009 }
3010 return status;
3011 }
3012
3013 int skipdot = (flags & FNM_GLOB_SKIPDOT);
3014 flags |= FNM_GLOB_SKIPDOT;
3015
3016 while ((dp = glob_getent(&globent, flags, enc)) != NULL) {
3017 char *buf;
3018 rb_pathtype_t new_pathtype = path_unknown;
3019 const char *name;
3020 size_t namlen;
3021 int dotfile = 0;
3022 IF_NORMALIZE_UTF8PATH(VALUE utf8str = Qnil);
3023
3024 name = dp->d_name;
3025 namlen = dp->d_namlen;
3026 if (name[0] == '.') {
3027 ++dotfile;
3028 if (namlen == 1) {
3029 /* unless DOTMATCH, skip current directories not to recurse infinitely */
3030 if (recursive && !(flags & FNM_DOTMATCH)) continue;
3031 if (skipdot) continue;
3032 ++dotfile;
3033 new_pathtype = path_directory; /* force to skip stat/lstat */
3034 }
3035 else if (namlen == 2 && name[1] == '.') {
3036 /* always skip parent directories not to recurse infinitely */
3037 continue;
3038 }
3039 }
3040
3041# if NORMALIZE_UTF8PATH
3042 if (norm_p && has_nonascii(name, namlen)) {
3043 if (!NIL_P(utf8str = rb_str_normalize_ospath(name, namlen))) {
3044 RSTRING_GETMEM(utf8str, name, namlen);
3045 }
3046 }
3047# endif
3048 buf = join_path(path, pathlen, dirsep, name, namlen);
3049 IF_NORMALIZE_UTF8PATH(if (!NIL_P(utf8str)) rb_str_resize(utf8str, 0));
3050 if (!buf) {
3051 status = -1;
3052 break;
3053 }
3054 name = buf + pathlen + (dirsep != 0);
3055#if !EMULATE_IFTODT
3056 if (dp->d_type != DT_UNKNOWN) {
3057 /* Got it. We need no more lstat. */
3058 new_pathtype = dp->d_type;
3059 }
3060#endif
3061 if (recursive && dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1) &&
3062 new_pathtype == path_unknown) {
3063 /* RECURSIVE never match dot files unless FNM_DOTMATCH is set */
3064 if (do_lstat(fd, buf, &st, flags, enc) == 0)
3065 new_pathtype = IFTODT(st.st_mode);
3066 else
3067 new_pathtype = path_noent;
3068 }
3069
3070 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, (end - beg) * 2);
3071 if (!new_beg) {
3072 GLOB_FREE(buf);
3073 status = -1;
3074 break;
3075 }
3076
3077 for (cur = beg; cur < end; ++cur) {
3078 struct glob_pattern *p = *cur;
3079 struct dirent_brace_args args;
3080 if (p->type == RECURSIVE) {
3081 if (new_pathtype == path_directory || /* not symlink but real directory */
3082 new_pathtype == path_exist) {
3083 if (dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1))
3084 *new_end++ = p; /* append recursive pattern */
3085 }
3086 p = p->next; /* 0 times recursion */
3087 }
3088 switch (p->type) {
3089 case BRACE:
3090 args.name = name;
3091 args.dp = dp;
3092 args.flags = flags;
3093 if (ruby_brace_expand(p->str, flags, dirent_match_brace,
3094 (VALUE)&args, enc, Qfalse) > 0)
3095 *new_end++ = p->next;
3096 break;
3097 case ALPHA:
3098# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
3099 if (plainname) {
3100 *new_end++ = p->next;
3101 break;
3102 }
3103# endif
3104 case PLAIN:
3105 case MAGICAL:
3106 if (dirent_match(p->str, enc, name, dp, flags))
3107 *new_end++ = p->next;
3108 default:
3109 break;
3110 }
3111 }
3112
3113 status = glob_helper(fd, buf, baselen, name - buf - baselen + namlen, 1,
3114 new_pathtype, new_beg, new_end,
3115 flags, funcs, arg, enc);
3116 GLOB_FREE(buf);
3117 GLOB_FREE(new_beg);
3118 if (status) break;
3119 }
3120
3121 glob_dir_finish(&globent, flags);
3122 }
3123 else if (plain) {
3124 struct glob_pattern **copy_beg, **copy_end, **cur2;
3125
3126# if FNM_SYSCASE || NORMALIZE_UTF8PATH
3127 literally:
3128# endif
3129 copy_beg = copy_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
3130 if (!copy_beg) return -1;
3131 for (cur = beg; cur < end; ++cur)
3132 *copy_end++ = (*cur)->type <= ALPHA ? *cur : 0;
3133
3134 for (cur = copy_beg; cur < copy_end; ++cur) {
3135 if (*cur) {
3136 rb_pathtype_t new_pathtype = path_unknown;
3137 char *buf;
3138 char *name;
3139 size_t len = strlen((*cur)->str) + 1;
3140 name = GLOB_ALLOC_N(char, len);
3141 if (!name) {
3142 status = -1;
3143 break;
3144 }
3145 memcpy(name, (*cur)->str, len);
3146 if (escape)
3147 len = remove_backslashes(name, name+len-1, enc) - name;
3148
3149 new_beg = new_end = GLOB_ALLOC_N(struct glob_pattern *, end - beg);
3150 if (!new_beg) {
3151 GLOB_FREE(name);
3152 status = -1;
3153 break;
3154 }
3155 *new_end++ = (*cur)->next;
3156 for (cur2 = cur + 1; cur2 < copy_end; ++cur2) {
3157 if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) {
3158 *new_end++ = (*cur2)->next;
3159 *cur2 = 0;
3160 }
3161 }
3162
3163 buf = join_path(path, pathlen, dirsep, name, len);
3164 GLOB_FREE(name);
3165 if (!buf) {
3166 GLOB_FREE(new_beg);
3167 status = -1;
3168 break;
3169 }
3170#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
3171 if ((*cur)->type == ALPHA) {
3172 buf = replace_real_basename(buf, pathlen + (dirsep != 0), enc,
3173 IF_NORMALIZE_UTF8PATH(1)+0,
3174 flags, &new_pathtype);
3175 if (!buf) break;
3176 }
3177#endif
3178 status = glob_helper(fd, buf, baselen,
3179 namelen + strlen(buf + pathlen), 1,
3180 new_pathtype, new_beg, new_end,
3181 flags, funcs, arg, enc);
3182 GLOB_FREE(buf);
3183 GLOB_FREE(new_beg);
3184 if (status) break;
3185 }
3186 }
3187
3188 GLOB_FREE(copy_beg);
3189 }
3190
3191 return status;
3192}
3193
3194static int
3195push_caller(const char *path, VALUE val, void *enc)
3196{
3197 struct push_glob_args *arg = (struct push_glob_args *)val;
3198 struct glob_pattern *list;
3199 int status;
3200
3201 list = glob_make_pattern(path, path + strlen(path), arg->flags, enc);
3202 if (!list) {
3203 return -1;
3204 }
3205 status = glob_helper(arg->fd, arg->path, arg->baselen, arg->namelen, arg->dirsep,
3206 arg->pathtype, &list, &list + 1, arg->flags, arg->funcs,
3207 arg->arg, enc);
3208 glob_free_pattern(list);
3209 return status;
3210}
3211
3212static int ruby_glob0(const char *path, int fd, const char *base, int flags,
3213 const ruby_glob_funcs_t *funcs, VALUE arg, rb_encoding *enc);
3214
3215struct push_glob0_args {
3216 int fd;
3217 const char *base;
3218 int flags;
3219 const ruby_glob_funcs_t *funcs;
3220 VALUE arg;
3221};
3222
3223static int
3224push_glob0_caller(const char *path, VALUE val, void *enc)
3225{
3226 struct push_glob0_args *arg = (struct push_glob0_args *)val;
3227 return ruby_glob0(path, arg->fd, arg->base, arg->flags, arg->funcs, arg->arg, enc);
3228}
3229
3230static int
3231ruby_glob0(const char *path, int fd, const char *base, int flags,
3232 const ruby_glob_funcs_t *funcs, VALUE arg,
3233 rb_encoding *enc)
3234{
3235 struct glob_pattern *list;
3236 const char *root, *start;
3237 char *buf;
3238 size_t n, baselen = 0;
3239 int status, dirsep = FALSE;
3240
3241 start = root = path;
3242
3243 if (*root == '{') {
3244 struct push_glob0_args args;
3245 args.fd = fd;
3246 args.base = base;
3247 args.flags = flags;
3248 args.funcs = funcs;
3249 args.arg = arg;
3250 return ruby_brace_expand(path, flags, push_glob0_caller, (VALUE)&args, enc, Qfalse);
3251 }
3252
3253 flags |= FNM_SYSCASE;
3254#if defined DOSISH
3255 root = rb_enc_path_skip_prefix(root, root + strlen(root), enc);
3256#endif
3257
3258 if (*root == '/') root++;
3259
3260 n = root - start;
3261 if (!n && base) {
3262 n = strlen(base);
3263 baselen = n;
3264 start = base;
3265 dirsep = TRUE;
3266 }
3267 buf = GLOB_ALLOC_N(char, n + 1);
3268 if (!buf) return -1;
3269 MEMCPY(buf, start, char, n);
3270 buf[n] = '\0';
3271
3272 list = glob_make_pattern(root, root + strlen(root), flags, enc);
3273 if (!list) {
3274 GLOB_FREE(buf);
3275 return -1;
3276 }
3277 status = glob_helper(fd, buf, baselen, n-baselen, dirsep,
3278 path_unknown, &list, &list + 1,
3279 flags, funcs, arg, enc);
3280 glob_free_pattern(list);
3281 GLOB_FREE(buf);
3282
3283 return status;
3284}
3286int
3287ruby_glob(const char *path, int flags, ruby_glob_func *func, VALUE arg)
3288{
3289 ruby_glob_funcs_t funcs;
3290 funcs.match = func;
3291 funcs.error = 0;
3292 return ruby_glob0(path, AT_FDCWD, 0, flags & ~GLOB_VERBOSE,
3293 &funcs, arg, rb_ascii8bit_encoding());
3294}
3295
3296static int
3297rb_glob_caller(const char *path, VALUE a, void *enc)
3298{
3299 int status;
3300 struct glob_args *args = (struct glob_args *)a;
3301
3302 args->path = path;
3303 rb_protect(glob_func_caller, a, &status);
3304 return status;
3305}
3306
3307static const ruby_glob_funcs_t rb_glob_funcs = {
3308 rb_glob_caller, rb_glob_error,
3309};
3310
3311void
3312rb_glob(const char *path, void (*func)(const char *, VALUE, void *), VALUE arg)
3313{
3314 struct glob_args args;
3315 int status;
3316
3317 args.func = func;
3318 args.value = arg;
3319 args.enc = rb_ascii8bit_encoding();
3320
3321 status = ruby_glob0(path, AT_FDCWD, 0, GLOB_VERBOSE, &rb_glob_funcs,
3322 (VALUE)&args, args.enc);
3323 if (status) GLOB_JUMP_TAG(status);
3324}
3325
3326static void
3327push_pattern(const char *path, VALUE ary, void *enc)
3328{
3329#if defined _WIN32 || defined __APPLE__
3330 VALUE name = rb_utf8_str_new_cstr(path);
3331 rb_encoding *eenc = rb_default_internal_encoding();
3332 name = rb_str_conv_enc(name, NULL, eenc ? eenc : enc);
3333#else
3334 VALUE name = rb_external_str_new_with_enc(path, strlen(path), enc);
3335#endif
3336 rb_ary_push(ary, name);
3337}
3338
3339static int
3340ruby_brace_expand(const char *str, int flags, ruby_glob_func *func, VALUE arg,
3341 rb_encoding *enc, VALUE var)
3342{
3343 const int escape = !(flags & FNM_NOESCAPE);
3344 const char *p = str;
3345 const char *pend = p + strlen(p);
3346 const char *s = p;
3347 const char *lbrace = 0, *rbrace = 0;
3348 int nest = 0, status = 0;
3349
3350 while (*p) {
3351 if (*p == '{' && nest++ == 0) {
3352 lbrace = p;
3353 }
3354 if (*p == '}' && lbrace && --nest == 0) {
3355 rbrace = p;
3356 break;
3357 }
3358 if (*p == '\\' && escape) {
3359 if (!*++p) break;
3360 }
3361 Inc(p, pend, enc);
3362 }
3363
3364 if (lbrace && rbrace) {
3365 size_t len = strlen(s) + 1;
3366 char *buf = GLOB_ALLOC_N(char, len);
3367 long shift;
3368
3369 if (!buf) return -1;
3370 memcpy(buf, s, lbrace-s);
3371 shift = (lbrace-s);
3372 p = lbrace;
3373 while (p < rbrace) {
3374 const char *t = ++p;
3375 nest = 0;
3376 while (p < rbrace && !(*p == ',' && nest == 0)) {
3377 if (*p == '{') nest++;
3378 if (*p == '}') nest--;
3379 if (*p == '\\' && escape) {
3380 if (++p == rbrace) break;
3381 }
3382 Inc(p, pend, enc);
3383 }
3384 memcpy(buf+shift, t, p-t);
3385 strlcpy(buf+shift+(p-t), rbrace+1, len-(shift+(p-t)));
3386 status = ruby_brace_expand(buf, flags, func, arg, enc, var);
3387 if (status) break;
3388 }
3389 GLOB_FREE(buf);
3390 }
3391 else if (!lbrace && !rbrace) {
3392 status = glob_call_func(func, s, arg, enc);
3393 }
3394
3395 RB_GC_GUARD(var);
3396 return status;
3398
3399struct brace_args {
3400 ruby_glob_funcs_t funcs;
3401 VALUE value;
3402 int flags;
3403};
3404
3405static int
3406glob_brace(const char *path, VALUE val, void *enc)
3407{
3408 struct brace_args *arg = (struct brace_args *)val;
3409
3410 return ruby_glob0(path, AT_FDCWD, 0, arg->flags, &arg->funcs, arg->value, enc);
3411}
3412
3413int
3414ruby_brace_glob_with_enc(const char *str, int flags, ruby_glob_func *func, VALUE arg, rb_encoding *enc)
3415{
3416 struct brace_args args;
3417
3418 flags &= ~GLOB_VERBOSE;
3419 args.funcs.match = func;
3420 args.funcs.error = 0;
3421 args.value = arg;
3422 args.flags = flags;
3423 return ruby_brace_expand(str, flags, glob_brace, (VALUE)&args, enc, Qfalse);
3424}
3426int
3427ruby_brace_glob(const char *str, int flags, ruby_glob_func *func, VALUE arg)
3428{
3429 return ruby_brace_glob_with_enc(str, flags, func, arg, rb_ascii8bit_encoding());
3430}
3431
3432static int
3433push_glob(VALUE ary, VALUE str, VALUE base, int flags)
3434{
3435 struct glob_args args;
3436 int fd;
3437 rb_encoding *enc = rb_enc_get(str);
3438
3439#if defined _WIN32 || defined __APPLE__
3440 str = rb_str_encode_ospath(str);
3441#endif
3442 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3443 enc = rb_filesystem_encoding();
3444 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3445 enc = rb_ascii8bit_encoding();
3446 flags |= GLOB_VERBOSE;
3447 args.func = push_pattern;
3448 args.value = ary;
3449 args.enc = enc;
3450 args.base = 0;
3451 fd = AT_FDCWD;
3452 if (!NIL_P(base)) {
3453 if (!RB_TYPE_P(base, T_STRING) || !rb_enc_check(str, base)) {
3454 struct dir_data *dirp = RTYPEDDATA_GET_DATA(base);
3455 if (!dirp->dir) dir_closed();
3456#ifdef HAVE_DIRFD
3457 if ((fd = dirfd(dirp->dir)) == -1)
3458 rb_sys_fail_path(dir_inspect(base));
3459#endif
3460 base = dirp->path;
3461 }
3462 args.base = RSTRING_PTR(base);
3463 }
3464#if defined _WIN32 || defined __APPLE__
3465 enc = rb_utf8_encoding();
3466#endif
3467
3468 return ruby_glob0(RSTRING_PTR(str), fd, args.base, flags, &rb_glob_funcs,
3469 (VALUE)&args, enc);
3470}
3471
3472static VALUE
3473rb_push_glob(VALUE str, VALUE base, int flags) /* '\0' is delimiter */
3474{
3475 VALUE ary;
3476 int status;
3477
3478 /* can contain null bytes as separators */
3479 if (!RB_TYPE_P(str, T_STRING)) {
3480 FilePathValue(str);
3481 }
3482 else if (!rb_str_to_cstr(str)) {
3483 rb_raise(rb_eArgError, "nul-separated glob pattern is deprecated");
3484 }
3485 else {
3486 rb_enc_check(str, rb_enc_from_encoding(rb_usascii_encoding()));
3487 }
3488 ary = rb_ary_new();
3489
3490 status = push_glob(ary, str, base, flags);
3491 if (status) GLOB_JUMP_TAG(status);
3492
3493 return ary;
3494}
3495
3496static VALUE
3497dir_globs(VALUE args, VALUE base, int flags)
3498{
3499 VALUE ary = rb_ary_new();
3500 long i;
3501
3502 for (i = 0; i < RARRAY_LEN(args); ++i) {
3503 int status;
3504 VALUE str = RARRAY_AREF(args, i);
3505 FilePathValue(str);
3506 status = push_glob(ary, str, base, flags);
3507 if (status) GLOB_JUMP_TAG(status);
3508 }
3509 RB_GC_GUARD(args);
3510
3511 return ary;
3512}
3513
3514static VALUE
3515dir_glob_option_base(VALUE base)
3516{
3517 if (NIL_OR_UNDEF_P(base)) {
3518 return Qnil;
3519 }
3520#if USE_OPENDIR_AT
3521 if (rb_typeddata_is_kind_of(base, &dir_data_type)) {
3522 return base;
3523 }
3524#endif
3525 FilePathValue(base);
3526 if (!RSTRING_LEN(base)) return Qnil;
3527 return base;
3528}
3529
3530static int
3531dir_glob_option_sort(VALUE sort)
3532{
3533 return (rb_bool_expected(sort, "sort", TRUE) ? 0 : FNM_GLOB_NOSORT);
3534}
3535
3536static VALUE
3537dir_s_aref(rb_execution_context_t *ec, VALUE obj, VALUE args, VALUE base, VALUE sort)
3538{
3539 const int flags = dir_glob_option_sort(sort);
3540 base = dir_glob_option_base(base);
3541 if (RARRAY_LEN(args) == 1) {
3542 return rb_push_glob(RARRAY_AREF(args, 0), base, flags);
3543 }
3544 return dir_globs(args, base, flags);
3545}
3546
3547static VALUE
3548dir_s_glob(rb_execution_context_t *ec, VALUE obj, VALUE str, VALUE rflags, VALUE base, VALUE sort)
3549{
3550 VALUE ary = rb_check_array_type(str);
3551 const int flags = (NUM2INT(rflags) | dir_glob_option_sort(sort)) & ~FNM_CASEFOLD;
3552 base = dir_glob_option_base(base);
3553 if (NIL_P(ary)) {
3554 ary = rb_push_glob(str, base, flags);
3555 }
3556 else {
3557 ary = dir_globs(ary, base, flags);
3558 }
3559
3560 if (rb_block_given_p()) {
3561 rb_ary_each(ary);
3562 return Qnil;
3563 }
3564 return ary;
3565}
3566
3567static VALUE
3568dir_open_dir(int argc, VALUE *argv)
3569{
3570 VALUE dir = rb_funcallv_kw(rb_cDir, rb_intern("open"), argc, argv, RB_PASS_CALLED_KEYWORDS);
3571
3572 rb_check_typeddata(dir, &dir_data_type);
3573 return dir;
3574}
3575
3576
3577/*
3578 * call-seq:
3579 * Dir.foreach(dirpath, encoding: 'UTF-8') {|entry_name| ... } -> nil
3580 *
3581 * Calls the block with each entry name in the directory at +dirpath+;
3582 * sets the given encoding onto each passed +entry_name+:
3583 *
3584 * Dir.foreach('/example') {|entry_name| p entry_name }
3585 *
3586 * Output:
3587 *
3588 * "config.h"
3589 * "lib"
3590 * "main.rb"
3591 * ".."
3592 * "."
3593 *
3594 * Encoding:
3595 *
3596 * Dir.foreach('/example') {|entry_name| p entry_name.encoding; break }
3597 * Dir.foreach('/example', encoding: 'US-ASCII') {|entry_name| p entry_name.encoding; break }
3598 *
3599 * Output:
3600 *
3601 * #<Encoding:UTF-8>
3602 * #<Encoding:US-ASCII>
3603 *
3604 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3605 *
3606 * Returns an enumerator if no block is given.
3607 */
3608static VALUE
3609dir_foreach(int argc, VALUE *argv, VALUE io)
3610{
3611 VALUE dir;
3612
3613 RETURN_ENUMERATOR(io, argc, argv);
3614 dir = dir_open_dir(argc, argv);
3615 rb_ensure(dir_each, dir, dir_close, dir);
3616 return Qnil;
3617}
3618
3619static VALUE
3620dir_entry_ary_push(VALUE ary, VALUE entry, struct dir_entry_args *_unused)
3621{
3622 return rb_ary_push(ary, entry);
3623}
3624
3625static VALUE
3626dir_collect(VALUE dir)
3627{
3628 VALUE ary = rb_ary_new();
3629 dir_each_entry(dir, dir_entry_ary_push, ary, FALSE);
3630 return ary;
3631}
3632
3633/*
3634 * call-seq:
3635 * Dir.entries(dirname, encoding: 'UTF-8') -> array
3636 *
3637 * Returns an array of the entry names in the directory at +dirpath+;
3638 * sets the given encoding onto each returned entry name:
3639 *
3640 * Dir.entries('/example') # => ["config.h", "lib", "main.rb", "..", "."]
3641 * Dir.entries('/example').first.encoding
3642 * # => #<Encoding:UTF-8>
3643 * Dir.entries('/example', encoding: 'US-ASCII').first.encoding
3644 * # => #<Encoding:US-ASCII>
3645 *
3646 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3647 *
3648 * Raises an exception if the directory does not exist.
3649 */
3650static VALUE
3651dir_entries(int argc, VALUE *argv, VALUE io)
3652{
3653 VALUE dir;
3654
3655 dir = dir_open_dir(argc, argv);
3656 return rb_ensure(dir_collect, dir, dir_close, dir);
3657}
3658
3659static VALUE
3660dir_each_child(VALUE dir)
3661{
3662 return dir_each_entry(dir, dir_yield, Qnil, TRUE);
3663}
3664
3665/*
3666 * call-seq:
3667 * Dir.each_child(dirpath) {|entry_name| ... } -> nil
3668 * Dir.each_child(dirpath, encoding: 'UTF-8') {|entry_name| ... } -> nil
3669 *
3670 * Like Dir.foreach, except that entries <tt>'.'</tt> and <tt>'..'</tt>
3671 * are not included.
3672 */
3673static VALUE
3674dir_s_each_child(int argc, VALUE *argv, VALUE io)
3675{
3676 VALUE dir;
3677
3678 RETURN_ENUMERATOR(io, argc, argv);
3679 dir = dir_open_dir(argc, argv);
3680 rb_ensure(dir_each_child, dir, dir_close, dir);
3681 return Qnil;
3682}
3683
3684/*
3685 * call-seq:
3686 * each_child {|entry_name| ... } -> self
3687 *
3688 * Calls the block with each entry name in +self+
3689 * except <tt>'.'</tt> and <tt>'..'</tt>:
3690 *
3691 * dir = Dir.new('/example')
3692 * dir.each_child {|entry_name| p entry_name }
3693 *
3694 * Output:
3695 *
3696 * "config.h"
3697 * "lib"
3698 * "main.rb"
3699 *
3700 * If no block is given, returns an enumerator.
3701 */
3702static VALUE
3703dir_each_child_m(VALUE dir)
3704{
3705 RETURN_ENUMERATOR(dir, 0, 0);
3706 return dir_each_entry(dir, dir_yield, Qnil, TRUE);
3707}
3708
3709/*
3710 * call-seq:
3711 * children -> array
3712 *
3713 * Returns an array of the entry names in +self+
3714 * except for <tt>'.'</tt> and <tt>'..'</tt>:
3715 *
3716 * dir = Dir.new('/example')
3717 * dir.children # => ["config.h", "lib", "main.rb"]
3718 *
3719 */
3720static VALUE
3721dir_collect_children(VALUE dir)
3722{
3723 VALUE ary = rb_ary_new();
3724 dir_each_entry(dir, dir_entry_ary_push, ary, TRUE);
3725 return ary;
3726}
3727
3728/*
3729 * call-seq:
3730 * children -> array
3731 *
3732 * Returns an array of the entry names in +self+ along with their type
3733 * except for <tt>'.'</tt> and <tt>'..'</tt>:
3734 *
3735 * dir = Dir.new('/example')
3736 * dir.scan # => [["config.h", :file], ["lib", :directory], ["main.rb", :file]]
3737 *
3738 */
3739static VALUE
3740dir_scan_children(VALUE dir)
3741{
3742 if (rb_block_given_p()) {
3743 dir_each_entry(dir, dir_yield_with_type, Qnil, TRUE);
3744 return Qnil;
3745 }
3746 else {
3747 VALUE ary = rb_ary_new();
3748 dir_each_entry(dir, dir_yield_with_type, ary, TRUE);
3749 return ary;
3750 }
3751}
3752
3753/*
3754 * call-seq:
3755 * Dir.children(dirpath) -> array
3756 * Dir.children(dirpath, encoding: 'UTF-8') -> array
3757 *
3758 * Returns an array of the entry names in the directory at +dirpath+
3759 * except for <tt>'.'</tt> and <tt>'..'</tt>;
3760 * sets the given encoding onto each returned entry name:
3761 *
3762 * Dir.children('/example') # => ["config.h", "lib", "main.rb"]
3763 * Dir.children('/example').first.encoding
3764 * # => #<Encoding:UTF-8>
3765 * Dir.children('/example', encoding: 'US-ASCII').first.encoding
3766 * # => #<Encoding:US-ASCII>
3767 *
3768 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3769 *
3770 * Raises an exception if the directory does not exist.
3771 */
3772static VALUE
3773dir_s_children(int argc, VALUE *argv, VALUE io)
3774{
3775 VALUE dir;
3776
3777 dir = dir_open_dir(argc, argv);
3778 return rb_ensure(dir_collect_children, dir, dir_close, dir);
3779}
3780
3781/*
3782 * call-seq:
3783 * Dir.scan(dirpath) {|entry_name, entry_type| ... } -> nil
3784 * Dir.scan(dirpath, encoding: 'UTF-8') {|entry_name, entry_type| ... } -> nil
3785 * Dir.scan(dirpath) -> [[entry_name, entry_type], ...]
3786 * Dir.scan(dirpath, encoding: 'UTF-8') -> [[entry_name, entry_type], ...]
3787 *
3788 * Yields or returns an array of the entry names in the directory at +dirpath+
3789 * associated with their type, except for <tt>'.'</tt> and <tt>'..'</tt>;
3790 * sets the given encoding onto each returned entry name.
3791 *
3792 * The type symbol is one of:
3793 * ``<code>:file</code>'', ``<code>:directory</code>'',
3794 * ``<code>:characterSpecial</code>'', ``<code>:blockSpecial</code>'',
3795 * ``<code>:fifo</code>'', ``<code>:link</code>'',
3796 * or ``<code>:socket</code>'':
3797 *
3798 * Dir.children('/example') # => [["config.h", :file], ["lib", :directory], ["main.rb", :file]]
3799 * Dir.children('/example').first.first.encoding
3800 * # => #<Encoding:UTF-8>
3801 * Dir.children('/example', encoding: 'US-ASCII').first.encoding
3802 * # => #<Encoding:US-ASCII>
3803 *
3804 * See {String Encoding}[rdoc-ref:encodings.rdoc@String+Encoding].
3805 *
3806 * Raises an exception if the directory does not exist.
3807 */
3808static VALUE
3809dir_s_scan(int argc, VALUE *argv, VALUE klass)
3810{
3811 VALUE dir = dir_open_dir(argc, argv);
3812 return rb_ensure(dir_scan_children, dir, dir_close, dir);
3813}
3814
3815static int
3816fnmatch_brace(const char *pattern, VALUE val, void *enc)
3817{
3818 struct brace_args *arg = (struct brace_args *)val;
3819 VALUE path = arg->value;
3820 rb_encoding *enc_pattern = enc;
3821 rb_encoding *enc_path = rb_enc_get(path);
3822
3823 if (enc_pattern != enc_path) {
3824 if (!rb_enc_asciicompat(enc_pattern))
3825 return FNM_NOMATCH;
3826 if (!rb_enc_asciicompat(enc_path))
3827 return FNM_NOMATCH;
3828 if (!rb_enc_str_asciionly_p(path)) {
3829 int cr = ENC_CODERANGE_7BIT;
3830 long len = strlen(pattern);
3831 if (rb_str_coderange_scan_restartable(pattern, pattern + len,
3832 enc_pattern, &cr) != len)
3833 return FNM_NOMATCH;
3834 if (cr != ENC_CODERANGE_7BIT)
3835 return FNM_NOMATCH;
3836 }
3837 }
3838 return (fnmatch(pattern, enc, RSTRING_PTR(path), arg->flags) == 0);
3839}
3840
3841/* :nodoc: */
3842static VALUE
3843file_s_fnmatch(int argc, VALUE *argv, VALUE obj)
3844{
3845 VALUE pattern, path;
3846 VALUE rflags;
3847 int flags;
3848
3849 if (rb_scan_args(argc, argv, "21", &pattern, &path, &rflags) == 3)
3850 flags = NUM2INT(rflags);
3851 else
3852 flags = 0;
3853
3854 StringValueCStr(pattern);
3855 FilePathStringValue(path);
3856
3857 if (flags & FNM_EXTGLOB) {
3858 struct brace_args args;
3859
3860 args.value = path;
3861 args.flags = flags;
3862 if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
3863 (VALUE)&args, rb_enc_get(pattern), pattern) > 0)
3864 return Qtrue;
3865 }
3866 else {
3867 rb_encoding *enc = rb_enc_compatible(pattern, path);
3868 if (!enc) return Qfalse;
3869 if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
3870 return Qtrue;
3871 }
3872 RB_GC_GUARD(pattern);
3873
3874 return Qfalse;
3875}
3876
3877/*
3878 * call-seq:
3879 * Dir.home(user_name = nil) -> dirpath
3880 *
3881 * Returns the home directory path of the user specified with +user_name+
3882 * if it is not +nil+, or the current login user:
3883 *
3884 * Dir.home # => "/home/me"
3885 * Dir.home('root') # => "/root"
3886 *
3887 * Raises ArgumentError if +user_name+ is not a user name.
3888 */
3889static VALUE
3890dir_s_home(int argc, VALUE *argv, VALUE obj)
3891{
3892 VALUE user;
3893 const char *u = 0;
3894
3895 rb_check_arity(argc, 0, 1);
3896 user = (argc > 0) ? argv[0] : Qnil;
3897 if (!NIL_P(user)) {
3898 StringValue(user);
3899 rb_must_asciicompat(user);
3900 u = StringValueCStr(user);
3901 if (*u) {
3902 return rb_home_dir_of(user, rb_str_new(0, 0));
3903 }
3904 }
3905 return rb_default_home_dir(rb_str_new(0, 0));
3906
3907}
3908
3909#if 0
3910/*
3911 * call-seq:
3912 * Dir.exist?(dirpath) -> true or false
3913 *
3914 * Returns whether +dirpath+ is a directory in the underlying file system:
3915 *
3916 * Dir.exist?('/example') # => true
3917 * Dir.exist?('/nosuch') # => false
3918 * Dir.exist?('/example/main.rb') # => false
3919 *
3920 * Same as File.directory?.
3921 *
3922 */
3923VALUE
3924rb_file_directory_p(void)
3925{
3926}
3927#endif
3928
3929static void *
3930nogvl_dir_empty_p(void *ptr)
3931{
3932 const char *path = ptr;
3933 DIR *dir = opendir(path);
3934 struct dirent *dp;
3935 VALUE result = Qtrue;
3936
3937 if (!dir) {
3938 int e = errno;
3939 switch (gc_for_fd_with_gvl(e)) {
3940 default:
3941 dir = opendir(path);
3942 if (dir) break;
3943 e = errno;
3944 /* fall through */
3945 case 0:
3946 if (e == ENOTDIR) return (void *)Qfalse;
3947 return (void *)INT2FIX(e);
3948 }
3949 }
3950 while ((dp = READDIR_NOGVL(dir, NULL)) != NULL) {
3951 if (!to_be_skipped(dp)) {
3952 result = Qfalse;
3953 break;
3954 }
3955 }
3956 check_closedir(dir);
3957 return (void *)result;
3958}
3959
3960/*
3961 * call-seq:
3962 * Dir.empty?(dirpath) -> true or false
3963 *
3964 * Returns whether +dirpath+ specifies an empty directory:
3965 *
3966 * dirpath = '/tmp/foo'
3967 * Dir.mkdir(dirpath)
3968 * Dir.empty?(dirpath) # => true
3969 * Dir.empty?('/example') # => false
3970 * Dir.empty?('/example/main.rb') # => false
3971 *
3972 * Raises an exception if +dirpath+ does not specify a directory or file
3973 * in the underlying file system.
3974 */
3975static VALUE
3976rb_dir_s_empty_p(VALUE obj, VALUE dirname)
3977{
3978 VALUE result, orig;
3979 const char *path;
3980 enum {false_on_notdir = 1};
3981
3982 FilePathValue(dirname);
3983 orig = rb_str_dup_frozen(dirname);
3984 dirname = rb_str_encode_ospath(dirname);
3985 dirname = rb_str_dup_frozen(dirname);
3986 path = RSTRING_PTR(dirname);
3987
3988#if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT
3989 {
3990 u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
3991 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
3992 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, 0);
3993 if (gvl_getattrlist(&args, path) != 0)
3994 rb_sys_fail_path(orig);
3995 if (*(const fsobj_tag_t *)(attrbuf+1) == VT_HFS) {
3996 al.commonattr = 0;
3997 al.dirattr = ATTR_DIR_ENTRYCOUNT;
3998 if (gvl_getattrlist(&args, path) == 0) {
3999 if (attrbuf[0] >= 2 * sizeof(u_int32_t))
4000 return RBOOL(attrbuf[1] == 0);
4001 if (false_on_notdir) return Qfalse;
4002 }
4003 rb_sys_fail_path(orig);
4004 }
4005 }
4006#endif
4007
4008 result = (VALUE)IO_WITHOUT_GVL(nogvl_dir_empty_p, (void *)path);
4009 if (FIXNUM_P(result)) {
4010 rb_syserr_fail_path((int)FIX2LONG(result), orig);
4011 }
4012 return result;
4013}
4014
4015void
4016Init_Dir(void)
4017{
4018 sym_directory = ID2SYM(rb_intern("directory"));
4019 sym_link = ID2SYM(rb_intern("link"));
4020 sym_file = ID2SYM(rb_intern("file"));
4021 sym_unknown = ID2SYM(rb_intern("unknown"));
4022
4023#if defined(DT_BLK) || defined(S_IFBLK)
4024 sym_block_device = ID2SYM(rb_intern("blockSpecial"));
4025#endif
4026#if defined(DT_CHR) || defined(S_IFCHR)
4027 sym_character_device = ID2SYM(rb_intern("characterSpecial"));
4028#endif
4029#if defined(DT_FIFO) || defined(S_IFIFO)
4030 sym_fifo = ID2SYM(rb_intern("fifo"));
4031#endif
4032#if defined(DT_SOCK) || defined(S_IFSOCK)
4033 sym_socket = ID2SYM(rb_intern("socket"));
4034#endif
4035
4036 rb_gc_register_address(&chdir_lock.path);
4037 rb_gc_register_address(&chdir_lock.thread);
4038 rb_gc_register_address(&last_cwd);
4039
4041
4043
4044 rb_define_alloc_func(rb_cDir, dir_s_alloc);
4045 rb_define_singleton_method(rb_cDir,"for_fd", dir_s_for_fd, 1);
4046 rb_define_singleton_method(rb_cDir, "foreach", dir_foreach, -1);
4047 rb_define_singleton_method(rb_cDir, "entries", dir_entries, -1);
4048 rb_define_singleton_method(rb_cDir, "each_child", dir_s_each_child, -1);
4049 rb_define_singleton_method(rb_cDir, "children", dir_s_children, -1);
4050 rb_define_singleton_method(rb_cDir, "scan", dir_s_scan, -1);
4051
4052 rb_define_method(rb_cDir,"fileno", dir_fileno, 0);
4053 rb_define_method(rb_cDir,"path", dir_path, 0);
4054 rb_define_method(rb_cDir,"to_path", dir_path, 0);
4055 rb_define_method(rb_cDir,"inspect", dir_inspect, 0);
4056 rb_define_method(rb_cDir,"read", dir_read, 0);
4057 rb_define_method(rb_cDir,"each", dir_each, 0);
4058 rb_define_method(rb_cDir,"each_child", dir_each_child_m, 0);
4059 rb_define_method(rb_cDir,"children", dir_collect_children, 0);
4060 rb_define_method(rb_cDir,"scan", dir_scan_children, 0);
4061 rb_define_method(rb_cDir,"rewind", dir_rewind, 0);
4062 rb_define_method(rb_cDir,"tell", dir_tell, 0);
4063 rb_define_method(rb_cDir,"seek", dir_seek, 1);
4064 rb_define_method(rb_cDir,"pos", dir_tell, 0);
4065 rb_define_method(rb_cDir,"pos=", dir_set_pos, 1);
4066 rb_define_method(rb_cDir,"close", dir_close, 0);
4067 rb_define_method(rb_cDir,"chdir", dir_chdir, 0);
4068
4069 rb_define_singleton_method(rb_cDir,"fchdir", dir_s_fchdir, 1);
4070 rb_define_singleton_method(rb_cDir,"chdir", dir_s_chdir, -1);
4071 rb_define_singleton_method(rb_cDir,"getwd", dir_s_getwd, 0);
4072 rb_define_singleton_method(rb_cDir,"pwd", dir_s_getwd, 0);
4073 rb_define_singleton_method(rb_cDir,"chroot", dir_s_chroot, 1);
4074 rb_define_singleton_method(rb_cDir,"mkdir", dir_s_mkdir, -1);
4075 rb_define_singleton_method(rb_cDir,"rmdir", dir_s_rmdir, 1);
4076 rb_define_singleton_method(rb_cDir,"delete", dir_s_rmdir, 1);
4077 rb_define_singleton_method(rb_cDir,"unlink", dir_s_rmdir, 1);
4078 rb_define_singleton_method(rb_cDir,"home", dir_s_home, -1);
4079
4080 rb_define_singleton_method(rb_cDir,"exist?", rb_file_directory_p, 1);
4081 rb_define_singleton_method(rb_cDir,"empty?", rb_dir_s_empty_p, 1);
4082
4083 rb_define_singleton_method(rb_cFile,"fnmatch", file_s_fnmatch, -1);
4084 rb_define_singleton_method(rb_cFile,"fnmatch?", file_s_fnmatch, -1);
4085
4086 /* {File::FNM_NOESCAPE}[rdoc-ref:File::Constants@File-3A-3AFNM_NOESCAPE] */
4087 rb_file_const("FNM_NOESCAPE", INT2FIX(FNM_NOESCAPE));
4088 /* {File::FNM_PATHNAME}[rdoc-ref:File::Constants@File-3A-3AFNM_PATHNAME] */
4089 rb_file_const("FNM_PATHNAME", INT2FIX(FNM_PATHNAME));
4090 /* {File::FNM_DOTMATCH}[rdoc-ref:File::Constants@File-3A-3AFNM_DOTMATCH] */
4091 rb_file_const("FNM_DOTMATCH", INT2FIX(FNM_DOTMATCH));
4092 /* {File::FNM_CASEFOLD}[rdoc-ref:File::Constants@File-3A-3AFNM_CASEFOLD] */
4093 rb_file_const("FNM_CASEFOLD", INT2FIX(FNM_CASEFOLD));
4094 /* {File::FNM_EXTGLOB}[rdoc-ref:File::Constants@File-3A-3AFNM_EXTGLOB] */
4095 rb_file_const("FNM_EXTGLOB", INT2FIX(FNM_EXTGLOB));
4096 /* {File::FNM_SYSCASE}[rdoc-ref:File::Constants@File-3A-3AFNM_SYSCASE] */
4097 rb_file_const("FNM_SYSCASE", INT2FIX(FNM_SYSCASE));
4098 /* {File::FNM_SHORTNAME}[rdoc-ref:File::Constants@File-3A-3AFNM_SHORTNAME] */
4099 rb_file_const("FNM_SHORTNAME", INT2FIX(FNM_SHORTNAME));
4100}
4101
4102#include "dir.rbinc"
#define RUBY_DEBUG
Define this macro when you want assertions.
Definition assert.h:88
#define RUBY_ATOMIC_VALUE_SET(var, val)
Identical to RUBY_ATOMIC_SET, except it expects its arguments are VALUE.
Definition atomic.h:378
#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:1603
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1396
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:3061
int rb_block_given_p(void)
Determines if the current method is given a block.
Definition eval.c:1018
#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:3967
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:3973
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1425
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:1413
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
Definition error.c:467
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:456
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:1344
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:1157
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:1350
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
Definition string.c:970
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:826
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:1088
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
VALUE rb_str_new_shared(VALUE str)
Identical to rb_str_new_cstr(), except it takes a Ruby's string instead of C's.
Definition string.c:1514
#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:3836
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:3189
#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:1996
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
Definition string.c:2792
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
Definition string.c:3314
#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:3194
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:2063
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:1399
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:1421
VALUE rb_yield(VALUE val)
Yields the block.
Definition vm_eval.c:1376
#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:122
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:769
#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:578
#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:229
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