Fix races with threads and file descriptors.
[bpt/emacs.git] / src / dired.c
1 /* Lisp functions for making directory listings.
2 Copyright (C) 1985-1986, 1993-1994, 1999-2013 Free Software
3 Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30 #include <grp.h>
31
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <unistd.h>
35
36 #include <dirent.h>
37 #include <filemode.h>
38 #include <stat-time.h>
39
40 #include "lisp.h"
41 #include "systime.h"
42 #include "character.h"
43 #include "buffer.h"
44 #include "commands.h"
45 #include "charset.h"
46 #include "coding.h"
47 #include "regex.h"
48 #include "blockinput.h"
49
50 static Lisp_Object Qdirectory_files;
51 static Lisp_Object Qdirectory_files_and_attributes;
52 static Lisp_Object Qfile_name_completion;
53 static Lisp_Object Qfile_name_all_completions;
54 static Lisp_Object Qfile_attributes;
55 static Lisp_Object Qfile_attributes_lessp;
56
57 static ptrdiff_t scmp (const char *, const char *, ptrdiff_t);
58 static Lisp_Object file_attributes (int, char const *, Lisp_Object);
59 \f
60 /* Return the number of bytes in DP's name. */
61 static ptrdiff_t
62 dirent_namelen (struct dirent *dp)
63 {
64 #ifdef _D_EXACT_NAMLEN
65 return _D_EXACT_NAMLEN (dp);
66 #else
67 return strlen (dp->d_name);
68 #endif
69 }
70
71 static DIR *
72 open_directory (char const *name, int *fdp)
73 {
74 DIR *d;
75 int fd, opendir_errno;
76
77 block_input ();
78
79 #ifdef DOS_NT
80 /* Directories cannot be opened. The emulation assumes that any
81 file descriptor other than AT_FDCWD corresponds to the most
82 recently opened directory. This hack is good enough for Emacs. */
83 fd = 0;
84 d = opendir (name);
85 opendir_errno = errno;
86 #else
87 fd = emacs_open (name, O_RDONLY | O_DIRECTORY, 0);
88 if (fd < 0)
89 {
90 opendir_errno = errno;
91 d = 0;
92 }
93 else
94 {
95 d = fdopendir (fd);
96 opendir_errno = errno;
97 if (! d)
98 emacs_close (fd);
99 }
100 #endif
101
102 unblock_input ();
103
104 *fdp = fd;
105 errno = opendir_errno;
106 return d;
107 }
108
109 #ifdef WINDOWSNT
110 Lisp_Object
111 directory_files_internal_w32_unwind (Lisp_Object arg)
112 {
113 Vw32_get_true_file_attributes = arg;
114 return Qnil;
115 }
116 #endif
117
118 static Lisp_Object
119 directory_files_internal_unwind (Lisp_Object dh)
120 {
121 DIR *d = XSAVE_POINTER (dh, 0);
122 block_input ();
123 closedir (d);
124 unblock_input ();
125 return Qnil;
126 }
127
128 /* Function shared by Fdirectory_files and Fdirectory_files_and_attributes.
129 If not ATTRS, return a list of directory filenames;
130 if ATTRS, return a list of directory filenames and their attributes.
131 In the latter case, ID_FORMAT is passed to Ffile_attributes. */
132
133 Lisp_Object
134 directory_files_internal (Lisp_Object directory, Lisp_Object full,
135 Lisp_Object match, Lisp_Object nosort, bool attrs,
136 Lisp_Object id_format)
137 {
138 DIR *d;
139 int fd;
140 ptrdiff_t directory_nbytes;
141 Lisp_Object list, dirfilename, encoded_directory;
142 struct re_pattern_buffer *bufp = NULL;
143 bool needsep = 0;
144 ptrdiff_t count = SPECPDL_INDEX ();
145 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
146 struct dirent *dp;
147 #ifdef WINDOWSNT
148 Lisp_Object w32_save = Qnil;
149 #endif
150
151 /* Because of file name handlers, these functions might call
152 Ffuncall, and cause a GC. */
153 list = encoded_directory = dirfilename = Qnil;
154 GCPRO5 (match, directory, list, dirfilename, encoded_directory);
155 dirfilename = Fdirectory_file_name (directory);
156
157 if (!NILP (match))
158 {
159 CHECK_STRING (match);
160
161 /* MATCH might be a flawed regular expression. Rather than
162 catching and signaling our own errors, we just call
163 compile_pattern to do the work for us. */
164 /* Pass 1 for the MULTIBYTE arg
165 because we do make multibyte strings if the contents warrant. */
166 # ifdef WINDOWSNT
167 /* Windows users want case-insensitive wildcards. */
168 bufp = compile_pattern (match, 0,
169 BVAR (&buffer_defaults, case_canon_table), 0, 1);
170 # else /* !WINDOWSNT */
171 bufp = compile_pattern (match, 0, Qnil, 0, 1);
172 # endif /* !WINDOWSNT */
173 }
174
175 /* Note: ENCODE_FILE and DECODE_FILE can GC because they can run
176 run_pre_post_conversion_on_str which calls Lisp directly and
177 indirectly. */
178 if (STRING_MULTIBYTE (dirfilename))
179 dirfilename = ENCODE_FILE (dirfilename);
180 encoded_directory = (STRING_MULTIBYTE (directory)
181 ? ENCODE_FILE (directory) : directory);
182
183 /* Now *bufp is the compiled form of MATCH; don't call anything
184 which might compile a new regexp until we're done with the loop! */
185
186 d = open_directory (SSDATA (dirfilename), &fd);
187 if (d == NULL)
188 report_file_error ("Opening directory", Fcons (directory, Qnil));
189
190 /* Unfortunately, we can now invoke expand-file-name and
191 file-attributes on filenames, both of which can throw, so we must
192 do a proper unwind-protect. */
193 record_unwind_protect (directory_files_internal_unwind,
194 make_save_pointer (d));
195
196 #ifdef WINDOWSNT
197 if (attrs)
198 {
199 extern int is_slow_fs (const char *);
200
201 /* Do this only once to avoid doing it (in w32.c:stat) for each
202 file in the directory, when we call Ffile_attributes below. */
203 record_unwind_protect (directory_files_internal_w32_unwind,
204 Vw32_get_true_file_attributes);
205 w32_save = Vw32_get_true_file_attributes;
206 if (EQ (Vw32_get_true_file_attributes, Qlocal))
207 {
208 /* w32.c:stat will notice these bindings and avoid calling
209 GetDriveType for each file. */
210 if (is_slow_fs (SDATA (dirfilename)))
211 Vw32_get_true_file_attributes = Qnil;
212 else
213 Vw32_get_true_file_attributes = Qt;
214 }
215 }
216 #endif
217
218 directory_nbytes = SBYTES (directory);
219 re_match_object = Qt;
220
221 /* Decide whether we need to add a directory separator. */
222 if (directory_nbytes == 0
223 || !IS_ANY_SEP (SREF (directory, directory_nbytes - 1)))
224 needsep = 1;
225
226 /* Loop reading blocks until EOF or error. */
227 for (;;)
228 {
229 ptrdiff_t len;
230 bool wanted = 0;
231 Lisp_Object name, finalname;
232 struct gcpro gcpro1, gcpro2;
233
234 errno = 0;
235 dp = readdir (d);
236 if (!dp)
237 {
238 if (errno == EAGAIN || errno == EINTR)
239 {
240 QUIT;
241 continue;
242 }
243 break;
244 }
245
246 len = dirent_namelen (dp);
247 name = finalname = make_unibyte_string (dp->d_name, len);
248 GCPRO2 (finalname, name);
249
250 /* Note: DECODE_FILE can GC; it should protect its argument,
251 though. */
252 name = DECODE_FILE (name);
253 len = SBYTES (name);
254
255 /* Now that we have unwind_protect in place, we might as well
256 allow matching to be interrupted. */
257 immediate_quit = 1;
258 QUIT;
259
260 if (NILP (match)
261 || re_search (bufp, SSDATA (name), len, 0, len, 0) >= 0)
262 wanted = 1;
263
264 immediate_quit = 0;
265
266 if (wanted)
267 {
268 if (!NILP (full))
269 {
270 Lisp_Object fullname;
271 ptrdiff_t nbytes = len + directory_nbytes + needsep;
272 ptrdiff_t nchars;
273
274 fullname = make_uninit_multibyte_string (nbytes, nbytes);
275 memcpy (SDATA (fullname), SDATA (directory),
276 directory_nbytes);
277
278 if (needsep)
279 SSET (fullname, directory_nbytes, DIRECTORY_SEP);
280
281 memcpy (SDATA (fullname) + directory_nbytes + needsep,
282 SDATA (name), len);
283
284 nchars = chars_in_text (SDATA (fullname), nbytes);
285
286 /* Some bug somewhere. */
287 if (nchars > nbytes)
288 emacs_abort ();
289
290 STRING_SET_CHARS (fullname, nchars);
291 if (nchars == nbytes)
292 STRING_SET_UNIBYTE (fullname);
293
294 finalname = fullname;
295 }
296 else
297 finalname = name;
298
299 if (attrs)
300 {
301 Lisp_Object fileattrs
302 = file_attributes (fd, dp->d_name, id_format);
303 list = Fcons (Fcons (finalname, fileattrs), list);
304 }
305 else
306 list = Fcons (finalname, list);
307 }
308
309 UNGCPRO;
310 }
311
312 block_input ();
313 closedir (d);
314 unblock_input ();
315 #ifdef WINDOWSNT
316 if (attrs)
317 Vw32_get_true_file_attributes = w32_save;
318 #endif
319
320 /* Discard the unwind protect. */
321 specpdl_ptr = specpdl + count;
322
323 if (NILP (nosort))
324 list = Fsort (Fnreverse (list),
325 attrs ? Qfile_attributes_lessp : Qstring_lessp);
326
327 RETURN_UNGCPRO (list);
328 }
329
330
331 DEFUN ("directory-files", Fdirectory_files, Sdirectory_files, 1, 4, 0,
332 doc: /* Return a list of names of files in DIRECTORY.
333 There are three optional arguments:
334 If FULL is non-nil, return absolute file names. Otherwise return names
335 that are relative to the specified directory.
336 If MATCH is non-nil, mention only file names that match the regexp MATCH.
337 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
338 Otherwise, the list returned is sorted with `string-lessp'.
339 NOSORT is useful if you plan to sort the result yourself. */)
340 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort)
341 {
342 Lisp_Object handler;
343 directory = Fexpand_file_name (directory, Qnil);
344
345 /* If the file name has special constructs in it,
346 call the corresponding file handler. */
347 handler = Ffind_file_name_handler (directory, Qdirectory_files);
348 if (!NILP (handler))
349 return call5 (handler, Qdirectory_files, directory,
350 full, match, nosort);
351
352 return directory_files_internal (directory, full, match, nosort, 0, Qnil);
353 }
354
355 DEFUN ("directory-files-and-attributes", Fdirectory_files_and_attributes,
356 Sdirectory_files_and_attributes, 1, 5, 0,
357 doc: /* Return a list of names of files and their attributes in DIRECTORY.
358 There are four optional arguments:
359 If FULL is non-nil, return absolute file names. Otherwise return names
360 that are relative to the specified directory.
361 If MATCH is non-nil, mention only file names that match the regexp MATCH.
362 If NOSORT is non-nil, the list is not sorted--its order is unpredictable.
363 NOSORT is useful if you plan to sort the result yourself.
364 ID-FORMAT specifies the preferred format of attributes uid and gid, see
365 `file-attributes' for further documentation.
366 On MS-Windows, performance depends on `w32-get-true-file-attributes',
367 which see. */)
368 (Lisp_Object directory, Lisp_Object full, Lisp_Object match, Lisp_Object nosort, Lisp_Object id_format)
369 {
370 Lisp_Object handler;
371 directory = Fexpand_file_name (directory, Qnil);
372
373 /* If the file name has special constructs in it,
374 call the corresponding file handler. */
375 handler = Ffind_file_name_handler (directory, Qdirectory_files_and_attributes);
376 if (!NILP (handler))
377 return call6 (handler, Qdirectory_files_and_attributes,
378 directory, full, match, nosort, id_format);
379
380 return directory_files_internal (directory, full, match, nosort, 1, id_format);
381 }
382
383 \f
384 static Lisp_Object file_name_completion (Lisp_Object, Lisp_Object, bool,
385 Lisp_Object);
386
387 DEFUN ("file-name-completion", Ffile_name_completion, Sfile_name_completion,
388 2, 3, 0,
389 doc: /* Complete file name FILE in directory DIRECTORY.
390 Returns the longest string
391 common to all file names in DIRECTORY that start with FILE.
392 If there is only one and FILE matches it exactly, returns t.
393 Returns nil if DIRECTORY contains no name starting with FILE.
394
395 If PREDICATE is non-nil, call PREDICATE with each possible
396 completion (in absolute form) and ignore it if PREDICATE returns nil.
397
398 This function ignores some of the possible completions as
399 determined by the variable `completion-ignored-extensions', which see. */)
400 (Lisp_Object file, Lisp_Object directory, Lisp_Object predicate)
401 {
402 Lisp_Object handler;
403 directory = Fexpand_file_name (directory, Qnil);
404
405 /* If the directory name has special constructs in it,
406 call the corresponding file handler. */
407 handler = Ffind_file_name_handler (directory, Qfile_name_completion);
408 if (!NILP (handler))
409 return call4 (handler, Qfile_name_completion, file, directory, predicate);
410
411 /* If the file name has special constructs in it,
412 call the corresponding file handler. */
413 handler = Ffind_file_name_handler (file, Qfile_name_completion);
414 if (!NILP (handler))
415 return call4 (handler, Qfile_name_completion, file, directory, predicate);
416
417 return file_name_completion (file, directory, 0, predicate);
418 }
419
420 DEFUN ("file-name-all-completions", Ffile_name_all_completions,
421 Sfile_name_all_completions, 2, 2, 0,
422 doc: /* Return a list of all completions of file name FILE in directory DIRECTORY.
423 These are all file names in directory DIRECTORY which begin with FILE. */)
424 (Lisp_Object file, Lisp_Object directory)
425 {
426 Lisp_Object handler;
427 directory = Fexpand_file_name (directory, Qnil);
428
429 /* If the directory name has special constructs in it,
430 call the corresponding file handler. */
431 handler = Ffind_file_name_handler (directory, Qfile_name_all_completions);
432 if (!NILP (handler))
433 return call3 (handler, Qfile_name_all_completions, file, directory);
434
435 /* If the file name has special constructs in it,
436 call the corresponding file handler. */
437 handler = Ffind_file_name_handler (file, Qfile_name_all_completions);
438 if (!NILP (handler))
439 return call3 (handler, Qfile_name_all_completions, file, directory);
440
441 return file_name_completion (file, directory, 1, Qnil);
442 }
443
444 static int file_name_completion_stat (int, struct dirent *, struct stat *);
445 static Lisp_Object Qdefault_directory;
446
447 static Lisp_Object
448 file_name_completion (Lisp_Object file, Lisp_Object dirname, bool all_flag,
449 Lisp_Object predicate)
450 {
451 DIR *d;
452 int fd;
453 ptrdiff_t bestmatchsize = 0;
454 int matchcount = 0;
455 /* If ALL_FLAG is 1, BESTMATCH is the list of all matches, decoded.
456 If ALL_FLAG is 0, BESTMATCH is either nil
457 or the best match so far, not decoded. */
458 Lisp_Object bestmatch, tem, elt, name;
459 Lisp_Object encoded_file;
460 Lisp_Object encoded_dir;
461 struct stat st;
462 bool directoryp;
463 /* If not INCLUDEALL, exclude files in completion-ignored-extensions as
464 well as "." and "..". Until shown otherwise, assume we can't exclude
465 anything. */
466 bool includeall = 1;
467 ptrdiff_t count = SPECPDL_INDEX ();
468 struct gcpro gcpro1, gcpro2, gcpro3, gcpro4, gcpro5;
469
470 elt = Qnil;
471
472 CHECK_STRING (file);
473
474 bestmatch = Qnil;
475 encoded_file = encoded_dir = Qnil;
476 GCPRO5 (file, dirname, bestmatch, encoded_file, encoded_dir);
477 specbind (Qdefault_directory, dirname);
478
479 /* Do completion on the encoded file name
480 because the other names in the directory are (we presume)
481 encoded likewise. We decode the completed string at the end. */
482 /* Actually, this is not quite true any more: we do most of the completion
483 work with decoded file names, but we still do some filtering based
484 on the encoded file name. */
485 encoded_file = STRING_MULTIBYTE (file) ? ENCODE_FILE (file) : file;
486
487 encoded_dir = ENCODE_FILE (Fdirectory_file_name (dirname));
488
489 d = open_directory (SSDATA (encoded_dir), &fd);
490 if (!d)
491 report_file_error ("Opening directory", Fcons (dirname, Qnil));
492
493 record_unwind_protect (directory_files_internal_unwind,
494 make_save_pointer (d));
495
496 /* Loop reading blocks */
497 /* (att3b compiler bug requires do a null comparison this way) */
498 while (1)
499 {
500 struct dirent *dp;
501 ptrdiff_t len;
502 bool canexclude = 0;
503
504 errno = 0;
505 dp = readdir (d);
506 if (!dp)
507 {
508 if (errno == EAGAIN || errno == EINTR)
509 {
510 QUIT;
511 continue;
512 }
513 break;
514 }
515
516 len = dirent_namelen (dp);
517
518 QUIT;
519 if (len < SCHARS (encoded_file)
520 || (scmp (dp->d_name, SSDATA (encoded_file),
521 SCHARS (encoded_file))
522 >= 0))
523 continue;
524
525 if (file_name_completion_stat (fd, dp, &st) < 0)
526 continue;
527
528 directoryp = S_ISDIR (st.st_mode) != 0;
529 tem = Qnil;
530 /* If all_flag is set, always include all.
531 It would not actually be helpful to the user to ignore any possible
532 completions when making a list of them. */
533 if (!all_flag)
534 {
535 ptrdiff_t skip;
536
537 #if 0 /* FIXME: The `scmp' call compares an encoded and a decoded string. */
538 /* If this entry matches the current bestmatch, the only
539 thing it can do is increase matchcount, so don't bother
540 investigating it any further. */
541 if (!completion_ignore_case
542 /* The return result depends on whether it's the sole match. */
543 && matchcount > 1
544 && !includeall /* This match may allow includeall to 0. */
545 && len >= bestmatchsize
546 && 0 > scmp (dp->d_name, SSDATA (bestmatch), bestmatchsize))
547 continue;
548 #endif
549
550 if (directoryp)
551 {
552 #ifndef TRIVIAL_DIRECTORY_ENTRY
553 #define TRIVIAL_DIRECTORY_ENTRY(n) (!strcmp (n, ".") || !strcmp (n, ".."))
554 #endif
555 /* "." and ".." are never interesting as completions, and are
556 actually in the way in a directory with only one file. */
557 if (TRIVIAL_DIRECTORY_ENTRY (dp->d_name))
558 canexclude = 1;
559 else if (len > SCHARS (encoded_file))
560 /* Ignore directories if they match an element of
561 completion-ignored-extensions which ends in a slash. */
562 for (tem = Vcompletion_ignored_extensions;
563 CONSP (tem); tem = XCDR (tem))
564 {
565 ptrdiff_t elt_len;
566 char *p1;
567
568 elt = XCAR (tem);
569 if (!STRINGP (elt))
570 continue;
571 /* Need to encode ELT, since scmp compares unibyte
572 strings only. */
573 elt = ENCODE_FILE (elt);
574 elt_len = SCHARS (elt) - 1; /* -1 for trailing / */
575 if (elt_len <= 0)
576 continue;
577 p1 = SSDATA (elt);
578 if (p1[elt_len] != '/')
579 continue;
580 skip = len - elt_len;
581 if (skip < 0)
582 continue;
583
584 if (scmp (dp->d_name + skip, p1, elt_len) >= 0)
585 continue;
586 break;
587 }
588 }
589 else
590 {
591 /* Compare extensions-to-be-ignored against end of this file name */
592 /* if name is not an exact match against specified string */
593 if (len > SCHARS (encoded_file))
594 /* and exit this for loop if a match is found */
595 for (tem = Vcompletion_ignored_extensions;
596 CONSP (tem); tem = XCDR (tem))
597 {
598 elt = XCAR (tem);
599 if (!STRINGP (elt)) continue;
600 /* Need to encode ELT, since scmp compares unibyte
601 strings only. */
602 elt = ENCODE_FILE (elt);
603 skip = len - SCHARS (elt);
604 if (skip < 0) continue;
605
606 if (scmp (dp->d_name + skip, SSDATA (elt), SCHARS (elt))
607 >= 0)
608 continue;
609 break;
610 }
611 }
612
613 /* If an ignored-extensions match was found,
614 don't process this name as a completion. */
615 if (CONSP (tem))
616 canexclude = 1;
617
618 if (!includeall && canexclude)
619 /* We're not including all files and this file can be excluded. */
620 continue;
621
622 if (includeall && !canexclude)
623 { /* If we have one non-excludable file, we want to exclude the
624 excludable files. */
625 includeall = 0;
626 /* Throw away any previous excludable match found. */
627 bestmatch = Qnil;
628 bestmatchsize = 0;
629 matchcount = 0;
630 }
631 }
632 /* FIXME: If we move this `decode' earlier we can eliminate
633 the repeated ENCODE_FILE on Vcompletion_ignored_extensions. */
634 name = make_unibyte_string (dp->d_name, len);
635 name = DECODE_FILE (name);
636
637 {
638 Lisp_Object regexps;
639
640 /* Ignore this element if it fails to match all the regexps. */
641 if (completion_ignore_case)
642 {
643 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
644 regexps = XCDR (regexps))
645 if (fast_string_match_ignore_case (XCAR (regexps), name) < 0)
646 break;
647 }
648 else
649 {
650 for (regexps = Vcompletion_regexp_list; CONSP (regexps);
651 regexps = XCDR (regexps))
652 if (fast_string_match (XCAR (regexps), name) < 0)
653 break;
654 }
655
656 if (CONSP (regexps))
657 continue;
658 }
659
660 /* This is a possible completion */
661 if (directoryp)
662 /* This completion is a directory; make it end with '/'. */
663 name = Ffile_name_as_directory (name);
664
665 /* Test the predicate, if any. */
666 if (!NILP (predicate))
667 {
668 Lisp_Object val;
669 struct gcpro gcpro1;
670
671 GCPRO1 (name);
672 val = call1 (predicate, name);
673 UNGCPRO;
674
675 if (NILP (val))
676 continue;
677 }
678
679 /* Suitably record this match. */
680
681 matchcount += matchcount <= 1;
682
683 if (all_flag)
684 bestmatch = Fcons (name, bestmatch);
685 else if (NILP (bestmatch))
686 {
687 bestmatch = name;
688 bestmatchsize = SCHARS (name);
689 }
690 else
691 {
692 Lisp_Object zero = make_number (0);
693 /* FIXME: This is a copy of the code in Ftry_completion. */
694 ptrdiff_t compare = min (bestmatchsize, SCHARS (name));
695 Lisp_Object cmp
696 = Fcompare_strings (bestmatch, zero,
697 make_number (compare),
698 name, zero,
699 make_number (compare),
700 completion_ignore_case ? Qt : Qnil);
701 ptrdiff_t matchsize = EQ (cmp, Qt) ? compare : eabs (XINT (cmp)) - 1;
702
703 if (completion_ignore_case)
704 {
705 /* If this is an exact match except for case,
706 use it as the best match rather than one that is not
707 an exact match. This way, we get the case pattern
708 of the actual match. */
709 /* This tests that the current file is an exact match
710 but BESTMATCH is not (it is too long). */
711 if ((matchsize == SCHARS (name)
712 && matchsize + directoryp < SCHARS (bestmatch))
713 ||
714 /* If there is no exact match ignoring case,
715 prefer a match that does not change the case
716 of the input. */
717 /* If there is more than one exact match aside from
718 case, and one of them is exact including case,
719 prefer that one. */
720 /* This == checks that, of current file and BESTMATCH,
721 either both or neither are exact. */
722 (((matchsize == SCHARS (name))
723 ==
724 (matchsize + directoryp == SCHARS (bestmatch)))
725 && (cmp = Fcompare_strings (name, zero,
726 make_number (SCHARS (file)),
727 file, zero,
728 Qnil,
729 Qnil),
730 EQ (Qt, cmp))
731 && (cmp = Fcompare_strings (bestmatch, zero,
732 make_number (SCHARS (file)),
733 file, zero,
734 Qnil,
735 Qnil),
736 ! EQ (Qt, cmp))))
737 bestmatch = name;
738 }
739 bestmatchsize = matchsize;
740
741 /* If the best completion so far is reduced to the string
742 we're trying to complete, then we already know there's no
743 other completion, so there's no point looking any further. */
744 if (matchsize <= SCHARS (file)
745 && !includeall /* A future match may allow includeall to 0. */
746 /* If completion-ignore-case is non-nil, don't
747 short-circuit because we want to find the best
748 possible match *including* case differences. */
749 && (!completion_ignore_case || matchsize == 0)
750 /* The return value depends on whether it's the sole match. */
751 && matchcount > 1)
752 break;
753
754 }
755 }
756
757 UNGCPRO;
758 /* This closes the directory. */
759 bestmatch = unbind_to (count, bestmatch);
760
761 if (all_flag || NILP (bestmatch))
762 return bestmatch;
763 /* Return t if the supplied string is an exact match (counting case);
764 it does not require any change to be made. */
765 if (matchcount == 1 && !NILP (Fequal (bestmatch, file)))
766 return Qt;
767 bestmatch = Fsubstring (bestmatch, make_number (0),
768 make_number (bestmatchsize));
769 return bestmatch;
770 }
771
772 /* Compare exactly LEN chars of strings at S1 and S2,
773 ignoring case if appropriate.
774 Return -1 if strings match,
775 else number of chars that match at the beginning. */
776
777 static ptrdiff_t
778 scmp (const char *s1, const char *s2, ptrdiff_t len)
779 {
780 register ptrdiff_t l = len;
781
782 if (completion_ignore_case)
783 {
784 while (l
785 && (downcase ((unsigned char) *s1++)
786 == downcase ((unsigned char) *s2++)))
787 l--;
788 }
789 else
790 {
791 while (l && *s1++ == *s2++)
792 l--;
793 }
794 if (l == 0)
795 return -1;
796 else
797 return len - l;
798 }
799
800 static int
801 file_name_completion_stat (int fd, struct dirent *dp, struct stat *st_addr)
802 {
803 int value;
804
805 #ifdef MSDOS
806 /* Some fields of struct stat are *very* expensive to compute on MS-DOS,
807 but aren't required here. Avoid computing the following fields:
808 st_inode, st_size and st_nlink for directories, and the execute bits
809 in st_mode for non-directory files with non-standard extensions. */
810
811 unsigned short save_djstat_flags = _djstat_flags;
812
813 _djstat_flags = _STAT_INODE | _STAT_EXEC_MAGIC | _STAT_DIRSIZE;
814 #endif /* MSDOS */
815
816 /* We want to return success if a link points to a nonexistent file,
817 but we want to return the status for what the link points to,
818 in case it is a directory. */
819 value = fstatat (fd, dp->d_name, st_addr, AT_SYMLINK_NOFOLLOW);
820 if (value == 0 && S_ISLNK (st_addr->st_mode))
821 fstatat (fd, dp->d_name, st_addr, 0);
822 #ifdef MSDOS
823 _djstat_flags = save_djstat_flags;
824 #endif /* MSDOS */
825 return value;
826 }
827 \f
828 static char *
829 stat_uname (struct stat *st)
830 {
831 #ifdef WINDOWSNT
832 return st->st_uname;
833 #else
834 struct passwd *pw = getpwuid (st->st_uid);
835
836 if (pw)
837 return pw->pw_name;
838 else
839 return NULL;
840 #endif
841 }
842
843 static char *
844 stat_gname (struct stat *st)
845 {
846 #ifdef WINDOWSNT
847 return st->st_gname;
848 #else
849 struct group *gr = getgrgid (st->st_gid);
850
851 if (gr)
852 return gr->gr_name;
853 else
854 return NULL;
855 #endif
856 }
857
858 DEFUN ("file-attributes", Ffile_attributes, Sfile_attributes, 1, 2, 0,
859 doc: /* Return a list of attributes of file FILENAME.
860 Value is nil if specified file cannot be opened.
861
862 ID-FORMAT specifies the preferred format of attributes uid and gid (see
863 below) - valid values are 'string and 'integer. The latter is the
864 default, but we plan to change that, so you should specify a non-nil value
865 for ID-FORMAT if you use the returned uid or gid.
866
867 Elements of the attribute list are:
868 0. t for directory, string (name linked to) for symbolic link, or nil.
869 1. Number of links to file.
870 2. File uid as a string or a number. If a string value cannot be
871 looked up, a numeric value, either an integer or a float, is returned.
872 3. File gid, likewise.
873 4. Last access time, as a list of integers (HIGH LOW USEC PSEC) in the
874 same style as (current-time).
875 (See a note below about access time on FAT-based filesystems.)
876 5. Last modification time, likewise. This is the time of the last
877 change to the file's contents.
878 6. Last status change time, likewise. This is the time of last change
879 to the file's attributes: owner and group, access mode bits, etc.
880 7. Size in bytes.
881 This is a floating point number if the size is too large for an integer.
882 8. File modes, as a string of ten letters or dashes as in ls -l.
883 9. An unspecified value, present only for backward compatibility.
884 10. inode number. If it is larger than what an Emacs integer can hold,
885 this is of the form (HIGH . LOW): first the high bits, then the low 16 bits.
886 If even HIGH is too large for an Emacs integer, this is instead of the form
887 (HIGH MIDDLE . LOW): first the high bits, then the middle 24 bits,
888 and finally the low 16 bits.
889 11. Filesystem device number. If it is larger than what the Emacs
890 integer can hold, this is a cons cell, similar to the inode number.
891
892 On most filesystems, the combination of the inode and the device
893 number uniquely identifies the file.
894
895 On MS-Windows, performance depends on `w32-get-true-file-attributes',
896 which see.
897
898 On some FAT-based filesystems, only the date of last access is recorded,
899 so last access time will always be midnight of that day. */)
900 (Lisp_Object filename, Lisp_Object id_format)
901 {
902 Lisp_Object encoded;
903 Lisp_Object handler;
904
905 filename = Fexpand_file_name (filename, Qnil);
906
907 /* If the file name has special constructs in it,
908 call the corresponding file handler. */
909 handler = Ffind_file_name_handler (filename, Qfile_attributes);
910 if (!NILP (handler))
911 { /* Only pass the extra arg if it is used to help backward compatibility
912 with old file handlers which do not implement the new arg. --Stef */
913 if (NILP (id_format))
914 return call2 (handler, Qfile_attributes, filename);
915 else
916 return call3 (handler, Qfile_attributes, filename, id_format);
917 }
918
919 encoded = ENCODE_FILE (filename);
920 return file_attributes (AT_FDCWD, SSDATA (encoded), id_format);
921 }
922
923 static Lisp_Object
924 file_attributes (int fd, char const *name, Lisp_Object id_format)
925 {
926 Lisp_Object values[12];
927 struct stat s;
928 int lstat_result;
929
930 /* An array to hold the mode string generated by filemodestring,
931 including its terminating space and null byte. */
932 char modes[sizeof "-rwxr-xr-x "];
933
934 char *uname = NULL, *gname = NULL;
935
936 #ifdef WINDOWSNT
937 /* We usually don't request accurate owner and group info, because
938 it can be very expensive on Windows to get that, and most callers
939 of 'lstat' don't need that. But here we do want that information
940 to be accurate. */
941 w32_stat_get_owner_group = 1;
942 #endif
943
944 lstat_result = fstatat (fd, name, &s, AT_SYMLINK_NOFOLLOW);
945
946 #ifdef WINDOWSNT
947 w32_stat_get_owner_group = 0;
948 #endif
949
950 if (lstat_result < 0)
951 return Qnil;
952
953 values[0] = (S_ISLNK (s.st_mode) ? emacs_readlinkat (fd, name)
954 : S_ISDIR (s.st_mode) ? Qt : Qnil);
955 values[1] = make_number (s.st_nlink);
956
957 if (!(NILP (id_format) || EQ (id_format, Qinteger)))
958 {
959 block_input ();
960 uname = stat_uname (&s);
961 gname = stat_gname (&s);
962 unblock_input ();
963 }
964 if (uname)
965 values[2] = DECODE_SYSTEM (build_string (uname));
966 else
967 values[2] = make_fixnum_or_float (s.st_uid);
968 if (gname)
969 values[3] = DECODE_SYSTEM (build_string (gname));
970 else
971 values[3] = make_fixnum_or_float (s.st_gid);
972
973 values[4] = make_lisp_time (get_stat_atime (&s));
974 values[5] = make_lisp_time (get_stat_mtime (&s));
975 values[6] = make_lisp_time (get_stat_ctime (&s));
976
977 /* If the file size is a 4-byte type, assume that files of sizes in
978 the 2-4 GiB range wrap around to negative values, as this is a
979 common bug on older 32-bit platforms. */
980 if (sizeof (s.st_size) == 4)
981 values[7] = make_fixnum_or_float (s.st_size & 0xffffffffu);
982 else
983 values[7] = make_fixnum_or_float (s.st_size);
984
985 filemodestring (&s, modes);
986 values[8] = make_string (modes, 10);
987 values[9] = Qt;
988 values[10] = INTEGER_TO_CONS (s.st_ino);
989 values[11] = INTEGER_TO_CONS (s.st_dev);
990
991 return Flist (sizeof (values) / sizeof (values[0]), values);
992 }
993
994 DEFUN ("file-attributes-lessp", Ffile_attributes_lessp, Sfile_attributes_lessp, 2, 2, 0,
995 doc: /* Return t if first arg file attributes list is less than second.
996 Comparison is in lexicographic order and case is significant. */)
997 (Lisp_Object f1, Lisp_Object f2)
998 {
999 return Fstring_lessp (Fcar (f1), Fcar (f2));
1000 }
1001 \f
1002
1003 DEFUN ("system-users", Fsystem_users, Ssystem_users, 0, 0, 0,
1004 doc: /* Return a list of user names currently registered in the system.
1005 If we don't know how to determine that on this platform, just
1006 return a list with one element, taken from `user-real-login-name'. */)
1007 (void)
1008 {
1009 Lisp_Object users = Qnil;
1010 #if defined HAVE_GETPWENT && defined HAVE_ENDPWENT
1011 struct passwd *pw;
1012
1013 while ((pw = getpwent ()))
1014 users = Fcons (DECODE_SYSTEM (build_string (pw->pw_name)), users);
1015
1016 endpwent ();
1017 #endif
1018 if (EQ (users, Qnil))
1019 /* At least current user is always known. */
1020 users = Fcons (Vuser_real_login_name, Qnil);
1021 return users;
1022 }
1023
1024 DEFUN ("system-groups", Fsystem_groups, Ssystem_groups, 0, 0, 0,
1025 doc: /* Return a list of user group names currently registered in the system.
1026 The value may be nil if not supported on this platform. */)
1027 (void)
1028 {
1029 Lisp_Object groups = Qnil;
1030 #if defined HAVE_GETGRENT && defined HAVE_ENDGRENT
1031 struct group *gr;
1032
1033 while ((gr = getgrent ()))
1034 groups = Fcons (DECODE_SYSTEM (build_string (gr->gr_name)), groups);
1035
1036 endgrent ();
1037 #endif
1038 return groups;
1039 }
1040
1041 void
1042 syms_of_dired (void)
1043 {
1044 DEFSYM (Qdirectory_files, "directory-files");
1045 DEFSYM (Qdirectory_files_and_attributes, "directory-files-and-attributes");
1046 DEFSYM (Qfile_name_completion, "file-name-completion");
1047 DEFSYM (Qfile_name_all_completions, "file-name-all-completions");
1048 DEFSYM (Qfile_attributes, "file-attributes");
1049 DEFSYM (Qfile_attributes_lessp, "file-attributes-lessp");
1050 DEFSYM (Qdefault_directory, "default-directory");
1051
1052 defsubr (&Sdirectory_files);
1053 defsubr (&Sdirectory_files_and_attributes);
1054 defsubr (&Sfile_name_completion);
1055 defsubr (&Sfile_name_all_completions);
1056 defsubr (&Sfile_attributes);
1057 defsubr (&Sfile_attributes_lessp);
1058 defsubr (&Ssystem_users);
1059 defsubr (&Ssystem_groups);
1060
1061 DEFVAR_LISP ("completion-ignored-extensions", Vcompletion_ignored_extensions,
1062 doc: /* Completion ignores file names ending in any string in this list.
1063 It does not ignore them if all possible completions end in one of
1064 these strings or when displaying a list of completions.
1065 It ignores directory names if they match any string in this list which
1066 ends in a slash. */);
1067 Vcompletion_ignored_extensions = Qnil;
1068 }