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