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