14#include "ruby/internal/config.h"
26# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD) && \
27 defined(HAVE_OPENAT) && defined(HAVE_FSTATAT)
28# define USE_OPENDIR_AT 1
30# define USE_OPENDIR_AT 0
42#undef HAVE_DIRENT_NAMLEN
43#if defined HAVE_DIRENT_H && !defined _WIN32
45# define NAMLEN(dirent) strlen((dirent)->d_name)
46#elif defined HAVE_DIRECT_H && !defined _WIN32
48# define NAMLEN(dirent) strlen((dirent)->d_name)
51# define NAMLEN(dirent) (dirent)->d_namlen
52# define HAVE_DIRENT_NAMLEN 1
53# ifdef HAVE_SYS_NDIR_H
63# include "win32/dir.h"
72char *strchr(
char*,
char);
79#define USE_NAME_ON_FS_REAL_BASENAME 1
81#define USE_NAME_ON_FS_BY_FNMATCH 2
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))
89# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
91# define USE_NAME_ON_FS USE_NAME_ON_FS_BY_FNMATCH
93# define USE_NAME_ON_FS 0
97# define NORMALIZE_UTF8PATH 1
98# include <sys/param.h>
99# include <sys/mount.h>
100# include <sys/vnode.h>
102# define NORMALIZE_UTF8PATH 0
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"
128#define vm_initialized rb_cThread
133# define chdir(p) rb_w32_uchdir(p)
135# define mkdir(p, m) rb_w32_umkdir((p), (m))
137# define rmdir(p) rb_w32_urmdir(p)
139# define opendir(p) rb_w32_uopendir(p)
140# define ruby_getcwd() rb_w32_ugetcwd(NULL, 0)
146#ifdef HAVE_GETATTRLIST
147struct getattrlist_args {
150 struct attrlist *list;
153 unsigned int options;
156# define GETATTRLIST_ARGS(list_, buf_, options_) (struct getattrlist_args) \
157 {.list = list_, .buf = buf_, .size = sizeof(buf_), .options = options_}
160nogvl_getattrlist(
void *args)
162 struct getattrlist_args *arg = args;
163 return (
void *)(
VALUE)getattrlist(arg->path, arg->list, arg->buf, arg->size, arg->options);
167gvl_getattrlist(
struct getattrlist_args *args,
const char *path)
170 return IO_WITHOUT_GVL_INT(nogvl_getattrlist, args);
173# ifdef HAVE_FGETATTRLIST
175nogvl_fgetattrlist(
void *args)
177 struct getattrlist_args *arg = args;
178 return (
void *)(
VALUE)fgetattrlist(arg->fd, arg->list, arg->buf, arg->size, arg->options);
182gvl_fgetattrlist(
struct getattrlist_args *args,
int fd)
185 return IO_WITHOUT_GVL_INT(nogvl_fgetattrlist, args);
190#if NORMALIZE_UTF8PATH
191# if defined HAVE_FGETATTRLIST || !defined HAVE_GETATTRLIST
192# define need_normalization(dirp, path) need_normalization(dirp)
194# define need_normalization(dirp, path) need_normalization(path)
197need_normalization(
DIR *dirp,
const char *path)
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));
206 int ret = gvl_getattrlist(&args, path);
209 const fsobj_tag_t *tag = (
void *)(attrbuf+1);
221has_nonascii(
const char *ptr,
size_t len)
231# define IF_NORMALIZE_UTF8PATH(something) something
233# define IF_NORMALIZE_UTF8PATH(something)
236#if defined(IFTODT) && defined(DT_UNKNOWN)
237# define EMULATE_IFTODT 0
239# define EMULATE_IFTODT 1
243# define IFTODT(m) (((m) & S_IFMT) / ((~S_IFMT & (S_IFMT-1)) + 1))
248 path_exist = DT_UNKNOWN,
249 path_directory = DT_DIR,
250 path_regular = DT_REG,
251 path_symlink = DT_LNK,
254 path_directory = IFTODT(S_IFDIR),
255 path_regular = IFTODT(S_IFREG),
256 path_symlink = IFTODT(S_IFLNK),
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
273#define FNM_SHORTNAME 0x20
275#define FNM_SHORTNAME 0
277#define FNM_GLOB_NOSORT 0x40
278#define FNM_GLOB_SKIPDOT 0x80
283# define Next(p, e, enc) ((p)+ rb_enc_mbclen((p), (e), (enc)))
284# define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
295 const int nocase = flags & FNM_CASEFOLD;
296 const int escape = !(flags & FNM_NOESCAPE);
301 if (p >= pend)
return NULL;
302 if (*p ==
'!' || *p ==
'^') {
309 if (escape && *t1 ==
'\\')
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;
318 if (escape && *t2 ==
'\\')
322 p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc));
324 if ((r <= (send-s) && memcmp(t1, s, r) == 0) ||
325 (r2 <= (send-s) && memcmp(t2, s, r2) == 0)) {
330 if (nocase) c1 = rb_enc_toupper(c1, enc);
332 if (nocase) c2 = rb_enc_toupper(c2, enc);
333 if (c1 < c2)
continue;
335 if (nocase) c2 = rb_enc_toupper(c2, enc);
336 if (c1 > c2)
continue;
340 if (r <= (send-s) && memcmp(t1, s, r) == 0) {
344 if (!nocase)
continue;
347 if (c1 != c2)
continue;
352 return ok == not ? NULL : (
char *)p + 1;
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);
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;
376 const char *ptmp = 0;
377 const char *stmp = 0;
379 const char *p = *pcur;
380 const char *pend = p + strlen(p);
381 const char *s = *scur;
382 const char *send = s + strlen(s);
386 if (period && *s ==
'.' && *UNESCAPE(p) !=
'.')
392 do { p++; }
while (*p ==
'*');
393 if (ISEND(UNESCAPE(p))) {
414 if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) {
426 RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
429 r = rb_enc_precise_mbclen(p, pend, enc);
432 if (r <= (send-s) && memcmp(p, s, r) == 0) {
437 if (!nocase)
goto failed;
448 Inc(stmp, send, enc);
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;
469 const char *ptmp = 0;
470 const char *stmp = 0;
474 if (p[0] ==
'*' && p[1] ==
'*' && p[2] ==
'/') {
475 do { p += 3; }
while (p[0] ==
'*' && p[1] ==
'*' && p[2] ==
'/');
479 if (fnmatch_helper(&p, &s, flags, enc) == 0) {
480 while (*s && *s !=
'/') Inc(s, send, enc);
490 if (ptmp && stmp && !(period && *stmp ==
'.')) {
491 while (*stmp && *stmp !=
'/') Inc(stmp, send, enc);
503 return fnmatch_helper(&p, &s, flags, enc);
507static VALUE sym_directory, sym_link, sym_file, sym_unknown;
509#if defined(DT_BLK) || defined(S_IFBLK)
510static VALUE sym_block_device;
512#if defined(DT_CHR) || defined(S_IFCHR)
513static VALUE sym_character_device;
515#if defined(DT_FIFO) || defined(S_IFIFO)
516static VALUE sym_fifo;
518#if defined(DT_SOCK) || defined(S_IFSOCK)
519static VALUE sym_socket;
533 if (dir->dir) closedir(dir->dir);
536RUBY_REFERENCES(dir_refs) = {
537 RUBY_REF_EDGE(
struct dir_data, path),
544 RUBY_REFS_LIST_PTR(dir_refs),
554dir_s_alloc(
VALUE klass)
567nogvl_opendir(
void *ptr)
569 const char *path = ptr;
571 return opendir(path);
575opendir_without_gvl(
const char *path)
577 if (vm_initialized) {
578 union {
const void *in;
void *out; } u;
582 return IO_WITHOUT_GVL(nogvl_opendir, u.out);
585 return opendir(path);
592 if (closedir(dp->dir) < 0) {
594 rb_sys_fail(
"closedir");
601check_closedir(
DIR *dirp)
603 if (closedir(dirp) < 0)
604 rb_sys_fail(
"closedir");
613 rb_encoding *fsenc =
NIL_P(enc) ? rb_filesystem_encoding() : rb_to_encoding(enc);
617 dirname = rb_str_encode_ospath(dirname);
624 path = RSTRING_PTR(dirname);
625 dp->dir = opendir_without_gvl(path);
626 if (dp->dir == NULL) {
628 if (rb_gc_for_fd(e)) {
629 dp->dir = opendir_without_gvl(path);
631#ifdef HAVE_GETATTRLIST
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);
641 if (dp->dir == NULL) {
643 rb_syserr_fail_path(e, orig);
657 dir_initialize(ec, dir, dirname, enc);
665 return dir_close(dir);
668# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD)
670nogvl_fdopendir(
void *fd)
672 return fdopendir((
int)(
VALUE)fd);
701 if (!(dp->dir = IO_WITHOUT_GVL(nogvl_fdopendir, (
void *)(
VALUE)
NUM2INT(fd)))) {
702 rb_sys_fail(
"fdopendir");
710#define dir_s_for_fd rb_f_notimplement
713NORETURN(
static void dir_closed(
void));
724 rb_check_frozen(dir);
731 struct dir_data *dirp = dir_get(dir);
732 if (!dirp->dir) dir_closed();
736#define GetDIR(obj, dirp) ((dirp) = dir_check(obj))
749dir_inspect(
VALUE dir)
754 if (!
NIL_P(dirp->path)) {
762 return rb_funcallv(dir, idTo_s, 0, 0);
768#if defined(__sun) && !defined(HAVE_DIRFD)
769# if defined(HAVE_DIR_D_FD)
770# define dirfd(x) ((x)->d_fd)
772# elif defined(HAVE_DIR_DD_FD)
773# define dirfd(x) ((x)->dd_fd)
800 fd = dirfd(dirp->dir);
802 rb_sys_fail(
"dirfd");
806#define dir_fileno rb_f_notimplement
833 switch (rb_enc_to_index(enc)) {
834 case ENCINDEX_ASCII_8BIT:
835 case ENCINDEX_US_ASCII:
842# define READDIR(dir, enc) rb_w32_readdir((dir), (enc))
843# define READDIR_NOGVL READDIR
845NORETURN(
static void *sys_failure(
void *function));
847sys_failure(
void *function)
849 rb_sys_fail(function);
853nogvl_readdir(
void *dir)
856 if ((dir = readdir(dir)) == NULL) {
863# define READDIR(dir, enc) IO_WITHOUT_GVL(nogvl_readdir, (void *)(dir))
864# define READDIR_NOGVL(dir, enc) nogvl_readdir((dir))
869to_be_skipped(
const struct dirent *dp)
871 const char *name = dp->d_name;
872 if (name[0] !=
'.')
return FALSE;
873#ifdef HAVE_DIRENT_NAMLEN
874 switch (NAMLEN(dp)) {
876 if (name[1] !=
'.')
return FALSE;
883 if (!name[1])
return TRUE;
884 if (name[1] !=
'.')
return FALSE;
885 if (!name[2])
return TRUE;
912 if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
935static int do_lstat(
int fd,
const char *path,
struct stat *pst,
int flags,
rb_encoding *enc);
941 switch (dir_entry->dp->d_type) {
944 type = sym_block_device;
949 type = sym_character_device;
953 type = sym_directory;
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) {
982 type = sym_directory;
1002 type = sym_block_device;
1007 type = sym_character_device;
1048 return dir_each_entry(dir, dir_yield,
Qnil, FALSE);
1056 IF_NORMALIZE_UTF8PATH(
int norm_p);
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);
1066 if (children_only && name[0] ==
'.') {
1067 if (namlen == 1)
continue;
1068 if (namlen == 2 && name[1] ==
'.')
continue;
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);
1082 (*each)(arg, path, &each_args);
1108 if((pos = telldir(dirp->dir)) < 0)
1109 rb_sys_fail(
"telldir");
1110 return rb_int2inum(pos);
1113#define dir_tell rb_f_notimplement
1144 seekdir(dirp->dir, p);
1148#define dir_seek rb_f_notimplement
1179#define dir_set_pos rb_f_notimplement
1198dir_rewind(
VALUE dir)
1203 rewinddir(dirp->dir);
1226 dirp = dir_get(dir);
1227 if (!dirp->dir)
return Qnil;
1228 close_dir_data(dirp);
1234nogvl_chdir(
void *ptr)
1236 const char *path = ptr;
1238 return (
void *)(
VALUE)chdir(path);
1242dir_chdir0(
VALUE path)
1244 if (IO_WITHOUT_GVL_INT(nogvl_chdir, (
void*)RSTRING_PTR(path)) < 0)
1245 rb_sys_fail_path(path);
1254 .blocking = 0, .thread =
Qnil,
1255 .path =
Qnil, .line = 0,
1261 if (chdir_lock.blocking == 0) {
1262 chdir_lock.path = rb_source_location(&chdir_lock.line);
1264 chdir_lock.blocking++;
1265 if (
NIL_P(chdir_lock.thread)) {
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;
1282chdir_alone_block_p(
void)
1285 if (chdir_lock.blocking > 0) {
1287 rb_raise(
rb_eRuntimeError,
"conflicting chdir during another chdir block");
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);
1295 rb_warn(
"conflicting chdir during another chdir block");
1303 VALUE old_path, new_path;
1312 dir_chdir0(args->new_path);
1319chdir_restore(
VALUE v)
1324 dir_chdir0(args->old_path);
1330chdir_path(
VALUE path,
bool yield_path)
1332 if (chdir_alone_block_p()) {
1335 args.old_path = rb_str_encode_ospath(rb_dir_getwd());
1336 args.new_path = path;
1338 args.yield_path = yield_path;
1342 char *p = RSTRING_PTR(path);
1343 int r = IO_WITHOUT_GVL_INT(nogvl_chdir, p);
1345 rb_sys_fail_path(path);
1420 path = rb_str_encode_ospath(rb_get_path(argv[0]));
1423 const char *dist = getenv(
"HOME");
1425 dist = getenv(
"LOGDIR");
1426 if (!dist) rb_raise(rb_eArgError,
"HOME/LOGDIR not set");
1431 return chdir_path(path,
true);
1434#if defined(HAVE_FCHDIR) && defined(HAVE_DIRFD) && HAVE_FCHDIR && HAVE_DIRFD
1436nogvl_fchdir(
void *ptr)
1438 const int *fd = ptr;
1440 return (
void *)(
VALUE)fchdir(*fd);
1446 if (IO_WITHOUT_GVL_INT(nogvl_fchdir, (
void *)&fd) < 0)
1447 rb_sys_fail(
"fchdir");
1457fchdir_yield(
VALUE v)
1459 struct fchdir_data *args = (
void *)v;
1460 dir_fchdir(args->fd);
1467fchdir_restore(
VALUE v)
1469 struct fchdir_data *args = (
void *)v;
1472 dir_fchdir(
RB_NUM2INT(dir_fileno(args->old_dir)));
1474 dir_close(args->old_dir);
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);
1544 int r = IO_WITHOUT_GVL_INT(nogvl_fchdir, &fd);
1546 rb_sys_fail(
"fchdir");
1552#define dir_s_fchdir rb_f_notimplement
1581#if defined(HAVE_FCHDIR) && defined(HAVE_DIRFD) && HAVE_FCHDIR && HAVE_DIRFD
1582 return dir_s_fchdir(
rb_cDir, dir_fileno(dir));
1584 return chdir_path(dir_get(dir)->path,
false);
1588static VALUE last_cwd;
1592getcwd_to_str(
VALUE arg)
1594 const char *path = (
const char *)arg;
1596 return rb_str_normalize_ospath(path, strlen(path));
1603getcwd_xfree(
VALUE arg)
1610rb_dir_getwd_ospath_slowpath(
void)
1617rb_dir_getwd_ospath(
void)
1620 char *path = getcwd(buf, PATH_MAX);
1622 return rb_dir_getwd_ospath_slowpath();
1625 VALUE cached_cwd = RUBY_ATOMIC_VALUE_LOAD(last_cwd);
1627 if (!cached_cwd || strcmp(RSTRING_PTR(cached_cwd), path) != 0) {
1629 cached_cwd = rb_str_normalize_ospath(path, strlen(path));
1644 int fsenc = rb_enc_to_index(fs);
1648 case ENCINDEX_US_ASCII:
1649 fsenc = ENCINDEX_ASCII_8BIT;
1650 case ENCINDEX_ASCII_8BIT:
1652#if defined _WIN32 || defined __APPLE__
1657 return rb_enc_associate_index(cwd, fsenc);
1671dir_s_getwd(
VALUE dir)
1673 return rb_dir_getwd();
1677check_dirname(
VALUE dir)
1685 enc = rb_enc_get(d);
1688 pend = rb_enc_path_end(rb_enc_path_skip_prefix(path, pend, enc), pend, enc);
1689 if (pend - path <
len) {
1693 return rb_str_encode_ospath(d);
1696#if defined(HAVE_CHROOT)
1698nogvl_chroot(
void *dirname)
1700 return (
void *)(
VALUE)chroot((
const char *)dirname);
1718 path = check_dirname(path);
1719 if (IO_WITHOUT_GVL_INT(nogvl_chroot, (
void *)RSTRING_PTR(path)) == -1)
1720 rb_sys_fail_path(path);
1725#define dir_s_chroot rb_f_notimplement
1734nogvl_mkdir(
void *ptr)
1738 return (
void *)(
VALUE)mkdir(m->path, m->mode);
1764 if (
rb_scan_args(argc, argv,
"11", &path, &vmode) == 2) {
1771 path = check_dirname(path);
1772 m.path = RSTRING_PTR(path);
1773 r = IO_WITHOUT_GVL_INT(nogvl_mkdir, &m);
1775 rb_sys_fail_path(path);
1781nogvl_rmdir(
void *ptr)
1783 const char *path = ptr;
1785 return (
void *)(
VALUE)rmdir(path);
1804 dir = check_dirname(dir);
1805 p = RSTRING_PTR(dir);
1806 r = IO_WITHOUT_GVL_INT(nogvl_rmdir, (
void *)p);
1808 rb_sys_fail_path(dir);
1814#ifdef RUBY_FUNCTION_NAME_STRING
1821#ifndef RUBY_FUNCTION_NAME_STRING
1822#define sys_enc_warning_in(func, mesg, enc) sys_enc_warning(mesg, enc)
1826sys_warning_1(
VALUE mesg)
1829#ifdef RUBY_FUNCTION_NAME_STRING
1830 rb_sys_enc_warning(arg->enc,
"%s: %s", arg->func, arg->mesg);
1832 rb_sys_enc_warning(arg->enc,
"%s", arg->mesg);
1838sys_enc_warning_in(
const char *func,
const char *mesg,
rb_encoding *enc)
1841#ifdef RUBY_FUNCTION_NAME_STRING
1846 rb_protect(sys_warning_1, (
VALUE)&arg, 0);
1849#define GLOB_VERBOSE (1U << (sizeof(int) * CHAR_BIT - 1))
1850#define sys_warning(val, enc) \
1851 ((flags & GLOB_VERBOSE) ? sys_enc_warning_in(RUBY_FUNCTION_NAME_STRING, (val), (enc)) :(void)0)
1854glob_alloc_size(
size_t x,
size_t y)
1866glob_alloc_n(
size_t x,
size_t y)
1868 return malloc(glob_alloc_size(x, y));
1872glob_realloc_n(
void *p,
size_t x,
size_t y)
1874 return realloc(p, glob_alloc_size(x, y));
1877#define GLOB_ALLOC(type) ((type *)malloc(sizeof(type)))
1878#define GLOB_ALLOC_N(type, n) ((type *)glob_alloc_n(sizeof(type), n))
1879#define GLOB_REALLOC(ptr, size) realloc((ptr), (size))
1880#define GLOB_REALLOC_N(ptr, n) glob_realloc_n(ptr, sizeof(*(ptr)), n)
1881#define GLOB_FREE(ptr) free(ptr)
1882#define GLOB_JUMP_TAG(status) (((status) == -1) ? rb_memerror() : rb_jump_tag(status))
1888ALWAYS_INLINE(
static int to_be_ignored(
int e));
1892 return e == ENOENT || e == ENOTDIR;
1896#define STAT(args) (int)(VALUE)nogvl_stat(&(args))
1897#define LSTAT(args) (int)(VALUE)nogvl_lstat(&(args))
1899#define STAT(args) IO_WITHOUT_GVL_INT(nogvl_stat, (void *)&(args))
1900#define LSTAT(args) IO_WITHOUT_GVL_INT(nogvl_lstat, (void *)&(args))
1903typedef int ruby_glob_errfunc(
const char*,
VALUE,
const void*,
int);
1906 ruby_glob_errfunc *error;
1910at_subpath(
int fd,
size_t baselen,
const char *path)
1913 if (fd != (
int)AT_FDCWD && baselen > 0) {
1915 if (*path ==
'/') ++path;
1918 return *path ? path :
".";
1922struct fstatat_args {
1930nogvl_fstatat(
void *args)
1932 struct fstatat_args *arg = (
struct fstatat_args *)args;
1933 return (
void *)(
VALUE)fstatat(arg->fd, arg->path, arg->pst, arg->flag);
1942nogvl_stat(
void *args)
1945 return (
void *)(
VALUE)stat(arg->path, arg->pst);
1951do_stat(
int fd,
const char *path,
struct stat *pst,
int flags,
rb_encoding *enc)
1954 struct fstatat_args args;
1959 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (
void *)&args);
1964 int ret = STAT(args);
1966 if (ret < 0 && !to_be_ignored(
errno))
1967 sys_warning(path, enc);
1972#if defined HAVE_LSTAT || defined lstat || USE_OPENDIR_AT
1975nogvl_lstat(
void *args)
1978 return (
void *)(
VALUE)lstat(arg->path, arg->pst);
1983do_lstat(
int fd,
const char *path,
struct stat *pst,
int flags,
rb_encoding *enc)
1986 struct fstatat_args args;
1990 args.flag = AT_SYMLINK_NOFOLLOW;
1991 int ret = IO_WITHOUT_GVL_INT(nogvl_fstatat, (
void *)&args);
1996 int ret = LSTAT(args);
1998 if (ret < 0 && !to_be_ignored(
errno))
1999 sys_warning(path, enc);
2004#define do_lstat do_stat
2013with_gvl_gc_for_fd(
void *ptr)
2017 return (
void *)RBOOL(rb_gc_for_fd(*e));
2021gc_for_fd_with_gvl(
int e)
2026 return RBOOL(rb_gc_for_fd(e));
2030nogvl_opendir_at(
void *ptr)
2036 const int opendir_flags = (O_RDONLY|O_CLOEXEC|
2041 int fd = openat(oaa->basefd, oaa->path, opendir_flags);
2043 dirp = fd >= 0 ? fdopendir(fd) : 0;
2047 switch (gc_for_fd_with_gvl(e)) {
2049 if (fd < 0) fd = openat(oaa->basefd, oaa->path, opendir_flags);
2050 if (fd >= 0) dirp = fdopendir(fd);
2051 if (dirp)
return dirp;
2056 if (fd >= 0) close(fd);
2061 dirp = opendir(oaa->path);
2062 if (!dirp && gc_for_fd_with_gvl(
errno))
2063 dirp = opendir(oaa->path);
2070opendir_at(
int basefd,
const char *path)
2074 oaa.basefd = basefd;
2078 return IO_WITHOUT_GVL(nogvl_opendir_at, &oaa);
2080 return nogvl_opendir_at(&oaa);
2084do_opendir(
const int basefd,
size_t baselen,
const char *path,
int flags,
rb_encoding *enc,
2085 ruby_glob_errfunc *errfunc,
VALUE arg,
int *status)
2090 if (!fundamental_encoding_p(enc)) {
2091 tmp = rb_enc_str_new(path, strlen(path), enc);
2092 tmp = rb_str_encode_ospath(tmp);
2093 path = RSTRING_PTR(tmp);
2096 dirp = opendir_at(basefd, at_subpath(basefd, baselen, path));
2101 if (!to_be_ignored(e)) {
2103 *status = (*errfunc)(path, arg, enc, e);
2106 sys_warning(path, enc);
2111 if (tmp) rb_str_resize(tmp, 0);
2118enum glob_pattern_type { PLAIN, ALPHA, BRACE, MAGICAL, RECURSIVE, MATCH_ALL, MATCH_DIR };
2121static enum glob_pattern_type
2122has_magic(
const char *p,
const char *pend,
int flags,
rb_encoding *enc)
2124 const int escape = !(flags & FNM_NOESCAPE);
2130 while (p < pend && (c = *p++) != 0) {
2142 if (escape && p++ >= pend)
2161 p = Next(p-1, pend, enc);
2164 return hasmagical ? MAGICAL : hasalpha ? ALPHA : PLAIN;
2169find_dirsep(
const char *p,
const char *pend,
int flags,
rb_encoding *enc)
2171 const int escape = !(flags & FNM_NOESCAPE);
2176 while ((c = *p++) != 0) {
2198 if (escape && !(c = *p++))
2203 p = Next(p-1, pend, enc);
2211remove_backslashes(
char *p,
register const char *pend,
rb_encoding *enc)
2219 memmove(t, s, p - s);
2230 memmove(t, s, p - s);
2237 enum glob_pattern_type
type;
2241static void glob_free_pattern(
struct glob_pattern *list);
2244glob_make_pattern(
const char *p,
const char *e,
int flags,
rb_encoding *enc)
2250 while (p < e && *p) {
2252 if (!tmp)
goto error;
2253 if (p + 2 < e && p[0] ==
'*' && p[1] ==
'*' && p[2] ==
'/') {
2255 do { p += 3;
while (*p ==
'/') p++; }
while (p[0] ==
'*' && p[1] ==
'*' && p[2] ==
'/');
2256 tmp->type = RECURSIVE;
2262 const char *m = find_dirsep(p, e, flags, enc);
2263 const enum glob_pattern_type magic = has_magic(p, m, flags, enc);
2264 const enum glob_pattern_type non_magic = (USE_NAME_ON_FS || FNM_SYSCASE) ? PLAIN : ALPHA;
2267 if (!(FNM_SYSCASE || magic > non_magic) && !recursive && *m) {
2269 while (has_magic(m+1, m2 = find_dirsep(m+1, e, flags, enc), flags, enc) <= non_magic &&
2274 buf = GLOB_ALLOC_N(
char, m-p+1);
2279 memcpy(buf, p, m-p);
2281 tmp->type = magic > MAGICAL ? MAGICAL : magic > non_magic ? magic : PLAIN;
2300 tmp->type = dirsep ? MATCH_DIR : MATCH_ALL;
2309 glob_free_pattern(list);
2320 GLOB_FREE(tmp->str);
2326join_path(
const char *path,
size_t len,
int dirsep,
const char *name,
size_t namlen)
2328 char *buf = GLOB_ALLOC_N(
char,
len+namlen+(dirsep?1:0)+1);
2331 memcpy(buf, path,
len);
2335 memcpy(buf+
len, name, namlen);
2336 buf[
len+namlen] =
'\0';
2340#ifdef HAVE_GETATTRLIST
2341# if defined HAVE_FGETATTRLIST
2342# define is_case_sensitive(dirp, path) is_case_sensitive(dirp)
2344# define is_case_sensitive(dirp, path) is_case_sensitive(path)
2347is_case_sensitive(
DIR *dirp,
const char *path)
2351 vol_capabilities_attr_t cap[1];
2353 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, 0, ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES};
2354 const vol_capabilities_attr_t *
const cap = attrbuf[0].cap;
2355 const int idx = VOL_CAPABILITIES_FORMAT;
2356 const uint32_t mask = VOL_CAP_FMT_CASE_SENSITIVE;
2357 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2358# if defined HAVE_FGETATTRLIST
2359 int ret = gvl_fgetattrlist(&args, dirfd(dirp));
2361 int ret = gvl_getattrlist(&args, path);
2366 if (!(cap->valid[idx] & mask))
2368 return (cap->capabilities[idx] & mask) != 0;
2372replace_real_basename(
char *path,
long base,
rb_encoding *enc,
int norm_p,
int flags, rb_pathtype_t *
type)
2376 attrreference_t ref[1];
2377 fsobj_type_t objtype;
2378 char path[MAXPATHLEN * 3];
2380 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_NAME|ATTR_CMN_OBJTYPE};
2381 const attrreference_t *
const ar = attrbuf[0].ref;
2385 IF_NORMALIZE_UTF8PATH(
VALUE utf8str =
Qnil);
2388 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
2389 if (gvl_getattrlist(&args, path)) {
2390 if (!to_be_ignored(
errno))
2391 sys_warning(path, enc);
2395 switch (attrbuf[0].objtype) {
2396 case VREG: *
type = path_regular;
break;
2397 case VDIR: *
type = path_directory;
break;
2398 case VLNK: *
type = path_symlink;
break;
2399 default: *
type = path_exist;
break;
2401 name = (
char *)ar + ar->attr_dataoffset;
2402 len = (long)ar->attr_length - 1;
2403 if (name +
len > (
char *)attrbuf +
sizeof(attrbuf))
2406# if NORMALIZE_UTF8PATH
2407 if (norm_p && has_nonascii(name,
len)) {
2408 if (!
NIL_P(utf8str = rb_str_normalize_ospath(name,
len))) {
2414 tmp = GLOB_REALLOC(path, base +
len + 1);
2417 memcpy(path + base, name,
len);
2418 path[base +
len] =
'\0';
2420 IF_NORMALIZE_UTF8PATH(
if (!
NIL_P(utf8str)) rb_str_resize(utf8str, 0));
2425int rb_w32_reparse_symlink_p(
const WCHAR *path);
2428replace_real_basename(
char *path,
long base,
rb_encoding *enc,
int norm_p,
int flags, rb_pathtype_t *
type)
2430 char *plainname = path;
2431 volatile VALUE tmp = 0;
2432 WIN32_FIND_DATAW fd;
2433 WIN32_FILE_ATTRIBUTE_DATA fa;
2435 HANDLE h = INVALID_HANDLE_VALUE;
2438 if (!fundamental_encoding_p(enc)) {
2440 tmp = rb_str_encode_ospath(tmp);
2441 plainname = RSTRING_PTR(tmp);
2443 wplain = rb_w32_mbstr_to_wstr(CP_UTF8, plainname, -1, &wlen);
2444 if (tmp) rb_str_resize(tmp, 0);
2445 if (!wplain)
return path;
2446 if (GetFileAttributesExW(wplain, GetFileExInfoStandard, &fa)) {
2447 h = FindFirstFileW(wplain, &fd);
2448 e = rb_w32_map_errno(GetLastError());
2450 if (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2451 if (!rb_w32_reparse_symlink_p(wplain))
2452 fa.dwFileAttributes &= ~FILE_ATTRIBUTE_REPARSE_POINT;
2455 if (h == INVALID_HANDLE_VALUE) {
2457 if (e && !to_be_ignored(e)) {
2459 sys_warning(path, enc);
2465 (fa.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ? path_symlink :
2466 (fa.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? path_directory :
2470 tmp = rb_w32_conv_from_wchar(fd.cFileName, enc);
2471 wlen = RSTRING_LEN(tmp);
2472 buf = GLOB_REALLOC(path, base + wlen + 1);
2475 memcpy(path + base, RSTRING_PTR(tmp), wlen);
2476 path[base + wlen] = 0;
2478 rb_str_resize(tmp, 0);
2482 wlen = WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, NULL, 0, NULL, NULL);
2483 utf8filename = GLOB_REALLOC(0, wlen);
2486 WideCharToMultiByte(CP_UTF8, 0, fd.cFileName, -1, utf8filename, wlen, NULL, NULL);
2487 buf = GLOB_REALLOC(path, base + wlen + 1);
2490 memcpy(path + base, utf8filename, wlen);
2491 path[base + wlen] = 0;
2493 GLOB_FREE(utf8filename);
2498#elif USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2499# error not implemented
2503# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
2508# define S_ISLNK(m) (0)
2510# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
2515 void (*func)(
const char *,
VALUE,
void *);
2523#define glob_call_func(func, path, arg, enc) (*(func))((path), (arg), (void *)(enc))
2526glob_func_caller(
VALUE val)
2530 glob_call_func(args->func, args->path, args->value, args->enc);
2541glob_func_warning(
VALUE val)
2544 rb_syserr_enc_warning(arg->error, arg->enc,
"%s", arg->path);
2550rb_glob_warning(
const char *path,
VALUE a,
const void *enc,
int error)
2558 rb_protect(glob_func_warning, (
VALUE)&args, &status);
2563NORETURN(
static VALUE glob_func_error(
VALUE val));
2566glob_func_error(
VALUE val)
2575rb_glob_error(
const char *path,
VALUE a,
const void *enc,
int error)
2586 errfunc = glob_func_warning;
2591 rb_protect(errfunc, (
VALUE)&args, &status);
2599 const char *d_altname;
2607 if (fnmatch(pat, enc, name, flags) == 0)
return 1;
2609 if (dp->d_altname && (flags & FNM_SHORTNAME)) {
2610 if (fnmatch(pat, enc, dp->d_altname, flags) == 0)
return 1;
2622 rb_pathtype_t pathtype;
2635dirent_match_brace(
const char *pattern,
VALUE val,
void *enc)
2639 return dirent_match(pattern, enc, arg->name, arg->dp, arg->flags);
2648 size_t path_len = 0;
2650 for (p = *beg; p; p = p->next) {
2665 path_len = strlen(str);
2666 path = GLOB_ALLOC_N(
char, path_len + 1);
2668 memcpy(path, str, path_len);
2669 path[path_len] =
'\0';
2673 size_t len = strlen(str);
2675 tmp = GLOB_REALLOC(path, path_len +
len + 2);
2678 path[path_len++] =
'/';
2679 memcpy(path + path_len, str,
len);
2681 path[path_len] =
'\0';
2688static int push_caller(
const char *path,
VALUE val,
void *enc);
2693static const size_t rb_dirent_name_offset =
2697dirent_copy(
const struct dirent *dp,
rb_dirent_t *rdp)
2699 if (!dp)
return NULL;
2700 size_t namlen = NAMLEN(dp);
2701 const size_t altlen =
2703 dp->d_altlen ? dp->d_altlen + 1 :
2707 if (!rdp && !(newrdp = malloc(rb_dirent_name_offset + namlen + 1 + altlen)))
2709 newrdp->d_namlen = namlen;
2711 char *name = (
char *)newrdp + rb_dirent_name_offset;
2712 memcpy(name, dp->d_name, namlen);
2713 name[namlen] =
'\0';
2715 newrdp->d_altname = NULL;
2717 char *
const altname = name + namlen + 1;
2718 memcpy(altname, dp->d_altname, altlen - 1);
2719 altname[altlen - 1] =
'\0';
2720 newrdp->d_altname = altname;
2723 newrdp->d_name = name;
2726 newrdp->d_name = dp->d_name;
2728 newrdp->d_altname = dp->d_altname;
2732 newrdp->d_type = dp->d_type;
2751glob_sort_cmp(
const void *a,
const void *b,
void *e)
2755 return strcmp(ent1->d_name, ent2->d_name);
2761 if (flags & FNM_GLOB_NOSORT) {
2762 check_closedir(ent->nosort.dirp);
2763 ent->nosort.dirp = NULL;
2765 else if (ent->sort.entries) {
2766 for (
size_t i = 0, count = ent->sort.count; i < count;) {
2767 GLOB_FREE(ent->sort.entries[i++]);
2769 GLOB_FREE(ent->sort.entries);
2770 ent->sort.entries = NULL;
2771 ent->sort.count = ent->sort.idx = 0;
2779 if (flags & FNM_GLOB_NOSORT) {
2780 ent->nosort.dirp = dirp;
2786 size_t count = 0, capacity = 0;
2787 ent->sort.count = 0;
2789 ent->sort.entries = 0;
2791 if ((capacity = dirp->nfiles) > 0) {
2792 if (!(newp = GLOB_ALLOC_N(
rb_dirent_t, capacity))) {
2793 check_closedir(dirp);
2796 ent->sort.entries = newp;
2799 while ((dp = READDIR(dirp, enc)) != NULL) {
2804 if (count >= capacity) {
2806 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, capacity))) {
2810 ent->sort.entries = newp;
2812 ent->sort.entries[count++] = rdp;
2813 ent->sort.count = count;
2815 check_closedir(dirp);
2816 if (count < capacity) {
2817 if (!(newp = GLOB_REALLOC_N(ent->sort.entries, count))) {
2818 glob_dir_finish(ent, 0);
2821 ent->sort.entries = newp;
2823 ruby_qsort(ent->sort.entries, ent->sort.count,
sizeof(ent->sort.entries[0]),
2824 glob_sort_cmp, NULL);
2829 glob_dir_finish(ent, 0);
2830 check_closedir(dirp);
2837 if (flags & FNM_GLOB_NOSORT) {
2838 return dirent_copy(READDIR(ent->nosort.dirp, enc), &ent->nosort.ent);
2840 else if (ent->sort.idx < ent->sort.count) {
2841 return ent->sort.entries[ent->sort.idx++];
2855 rb_pathtype_t pathtype,
2866 int plain = 0, brace = 0, magical = 0, recursive = 0, match_all = 0, match_dir = 0;
2867 int escape = !(flags & FNM_NOESCAPE);
2868 size_t pathlen = baselen + namelen;
2870 rb_check_stack_overflow();
2872 for (cur = beg; cur < end; ++cur) {
2874 if (p->type == RECURSIVE) {
2883#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
2890 if (!recursive || strchr(p->str,
'/')) {
2904 rb_bug(
"continuous RECURSIVEs");
2910 char* brace_path = join_path_from_pattern(beg);
2911 if (!brace_path)
return -1;
2914 args.baselen = baselen;
2915 args.namelen = namelen;
2916 args.dirsep = dirsep;
2917 args.pathtype = pathtype;
2921 status = ruby_brace_expand(brace_path, flags, push_caller, (
VALUE)&args, enc,
Qfalse);
2922 GLOB_FREE(brace_path);
2927 if (match_all && pathtype == path_unknown) {
2928 if (do_lstat(fd, path, &st, flags, enc) == 0) {
2929 pathtype = IFTODT(st.st_mode);
2932 pathtype = path_noent;
2935 if (match_dir && (pathtype == path_unknown || pathtype == path_symlink)) {
2936 if (do_stat(fd, path, &st, flags, enc) == 0) {
2937 pathtype = IFTODT(st.st_mode);
2940 pathtype = path_noent;
2943 if (match_all && pathtype > path_noent) {
2944 const char *subpath = path + baselen + (baselen && path[baselen] ==
'/');
2945 status = glob_call_func(funcs->match, subpath, arg, enc);
2946 if (status)
return status;
2948 if (match_dir && pathtype == path_directory) {
2949 int seplen = (baselen && path[baselen] ==
'/');
2950 const char *subpath = path + baselen + seplen;
2951 char *tmp = join_path(subpath, namelen - seplen, dirsep,
"", 0);
2952 if (!tmp)
return -1;
2953 status = glob_call_func(funcs->match, tmp, arg, enc);
2955 if (status)
return status;
2959 if (pathtype == path_noent)
return 0;
2961 if (magical || recursive) {
2964# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2965 char *plainname = 0;
2967 IF_NORMALIZE_UTF8PATH(
int norm_p);
2968# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
2969 if (cur + 1 == end && (*cur)->type <= ALPHA) {
2970 plainname = join_path(path, pathlen, dirsep, (*cur)->str, strlen((*cur)->str));
2971 if (!plainname)
return -1;
2972 dirp = do_opendir(fd, basename, plainname, flags, enc, funcs->error, arg, &status);
2973 GLOB_FREE(plainname);
2979 dirp = do_opendir(fd, baselen, path, flags, enc, funcs->error, arg, &status);
2981# if FNM_SYSCASE || NORMALIZE_UTF8PATH
2982 if ((magical < 2) && !recursive && (
errno == EACCES)) {
2989 IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp, *path ? path :
"."));
2991# if NORMALIZE_UTF8PATH
2992 if (!(norm_p || magical || recursive)) {
2993 check_closedir(dirp);
2997# ifdef HAVE_GETATTRLIST
2998 if (is_case_sensitive(dirp, path) == 0)
2999 flags |= FNM_CASEFOLD;
3002 if (!glob_opendir(&globent, dirp, flags, enc)) {
3005 status = (*funcs->error)(path, arg, enc, ENOMEM);
3008 sys_warning(path, enc);
3013 int skipdot = (flags & FNM_GLOB_SKIPDOT);
3014 flags |= FNM_GLOB_SKIPDOT;
3016 while ((dp = glob_getent(&globent, flags, enc)) != NULL) {
3018 rb_pathtype_t new_pathtype = path_unknown;
3022 IF_NORMALIZE_UTF8PATH(
VALUE utf8str =
Qnil);
3025 namlen = dp->d_namlen;
3026 if (name[0] ==
'.') {
3030 if (recursive && !(flags & FNM_DOTMATCH))
continue;
3031 if (skipdot)
continue;
3033 new_pathtype = path_directory;
3035 else if (namlen == 2 && name[1] ==
'.') {
3041# if NORMALIZE_UTF8PATH
3042 if (norm_p && has_nonascii(name, namlen)) {
3043 if (!
NIL_P(utf8str = rb_str_normalize_ospath(name, namlen))) {
3048 buf = join_path(path, pathlen, dirsep, name, namlen);
3049 IF_NORMALIZE_UTF8PATH(
if (!
NIL_P(utf8str)) rb_str_resize(utf8str, 0));
3054 name = buf + pathlen + (dirsep != 0);
3056 if (dp->d_type != DT_UNKNOWN) {
3058 new_pathtype = dp->d_type;
3061 if (recursive && dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1) &&
3062 new_pathtype == path_unknown) {
3064 if (do_lstat(fd, buf, &st, flags, enc) == 0)
3065 new_pathtype = IFTODT(st.st_mode);
3067 new_pathtype = path_noent;
3070 new_beg = new_end = GLOB_ALLOC_N(
struct glob_pattern *, (end - beg) * 2);
3077 for (cur = beg; cur < end; ++cur) {
3080 if (p->type == RECURSIVE) {
3081 if (new_pathtype == path_directory ||
3082 new_pathtype == path_exist) {
3083 if (dotfile < ((flags & FNM_DOTMATCH) ? 2 : 1))
3093 if (ruby_brace_expand(p->str, flags, dirent_match_brace,
3095 *new_end++ = p->next;
3098# if USE_NAME_ON_FS == USE_NAME_ON_FS_BY_FNMATCH
3100 *new_end++ = p->next;
3106 if (dirent_match(p->str, enc, name, dp, flags))
3107 *new_end++ = p->next;
3113 status = glob_helper(fd, buf, baselen, name - buf - baselen + namlen, 1,
3114 new_pathtype, new_beg, new_end,
3115 flags, funcs, arg, enc);
3121 glob_dir_finish(&globent, flags);
3126# if FNM_SYSCASE || NORMALIZE_UTF8PATH
3129 copy_beg = copy_end = GLOB_ALLOC_N(
struct glob_pattern *, end - beg);
3130 if (!copy_beg)
return -1;
3131 for (cur = beg; cur < end; ++cur)
3132 *copy_end++ = (*cur)->type <= ALPHA ? *cur : 0;
3134 for (cur = copy_beg; cur < copy_end; ++cur) {
3136 rb_pathtype_t new_pathtype = path_unknown;
3139 size_t len = strlen((*cur)->str) + 1;
3140 name = GLOB_ALLOC_N(
char,
len);
3145 memcpy(name, (*cur)->str,
len);
3147 len = remove_backslashes(name, name+
len-1, enc) - name;
3149 new_beg = new_end = GLOB_ALLOC_N(
struct glob_pattern *, end - beg);
3155 *new_end++ = (*cur)->next;
3156 for (cur2 = cur + 1; cur2 < copy_end; ++cur2) {
3157 if (*cur2 && fnmatch((*cur2)->str, enc, name, flags) == 0) {
3158 *new_end++ = (*cur2)->next;
3163 buf = join_path(path, pathlen, dirsep, name,
len);
3170#if USE_NAME_ON_FS == USE_NAME_ON_FS_REAL_BASENAME
3171 if ((*cur)->type == ALPHA) {
3172 buf = replace_real_basename(buf, pathlen + (dirsep != 0), enc,
3173 IF_NORMALIZE_UTF8PATH(1)+0,
3174 flags, &new_pathtype);
3178 status = glob_helper(fd, buf, baselen,
3179 namelen + strlen(buf + pathlen), 1,
3180 new_pathtype, new_beg, new_end,
3181 flags, funcs, arg, enc);
3188 GLOB_FREE(copy_beg);
3195push_caller(
const char *path,
VALUE val,
void *enc)
3201 list = glob_make_pattern(path, path + strlen(path), arg->flags, enc);
3205 status = glob_helper(arg->fd, arg->path, arg->baselen, arg->namelen, arg->dirsep,
3206 arg->pathtype, &list, &list + 1, arg->flags, arg->funcs,
3208 glob_free_pattern(list);
3212static int ruby_glob0(
const char *path,
int fd,
const char *base,
int flags,
3224push_glob0_caller(
const char *path,
VALUE val,
void *enc)
3227 return ruby_glob0(path, arg->fd, arg->base, arg->flags, arg->funcs, arg->arg, enc);
3231ruby_glob0(
const char *path,
int fd,
const char *base,
int flags,
3236 const char *root, *start;
3238 size_t n, baselen = 0;
3239 int status, dirsep = FALSE;
3241 start = root = path;
3250 return ruby_brace_expand(path, flags, push_glob0_caller, (
VALUE)&args, enc,
Qfalse);
3253 flags |= FNM_SYSCASE;
3255 root = rb_enc_path_skip_prefix(root, root + strlen(root), enc);
3258 if (*root ==
'/') root++;
3267 buf = GLOB_ALLOC_N(
char, n + 1);
3268 if (!buf)
return -1;
3269 MEMCPY(buf, start,
char, n);
3272 list = glob_make_pattern(root, root + strlen(root), flags, enc);
3277 status = glob_helper(fd, buf, baselen, n-baselen, dirsep,
3278 path_unknown, &list, &list + 1,
3279 flags, funcs, arg, enc);
3280 glob_free_pattern(list);
3292 return ruby_glob0(path, AT_FDCWD, 0, flags & ~GLOB_VERBOSE,
3293 &funcs, arg, rb_ascii8bit_encoding());
3297rb_glob_caller(
const char *path,
VALUE a,
void *enc)
3303 rb_protect(glob_func_caller, a, &status);
3308 rb_glob_caller, rb_glob_error,
3312rb_glob(
const char *path,
void (*func)(
const char *,
VALUE,
void *),
VALUE arg)
3319 args.enc = rb_ascii8bit_encoding();
3321 status = ruby_glob0(path, AT_FDCWD, 0, GLOB_VERBOSE, &rb_glob_funcs,
3322 (
VALUE)&args, args.enc);
3323 if (status) GLOB_JUMP_TAG(status);
3327push_pattern(
const char *path,
VALUE ary,
void *enc)
3329#if defined _WIN32 || defined __APPLE__
3331 rb_encoding *eenc = rb_default_internal_encoding();
3343 const int escape = !(flags & FNM_NOESCAPE);
3344 const char *p = str;
3345 const char *pend = p + strlen(p);
3347 const char *lbrace = 0, *rbrace = 0;
3348 int nest = 0, status = 0;
3351 if (*p ==
'{' && nest++ == 0) {
3354 if (*p ==
'}' && lbrace && --nest == 0) {
3358 if (*p ==
'\\' && escape) {
3364 if (lbrace && rbrace) {
3365 size_t len = strlen(s) + 1;
3366 char *buf = GLOB_ALLOC_N(
char,
len);
3369 if (!buf)
return -1;
3370 memcpy(buf, s, lbrace-s);
3373 while (p < rbrace) {
3374 const char *t = ++p;
3376 while (p < rbrace && !(*p ==
',' && nest == 0)) {
3377 if (*p ==
'{') nest++;
3378 if (*p ==
'}') nest--;
3379 if (*p ==
'\\' && escape) {
3380 if (++p == rbrace)
break;
3384 memcpy(buf+shift, t, p-t);
3385 strlcpy(buf+shift+(p-t), rbrace+1,
len-(shift+(p-t)));
3386 status = ruby_brace_expand(buf, flags, func, arg, enc, var);
3391 else if (!lbrace && !rbrace) {
3392 status = glob_call_func(func, s, arg, enc);
3406glob_brace(
const char *path,
VALUE val,
void *enc)
3410 return ruby_glob0(path, AT_FDCWD, 0, arg->flags, &arg->funcs, arg->value, enc);
3418 flags &= ~GLOB_VERBOSE;
3419 args.funcs.match = func;
3420 args.funcs.error = 0;
3423 return ruby_brace_expand(str, flags, glob_brace, (
VALUE)&args, enc,
Qfalse);
3429 return ruby_brace_glob_with_enc(str, flags, func, arg, rb_ascii8bit_encoding());
3439#if defined _WIN32 || defined __APPLE__
3440 str = rb_str_encode_ospath(str);
3442 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3443 enc = rb_filesystem_encoding();
3444 if (rb_enc_to_index(enc) == ENCINDEX_US_ASCII)
3445 enc = rb_ascii8bit_encoding();
3446 flags |= GLOB_VERBOSE;
3447 args.func = push_pattern;
3454 struct dir_data *dirp = RTYPEDDATA_GET_DATA(base);
3455 if (!dirp->dir) dir_closed();
3457 if ((fd = dirfd(dirp->dir)) == -1)
3458 rb_sys_fail_path(dir_inspect(base));
3462 args.base = RSTRING_PTR(base);
3464#if defined _WIN32 || defined __APPLE__
3465 enc = rb_utf8_encoding();
3468 return ruby_glob0(RSTRING_PTR(str), fd, args.base, flags, &rb_glob_funcs,
3473rb_push_glob(
VALUE str,
VALUE base,
int flags)
3482 else if (!rb_str_to_cstr(str)) {
3483 rb_raise(rb_eArgError,
"nul-separated glob pattern is deprecated");
3486 rb_enc_check(str, rb_enc_from_encoding(rb_usascii_encoding()));
3490 status = push_glob(ary, str, base, flags);
3491 if (status) GLOB_JUMP_TAG(status);
3506 status = push_glob(ary, str, base, flags);
3507 if (status) GLOB_JUMP_TAG(status);
3515dir_glob_option_base(
VALUE base)
3517 if (NIL_OR_UNDEF_P(base)) {
3521 if (rb_typeddata_is_kind_of(base, &dir_data_type)) {
3526 if (!RSTRING_LEN(base))
return Qnil;
3531dir_glob_option_sort(
VALUE sort)
3533 return (rb_bool_expected(sort,
"sort", TRUE) ? 0 : FNM_GLOB_NOSORT);
3539 const int flags = dir_glob_option_sort(sort);
3540 base = dir_glob_option_base(base);
3542 return rb_push_glob(
RARRAY_AREF(args, 0), base, flags);
3544 return dir_globs(args, base, flags);
3551 const int flags = (
NUM2INT(rflags) | dir_glob_option_sort(sort)) & ~FNM_CASEFOLD;
3552 base = dir_glob_option_base(base);
3554 ary = rb_push_glob(str, base, flags);
3557 ary = dir_globs(ary, base, flags);
3568dir_open_dir(
int argc,
VALUE *argv)
3614 dir = dir_open_dir(argc, argv);
3615 rb_ensure(dir_each, dir, dir_close, dir);
3626dir_collect(
VALUE dir)
3629 dir_each_entry(dir, dir_entry_ary_push, ary, FALSE);
3655 dir = dir_open_dir(argc, argv);
3656 return rb_ensure(dir_collect, dir, dir_close, dir);
3660dir_each_child(
VALUE dir)
3662 return dir_each_entry(dir, dir_yield,
Qnil, TRUE);
3674dir_s_each_child(
int argc,
VALUE *argv,
VALUE io)
3679 dir = dir_open_dir(argc, argv);
3680 rb_ensure(dir_each_child, dir, dir_close, dir);
3703dir_each_child_m(
VALUE dir)
3706 return dir_each_entry(dir, dir_yield,
Qnil, TRUE);
3721dir_collect_children(
VALUE dir)
3724 dir_each_entry(dir, dir_entry_ary_push, ary, TRUE);
3740dir_scan_children(
VALUE dir)
3743 dir_each_entry(dir, dir_yield_with_type,
Qnil, TRUE);
3748 dir_each_entry(dir, dir_yield_with_type, ary, TRUE);
3773dir_s_children(
int argc,
VALUE *argv,
VALUE io)
3777 dir = dir_open_dir(argc, argv);
3778 return rb_ensure(dir_collect_children, dir, dir_close, dir);
3809dir_s_scan(
int argc,
VALUE *argv,
VALUE klass)
3811 VALUE dir = dir_open_dir(argc, argv);
3812 return rb_ensure(dir_scan_children, dir, dir_close, dir);
3816fnmatch_brace(
const char *pattern,
VALUE val,
void *enc)
3819 VALUE path = arg->value;
3823 if (enc_pattern != enc_path) {
3824 if (!rb_enc_asciicompat(enc_pattern))
3826 if (!rb_enc_asciicompat(enc_path))
3830 long len = strlen(pattern);
3832 enc_pattern, &cr) !=
len)
3838 return (fnmatch(pattern, enc, RSTRING_PTR(path), arg->flags) == 0);
3843file_s_fnmatch(
int argc,
VALUE *argv,
VALUE obj)
3845 VALUE pattern, path;
3849 if (
rb_scan_args(argc, argv,
"21", &pattern, &path, &rflags) == 3)
3857 if (flags & FNM_EXTGLOB) {
3862 if (ruby_brace_expand(RSTRING_PTR(pattern), flags, fnmatch_brace,
3863 (
VALUE)&args, rb_enc_get(pattern), pattern) > 0)
3867 rb_encoding *enc = rb_enc_compatible(pattern, path);
3869 if (fnmatch(RSTRING_PTR(pattern), enc, RSTRING_PTR(path), flags) == 0)
3896 user = (argc > 0) ? argv[0] :
Qnil;
3902 return rb_home_dir_of(user,
rb_str_new(0, 0));
3905 return rb_default_home_dir(
rb_str_new(0, 0));
3924rb_file_directory_p(
void)
3930nogvl_dir_empty_p(
void *ptr)
3932 const char *path = ptr;
3933 DIR *dir = opendir(path);
3939 switch (gc_for_fd_with_gvl(e)) {
3941 dir = opendir(path);
3946 if (e == ENOTDIR)
return (
void *)
Qfalse;
3950 while ((dp = READDIR_NOGVL(dir, NULL)) != NULL) {
3951 if (!to_be_skipped(dp)) {
3956 check_closedir(dir);
3957 return (
void *)result;
3980 enum {false_on_notdir = 1};
3984 dirname = rb_str_encode_ospath(dirname);
3986 path = RSTRING_PTR(dirname);
3988#if defined HAVE_GETATTRLIST && defined ATTR_DIR_ENTRYCOUNT
3990 u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
3991 struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
3992 struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, 0);
3993 if (gvl_getattrlist(&args, path) != 0)
3994 rb_sys_fail_path(orig);
3995 if (*(
const fsobj_tag_t *)(attrbuf+1) == VT_HFS) {
3997 al.dirattr = ATTR_DIR_ENTRYCOUNT;
3998 if (gvl_getattrlist(&args, path) == 0) {
3999 if (attrbuf[0] >= 2 *
sizeof(u_int32_t))
4000 return RBOOL(attrbuf[1] == 0);
4001 if (false_on_notdir)
return Qfalse;
4003 rb_sys_fail_path(orig);
4008 result = (
VALUE)IO_WITHOUT_GVL(nogvl_dir_empty_p, (
void *)path);
4010 rb_syserr_fail_path((
int)
FIX2LONG(result), orig);
4018 sym_directory =
ID2SYM(rb_intern(
"directory"));
4019 sym_link =
ID2SYM(rb_intern(
"link"));
4020 sym_file =
ID2SYM(rb_intern(
"file"));
4021 sym_unknown =
ID2SYM(rb_intern(
"unknown"));
4023#if defined(DT_BLK) || defined(S_IFBLK)
4024 sym_block_device =
ID2SYM(rb_intern(
"blockSpecial"));
4026#if defined(DT_CHR) || defined(S_IFCHR)
4027 sym_character_device =
ID2SYM(rb_intern(
"characterSpecial"));
4029#if defined(DT_FIFO) || defined(S_IFIFO)
4030 sym_fifo =
ID2SYM(rb_intern(
"fifo"));
4032#if defined(DT_SOCK) || defined(S_IFSOCK)
4033 sym_socket =
ID2SYM(rb_intern(
"socket"));
4036 rb_gc_register_address(&chdir_lock.path);
4037 rb_gc_register_address(&chdir_lock.thread);
4038 rb_gc_register_address(&last_cwd);
4087 rb_file_const(
"FNM_NOESCAPE",
INT2FIX(FNM_NOESCAPE));
4089 rb_file_const(
"FNM_PATHNAME",
INT2FIX(FNM_PATHNAME));
4091 rb_file_const(
"FNM_DOTMATCH",
INT2FIX(FNM_DOTMATCH));
4093 rb_file_const(
"FNM_CASEFOLD",
INT2FIX(FNM_CASEFOLD));
4095 rb_file_const(
"FNM_EXTGLOB",
INT2FIX(FNM_EXTGLOB));
4097 rb_file_const(
"FNM_SYSCASE",
INT2FIX(FNM_SYSCASE));
4099 rb_file_const(
"FNM_SHORTNAME",
INT2FIX(FNM_SHORTNAME));
#define RUBY_DEBUG
Define this macro when you want assertions.
#define RUBY_ATOMIC_VALUE_SET(var, val)
Identical to RUBY_ATOMIC_SET, except it expects its arguments are VALUE.
#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.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
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.
int rb_block_given_p(void)
Determines if the current method is given a block.
#define rb_str_new2
Old name of rb_str_new_cstr.
#define ENC_CODERANGE_7BIT
Old name of RUBY_ENC_CODERANGE_7BIT.
#define T_STRING
Old name of RUBY_T_STRING.
#define xfree
Old name of ruby_xfree.
#define INT2FIX
Old name of RB_INT2FIX.
#define rb_str_cat2
Old name of rb_str_cat_cstr.
#define ID2SYM
Old name of RB_ID2SYM.
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
#define CLASS_OF
Old name of rb_class_of.
#define ISALPHA
Old name of rb_isalpha.
#define ISASCII
Old name of rb_isascii.
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
#define INT2NUM
Old name of RB_INT2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define NIL_P
Old name of RB_NIL_P.
#define MBCLEN_CHARFOUND_P(ret)
Old name of ONIGENC_MBCLEN_CHARFOUND_P.
#define NUM2LONG
Old name of RB_NUM2LONG.
#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.
VALUE rb_eIOError
IOError exception.
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.
VALUE rb_eRuntimeError
RuntimeError exception.
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.
void rb_warn(const char *fmt,...)
Identical to rb_warning(), except it reports unless $VERBOSE is nil.
VALUE rb_cObject
Object class.
VALUE rb_mEnumerable
Enumerable module.
VALUE rb_cFile
File class.
#define RB_OBJ_WRITE(old, slot, young)
Declaration of a "back" pointer.
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.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
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.
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.
int rb_enc_str_asciionly_p(VALUE str)
Queries if the passed string is "ASCII only".
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.
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.
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.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
VALUE rb_str_new_shared(VALUE str)
Identical to rb_str_new_cstr(), except it takes a Ruby's string instead of C's.
#define rb_utf8_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "UTF-8" encoding.
VALUE rb_str_append(VALUE dst, VALUE src)
Identical to rb_str_buf_append(), except it converts the right hand side before concatenating.
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...
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
VALUE rb_str_dup(VALUE str)
Duplicates a string.
void rb_must_asciicompat(VALUE obj)
Asserts that the given string's encoding is (Ruby's definition of) ASCII compatible.
VALUE rb_str_freeze(VALUE str)
This is the implementation of String#freeze.
#define rb_str_dup_frozen
Just another name of rb_str_new_frozen.
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
VALUE rb_thread_current(void)
Obtains the "current" thread.
VALUE rb_class_name(VALUE obj)
Queries the name of the given object's class.
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.
void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
(Re-)acquires the GVL.
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 ...
#define RB_NUM2INT
Just another name of rb_num2int_inline.
VALUE rb_yield_values(int n,...)
Identical to rb_yield(), except it takes variadic number of parameters and pass them to the block.
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...
VALUE rb_yield(VALUE val)
Yields the block.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
static int rb_mul_size_overflow(size_t a, size_t b, size_t max, size_t *c)
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
#define NUM2MODET
Converts a C's mode_t into an instance of rb_cInteger.
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.
#define RARRAY_AREF(a, i)
#define StringValue(v)
Ensures that the parameter object is a String.
#define RSTRING_GETMEM(str, ptrvar, lenvar)
Convenient macro to obtain the contents and length at once.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define RUBY_TYPED_FREE_IMMEDIATELY
Macros to see if each corresponding flag is defined.
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
#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...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
#define FilePathStringValue(v)
This macro actually does the same thing as FilePathValue now.
#define RB_PASS_CALLED_KEYWORDS
Pass keywords if current method is called with keywords, useful for argument delegation.
This is the struct that holds necessary info for a struct.
uintptr_t VALUE
Type that represents a Ruby object.
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.