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