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