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