-
Notifications
You must be signed in to change notification settings - Fork 62
/
dir.c
3870 lines (3480 loc) · 97.5 KB
/
dir.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
dir.c -
$Author$
created at: Wed Jan 5 09:51:01 JST 1994
Copyright (C) 1993-2007 Yukihiro Matsumoto
Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
Copyright (C) 2000 Information-technology Promotion Agency, Japan
**********************************************************************/
#include "ruby/internal/config.h"
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef O_CLOEXEC
# define O_CLOEXEC 0
#endif
#ifndef USE_OPENDIR_AT
# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD) && \
defined(HAVE_OPENAT) && defined(HAVE_FSTATAT)
# define USE_OPENDIR_AT 1
# else
# define USE_OPENDIR_AT 0
# endif
#endif
#if USE_OPENDIR_AT
# include <fcntl.h>
#endif
#undef HAVE_DIRENT_NAMLEN
#if defined HAVE_DIRENT_H && !defined _WIN32
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#elif defined HAVE_DIRECT_H && !defined _WIN32
# include <direct.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# define HAVE_DIRENT_NAMLEN 1
# ifdef HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
# include <ndir.h>
# endif
# ifdef _WIN32
# include "win32/dir.h"
# endif
#endif
#ifndef HAVE_STDLIB_H
char *getenv();
#endif
#ifndef HAVE_STRING_H
char *strchr(char*,char);
#endif
#ifdef HAVE_SYS_ATTR_H
#include <sys/attr.h>
#endif
#define USE_NAME_ON_FS_REAL_BASENAME 1 /* platform dependent APIs to
* get real basenames */
#define USE_NAME_ON_FS_BY_FNMATCH 2 /* select the matching
* basename by fnmatch */
#ifdef HAVE_GETATTRLIST
# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
# define RUP32(size) ((size)+3/4)
# define SIZEUP32(type) RUP32(sizeof(type))
#elif defined _WIN32
# define USE_NAME_ON_FS USE_NAME_ON_FS_REAL_BASENAME
#elif defined DOSISH
# define USE_NAME_ON_FS USE_NAME_ON_FS_BY_FNMATCH
#else
# define USE_NAME_ON_FS 0
#endif
#ifdef __APPLE__
# define NORMALIZE_UTF8PATH 1
# include <sys/param.h>
# include <sys/mount.h>
# include <sys/vnode.h>
#else
# define NORMALIZE_UTF8PATH 0
#endif
#include "encindex.h"
#include "id.h"
#include "internal.h"
#include "internal/array.h"
#include "internal/dir.h"
#include "internal/encoding.h"
#include "internal/error.h"
#include "internal/file.h"
#include "internal/gc.h"
#include "internal/io.h"
#include "internal/object.h"
#include "internal/imemo.h"
#include "internal/vm.h"
#include "ruby/encoding.h"
#include "ruby/ruby.h"
#include "ruby/thread.h"
#include "ruby/util.h"
#include "builtin.h"
#ifndef AT_FDCWD
# define AT_FDCWD -1
#endif
#define vm_initialized rb_cThread
/* define system APIs */
#ifdef _WIN32
# undef chdir
# define chdir(p) rb_w32_uchdir(p)
# undef mkdir
# define mkdir(p, m) rb_w32_umkdir((p), (m))
# undef rmdir
# define rmdir(p) rb_w32_urmdir(p)
# undef opendir
# define opendir(p) rb_w32_uopendir(p)
# define ruby_getcwd() rb_w32_ugetcwd(NULL, 0)
# define IS_WIN32 1
#else
# define IS_WIN32 0
#endif
#ifdef HAVE_GETATTRLIST
struct getattrlist_args {
const char *path;
int fd;
struct attrlist *list;
void *buf;
size_t size;
unsigned int options;
};
# define GETATTRLIST_ARGS(list_, buf_, options_) (struct getattrlist_args) \
{.list = list_, .buf = buf_, .size = sizeof(buf_), .options = options_}
static void *
nogvl_getattrlist(void *args)
{
struct getattrlist_args *arg = args;
return (void *)(VALUE)getattrlist(arg->path, arg->list, arg->buf, arg->size, arg->options);
}
static int
gvl_getattrlist(struct getattrlist_args *args, const char *path)
{
args->path = path;
return IO_WITHOUT_GVL_INT(nogvl_getattrlist, args);
}
# ifdef HAVE_FGETATTRLIST
static void *
nogvl_fgetattrlist(void *args)
{
struct getattrlist_args *arg = args;
return (void *)(VALUE)fgetattrlist(arg->fd, arg->list, arg->buf, arg->size, arg->options);
}
static int
gvl_fgetattrlist(struct getattrlist_args *args, int fd)
{
args->fd = fd;
return IO_WITHOUT_GVL_INT(nogvl_fgetattrlist, args);
}
# endif
#endif
#if NORMALIZE_UTF8PATH
# if defined HAVE_FGETATTRLIST || !defined HAVE_GETATTRLIST
# define need_normalization(dirp, path) need_normalization(dirp)
# else
# define need_normalization(dirp, path) need_normalization(path)
# endif
static inline int
need_normalization(DIR *dirp, const char *path)
{
# if defined HAVE_FGETATTRLIST || defined HAVE_GETATTRLIST
u_int32_t attrbuf[SIZEUP32(fsobj_tag_t)];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0, ATTR_CMN_OBJTAG,};
struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, 0);
# if defined HAVE_FGETATTRLIST
int ret = gvl_fgetattrlist(&args, dirfd(dirp));
# else
int ret = gvl_getattrlist(&args, path);
# endif
if (!ret) {
const fsobj_tag_t *tag = (void *)(attrbuf+1);
switch (*tag) {
case VT_HFS:
case VT_CIFS:
return TRUE;
}
}
# endif
return FALSE;
}
static inline int
has_nonascii(const char *ptr, size_t len)
{
while (len > 0) {
if (!ISASCII(*ptr)) return 1;
ptr++;
--len;
}
return 0;
}
# define IF_NORMALIZE_UTF8PATH(something) something
#else
# define IF_NORMALIZE_UTF8PATH(something) /* nothing */
#endif
#if defined(IFTODT) && defined(DT_UNKNOWN)
# define EMULATE_IFTODT 0
#else
# define EMULATE_IFTODT 1
#endif
#if EMULATE_IFTODT
# define IFTODT(m) (((m) & S_IFMT) / ((~S_IFMT & (S_IFMT-1)) + 1))
#endif
typedef enum {
#if !EMULATE_IFTODT
path_exist = DT_UNKNOWN,
path_directory = DT_DIR,
path_regular = DT_REG,
path_symlink = DT_LNK,
#else
path_exist,
path_directory = IFTODT(S_IFDIR),
path_regular = IFTODT(S_IFREG),
path_symlink = IFTODT(S_IFLNK),
#endif
path_noent = -1,
path_unknown = -2
} rb_pathtype_t;
#define FNM_NOESCAPE 0x01
#define FNM_PATHNAME 0x02
#define FNM_DOTMATCH 0x04
#define FNM_CASEFOLD 0x08
#define FNM_EXTGLOB 0x10
#if CASEFOLD_FILESYSTEM
#define FNM_SYSCASE FNM_CASEFOLD
#else
#define FNM_SYSCASE 0
#endif
#ifdef _WIN32
#define FNM_SHORTNAME 0x20
#else
#define FNM_SHORTNAME 0
#endif
#define FNM_GLOB_NOSORT 0x40
#define FNM_GLOB_SKIPDOT 0x80
#define FNM_NOMATCH 1
#define FNM_ERROR 2
# define Next(p, e, enc) ((p)+ rb_enc_mbclen((p), (e), (enc)))
# define Inc(p, e, enc) ((p) = Next((p), (e), (enc)))
static char *
bracket(
const char *p, /* pattern (next to '[') */
const char *pend,
const char *s, /* string */
const char *send,
int flags,
rb_encoding *enc)
{
const int nocase = flags & FNM_CASEFOLD;
const int escape = !(flags & FNM_NOESCAPE);
unsigned int c1, c2;
int r;
int ok = 0, not = 0;
if (p >= pend) return NULL;
if (*p == '!' || *p == '^') {
not = 1;
p++;
}
while (*p != ']') {
const char *t1 = p;
if (escape && *t1 == '\\')
t1++;
if (!*t1)
return NULL;
p = t1 + (r = rb_enc_mbclen(t1, pend, enc));
if (p >= pend) return NULL;
if (p[0] == '-' && p[1] != ']') {
const char *t2 = p + 1;
int r2;
if (escape && *t2 == '\\')
t2++;
if (!*t2)
return NULL;
p = t2 + (r2 = rb_enc_mbclen(t2, pend, enc));
if (ok) continue;
if ((r <= (send-s) && memcmp(t1, s, r) == 0) ||
(r2 <= (send-s) && memcmp(t2, s, r2) == 0)) {
ok = 1;
continue;
}
c1 = rb_enc_codepoint(s, send, enc);
if (nocase) c1 = rb_enc_toupper(c1, enc);
c2 = rb_enc_codepoint(t1, pend, enc);
if (nocase) c2 = rb_enc_toupper(c2, enc);
if (c1 < c2) continue;
c2 = rb_enc_codepoint(t2, pend, enc);
if (nocase) c2 = rb_enc_toupper(c2, enc);
if (c1 > c2) continue;
}
else {
if (ok) continue;
if (r <= (send-s) && memcmp(t1, s, r) == 0) {
ok = 1;
continue;
}
if (!nocase) continue;
c1 = rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc);
c2 = rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc);
if (c1 != c2) continue;
}
ok = 1;
}
return ok == not ? NULL : (char *)p + 1;
}
/* If FNM_PATHNAME is set, only path element will be matched. (up to '/' or '\0')
Otherwise, entire string will be matched.
End marker itself won't be compared.
And if function succeeds, *pcur reaches end marker.
*/
#define UNESCAPE(p) (escape && *(p) == '\\' ? (p) + 1 : (p))
#define ISEND(p) (!*(p) || (pathname && *(p) == '/'))
#define RETURN(val) return *pcur = p, *scur = s, (val);
static int
fnmatch_helper(
const char **pcur, /* pattern */
const char **scur, /* string */
int flags,
rb_encoding *enc)
{
const int period = !(flags & FNM_DOTMATCH);
const int pathname = flags & FNM_PATHNAME;
const int escape = !(flags & FNM_NOESCAPE);
const int nocase = flags & FNM_CASEFOLD;
const char *ptmp = 0;
const char *stmp = 0;
const char *p = *pcur;
const char *pend = p + strlen(p);
const char *s = *scur;
const char *send = s + strlen(s);
int r;
if (period && *s == '.' && *UNESCAPE(p) != '.') /* leading period */
RETURN(FNM_NOMATCH);
while (1) {
switch (*p) {
case '*':
do { p++; } while (*p == '*');
if (ISEND(UNESCAPE(p))) {
p = UNESCAPE(p);
RETURN(0);
}
if (ISEND(s))
RETURN(FNM_NOMATCH);
ptmp = p;
stmp = s;
continue;
case '?':
if (ISEND(s))
RETURN(FNM_NOMATCH);
p++;
Inc(s, send, enc);
continue;
case '[': {
const char *t;
if (ISEND(s))
RETURN(FNM_NOMATCH);
if ((t = bracket(p + 1, pend, s, send, flags, enc)) != 0) {
p = t;
Inc(s, send, enc);
continue;
}
goto failed;
}
}
/* ordinary */
p = UNESCAPE(p);
if (ISEND(s))
RETURN(ISEND(p) ? 0 : FNM_NOMATCH);
if (ISEND(p))
goto failed;
r = rb_enc_precise_mbclen(p, pend, enc);
if (!MBCLEN_CHARFOUND_P(r))
goto failed;
if (r <= (send-s) && memcmp(p, s, r) == 0) {
p += r;
s += r;
continue;
}
if (!nocase) goto failed;
if (rb_enc_toupper(rb_enc_codepoint(p, pend, enc), enc) !=
rb_enc_toupper(rb_enc_codepoint(s, send, enc), enc))
goto failed;
p += r;
Inc(s, send, enc);
continue;
failed: /* try next '*' position */
if (ptmp && stmp) {
p = ptmp;
Inc(stmp, send, enc); /* !ISEND(*stmp) */
s = stmp;
continue;
}
RETURN(FNM_NOMATCH);
}
}
static int
fnmatch(
const char *pattern,
rb_encoding *enc,
const char *string,
int flags)
{
const char *p = pattern;
const char *s = string;
const char *send = s + strlen(string);
const int period = !(flags & FNM_DOTMATCH);
const int pathname = flags & FNM_PATHNAME;
const char *ptmp = 0;
const char *stmp = 0;
if (pathname) {
while (1) {
if (p[0] == '*' && p[1] == '*' && p[2] == '/') {
do { p += 3; } while (p[0] == '*' && p[1] == '*' && p[2] == '/');
ptmp = p;
stmp = s;
}
if (fnmatch_helper(&p, &s, flags, enc) == 0) {
while (*s && *s != '/') Inc(s, send, enc);
if (*p && *s) {
p++;
s++;
continue;
}
if (!*p && !*s)
return 0;
}
/* failed : try next recursion */
if (ptmp && stmp && !(period && *stmp == '.')) {
while (*stmp && *stmp != '/') Inc(stmp, send, enc);
if (*stmp) {
p = ptmp;
stmp++;
s = stmp;
continue;
}
}
return FNM_NOMATCH;
}
}
else
return fnmatch_helper(&p, &s, flags, enc);
}
VALUE rb_cDir;
struct dir_data {
DIR *dir;
const VALUE path;
rb_encoding *enc;
};
static void
dir_free(void *ptr)
{
struct dir_data *dir = ptr;
if (dir->dir) closedir(dir->dir);
}
RUBY_REFERENCES(dir_refs) = {
RUBY_REF_EDGE(struct dir_data, path),
RUBY_REF_END
};
static const rb_data_type_t dir_data_type = {
"dir",
{
RUBY_REFS_LIST_PTR(dir_refs),
dir_free,
NULL, // Nothing allocated externally, so don't need a memsize function
},
0, NULL, RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_DECL_MARKING | RUBY_TYPED_EMBEDDABLE
};
static VALUE dir_close(VALUE);
static VALUE
dir_s_alloc(VALUE klass)
{
struct dir_data *dirp;
VALUE obj = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dirp);
dirp->dir = NULL;
RB_OBJ_WRITE(obj, &dirp->path, Qnil);
dirp->enc = NULL;
return obj;
}
static void *
nogvl_opendir(void *ptr)
{
const char *path = ptr;
return opendir(path);
}
static DIR *
opendir_without_gvl(const char *path)
{
if (vm_initialized) {
union { const void *in; void *out; } u;
u.in = path;
return IO_WITHOUT_GVL(nogvl_opendir, u.out);
}
else
return opendir(path);
}
static void
close_dir_data(struct dir_data *dp)
{
if (dp->dir) {
if (closedir(dp->dir) < 0) {
dp->dir = NULL;
rb_sys_fail("closedir");
}
dp->dir = NULL;
}
}
static void
check_closedir(DIR *dirp)
{
if (closedir(dirp) < 0)
rb_sys_fail("closedir");
}
static VALUE
dir_initialize(rb_execution_context_t *ec, VALUE dir, VALUE dirname, VALUE enc)
{
struct dir_data *dp;
VALUE orig;
const char *path;
rb_encoding *fsenc = NIL_P(enc) ? rb_filesystem_encoding() : rb_to_encoding(enc);
FilePathValue(dirname);
orig = rb_str_dup_frozen(dirname);
dirname = rb_str_encode_ospath(dirname);
dirname = rb_str_dup_frozen(dirname);
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dp);
close_dir_data(dp);
RB_OBJ_WRITE(dir, &dp->path, Qnil);
dp->enc = fsenc;
path = RSTRING_PTR(dirname);
dp->dir = opendir_without_gvl(path);
if (dp->dir == NULL) {
int e = errno;
if (rb_gc_for_fd(e)) {
dp->dir = opendir_without_gvl(path);
}
#ifdef HAVE_GETATTRLIST
else if (e == EIO) {
u_int32_t attrbuf[1];
struct attrlist al = {ATTR_BIT_MAP_COUNT, 0};
struct getattrlist_args args = GETATTRLIST_ARGS(&al, attrbuf, FSOPT_NOFOLLOW);
if (gvl_getattrlist(&args, path) == 0) {
dp->dir = opendir_without_gvl(path);
}
}
#endif
if (dp->dir == NULL) {
RB_GC_GUARD(dirname);
rb_syserr_fail_path(e, orig);
}
}
RB_OBJ_WRITE(dir, &dp->path, orig);
return dir;
}
static VALUE
dir_s_open(rb_execution_context_t *ec, VALUE klass, VALUE dirname, VALUE enc)
{
struct dir_data *dp;
VALUE dir = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dp);
dir_initialize(ec, dir, dirname, enc);
return dir;
}
static VALUE
dir_s_close(rb_execution_context_t *ec, VALUE klass, VALUE dir)
{
return dir_close(dir);
}
# if defined(HAVE_FDOPENDIR) && defined(HAVE_DIRFD)
static void *
nogvl_fdopendir(void *fd)
{
return fdopendir((int)(VALUE)fd);
}
/*
* call-seq:
* Dir.for_fd(fd) -> dir
*
* Returns a new \Dir object representing the directory specified by the given
* integer directory file descriptor +fd+:
*
* d0 = Dir.new('..')
* d1 = Dir.for_fd(d0.fileno)
*
* Note that the returned +d1+ does not have an associated path:
*
* d0.path # => '..'
* d1.path # => nil
*
* This method uses the
* {fdopendir()}[https://www.man7.org/linux/man-pages/man3/fdopendir.3p.html]
* function defined by POSIX 2008;
* the method is not implemented on non-POSIX platforms (raises NotImplementedError).
*/
static VALUE
dir_s_for_fd(VALUE klass, VALUE fd)
{
struct dir_data *dp;
VALUE dir = TypedData_Make_Struct(klass, struct dir_data, &dir_data_type, dp);
if (!(dp->dir = IO_WITHOUT_GVL(nogvl_fdopendir, (void *)(VALUE)NUM2INT(fd)))) {
rb_sys_fail("fdopendir");
UNREACHABLE_RETURN(Qnil);
}
RB_OBJ_WRITE(dir, &dp->path, Qnil);
return dir;
}
#else
#define dir_s_for_fd rb_f_notimplement
#endif
NORETURN(static void dir_closed(void));
static void
dir_closed(void)
{
rb_raise(rb_eIOError, "closed directory");
}
static struct dir_data *
dir_get(VALUE dir)
{
rb_check_frozen(dir);
return rb_check_typeddata(dir, &dir_data_type);
}
static struct dir_data *
dir_check(VALUE dir)
{
struct dir_data *dirp = dir_get(dir);
if (!dirp->dir) dir_closed();
return dirp;
}
#define GetDIR(obj, dirp) ((dirp) = dir_check(obj))
/*
* call-seq:
* inspect -> string
*
* Returns a string description of +self+:
*
* Dir.new('example').inspect # => "#<Dir:example>"
*
*/
static VALUE
dir_inspect(VALUE dir)
{
struct dir_data *dirp;
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
if (!NIL_P(dirp->path)) {
VALUE str = rb_str_new_cstr("#<");
rb_str_append(str, rb_class_name(CLASS_OF(dir)));
rb_str_cat2(str, ":");
rb_str_append(str, dirp->path);
rb_str_cat2(str, ">");
return str;
}
return rb_funcallv(dir, idTo_s, 0, 0);
}
/* Workaround for Solaris 10 that does not have dirfd.
Note: Solaris 11 (POSIX.1-2008 compliant) has dirfd(3C).
*/
#if defined(__sun) && !defined(HAVE_DIRFD)
# if defined(HAVE_DIR_D_FD)
# define dirfd(x) ((x)->d_fd)
# define HAVE_DIRFD 1
# elif defined(HAVE_DIR_DD_FD)
# define dirfd(x) ((x)->dd_fd)
# define HAVE_DIRFD 1
# endif
#endif
#ifdef HAVE_DIRFD
/*
* call-seq:
* fileno -> integer
*
* Returns the file descriptor used in <em>dir</em>.
*
* d = Dir.new('..')
* d.fileno # => 8
*
* This method uses the
* {dirfd()}[https://www.man7.org/linux/man-pages/man3/dirfd.3.html]
* function defined by POSIX 2008;
* the method is not implemented on non-POSIX platforms (raises NotImplementedError).
*/
static VALUE
dir_fileno(VALUE dir)
{
struct dir_data *dirp;
int fd;
GetDIR(dir, dirp);
fd = dirfd(dirp->dir);
if (fd == -1)
rb_sys_fail("dirfd");
return INT2NUM(fd);
}
#else
#define dir_fileno rb_f_notimplement
#endif
/*
* call-seq:
* path -> string or nil
*
* Returns the +dirpath+ string that was used to create +self+
* (or +nil+ if created by method Dir.for_fd):
*
* Dir.new('example').path # => "example"
*
*/
static VALUE
dir_path(VALUE dir)
{
struct dir_data *dirp;
TypedData_Get_Struct(dir, struct dir_data, &dir_data_type, dirp);
if (NIL_P(dirp->path)) return Qnil;
return rb_str_dup(dirp->path);
}
#if defined _WIN32
static int
fundamental_encoding_p(rb_encoding *enc)
{
switch (rb_enc_to_index(enc)) {
case ENCINDEX_ASCII_8BIT:
case ENCINDEX_US_ASCII:
case ENCINDEX_UTF_8:
return TRUE;
default:
return FALSE;
}
}
# define READDIR(dir, enc) rb_w32_readdir((dir), (enc))
# define READDIR_NOGVL READDIR
#else
NORETURN(static void *sys_failure(void *function));
static void *
sys_failure(void *function)
{
rb_sys_fail(function);
}
static void *
nogvl_readdir(void *dir)
{
rb_errno_set(0);
if ((dir = readdir(dir)) == NULL) {
if (rb_errno())
rb_thread_call_with_gvl(sys_failure, (void *)"readdir");
}
return dir;
}
# define READDIR(dir, enc) IO_WITHOUT_GVL(nogvl_readdir, (void *)(dir))
# define READDIR_NOGVL(dir, enc) nogvl_readdir((dir))
#endif
/* safe to use without GVL */
static int
to_be_skipped(const struct dirent *dp)
{
const char *name = dp->d_name;
if (name[0] != '.') return FALSE;
#ifdef HAVE_DIRENT_NAMLEN
switch (NAMLEN(dp)) {
case 2:
if (name[1] != '.') return FALSE;
case 1:
return TRUE;
default:
break;
}
#else
if (!name[1]) return TRUE;
if (name[1] != '.') return FALSE;
if (!name[2]) return TRUE;
#endif
return FALSE;
}
/*
* call-seq:
* read -> string or nil
*
* Reads and returns the next entry name from +self+;
* returns +nil+ if at end-of-stream;
* see {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like]:
*
* dir = Dir.new('example')
* dir.read # => "."
* dir.read # => ".."
* dir.read # => "config.h"
*
*/
static VALUE
dir_read(VALUE dir)
{
struct dir_data *dirp;
struct dirent *dp;
GetDIR(dir, dirp);
rb_errno_set(0);
if ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
return rb_external_str_new_with_enc(dp->d_name, NAMLEN(dp), dirp->enc);
}
else {
int e = errno;
if (e != 0) rb_syserr_fail(e, 0);
return Qnil; /* end of stream */
}
}
static VALUE dir_each_entry(VALUE, VALUE (*)(VALUE, VALUE), VALUE, int);
static VALUE
dir_yield(VALUE arg, VALUE path)
{
return rb_yield(path);
}
/*
* call-seq:
* each {|entry_name| ... } -> self
*
* Calls the block with each entry name in +self+:
*
* Dir.new('example').each {|entry_name| p entry_name }
*
* Output:
* "."
* ".."
* "config.h"
* "lib"
* "main.rb"
*
* With no block given, returns an Enumerator.
*
*/
static VALUE
dir_each(VALUE dir)
{
RETURN_ENUMERATOR(dir, 0, 0);
return dir_each_entry(dir, dir_yield, Qnil, FALSE);
}
static VALUE
dir_each_entry(VALUE dir, VALUE (*each)(VALUE, VALUE), VALUE arg, int children_only)
{
struct dir_data *dirp;
struct dirent *dp;
IF_NORMALIZE_UTF8PATH(int norm_p);
GetDIR(dir, dirp);
rewinddir(dirp->dir);
IF_NORMALIZE_UTF8PATH(norm_p = need_normalization(dirp->dir, RSTRING_PTR(dirp->path)));
while ((dp = READDIR(dirp->dir, dirp->enc)) != NULL) {
const char *name = dp->d_name;
size_t namlen = NAMLEN(dp);
VALUE path;
if (children_only && name[0] == '.') {
if (namlen == 1) continue; /* current directory */
if (namlen == 2 && name[1] == '.') continue; /* parent directory */
}
#if NORMALIZE_UTF8PATH
if (norm_p && has_nonascii(name, namlen) &&
!NIL_P(path = rb_str_normalize_ospath(name, namlen))) {
path = rb_external_str_with_enc(path, dirp->enc);
}
else
#endif
path = rb_external_str_new_with_enc(name, namlen, dirp->enc);
(*each)(arg, path);
}
return dir;
}
#ifdef HAVE_TELLDIR
/*
* call-seq:
* tell -> integer
*
* Returns the current position of +self+;
* see {Dir As Stream-Like}[rdoc-ref:Dir@Dir+As+Stream-Like]:
*
* dir = Dir.new('example')
* dir.tell # => 0
* dir.read # => "."
* dir.tell # => 1
*
*/
static VALUE
dir_tell(VALUE dir)
{
struct dir_data *dirp;
long pos;
GetDIR(dir, dirp);
if((pos = telldir(dirp->dir)) < 0)
rb_sys_fail("telldir");
return rb_int2inum(pos);
}
#else
#define dir_tell rb_f_notimplement