mirrored from git://git.sv.gnu.org/emacs.git
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
fileio.c
6686 lines (5835 loc) · 210 KB
/
fileio.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
/* File IO for GNU Emacs.
Copyright (C) 1985-1988, 1993-2023 Free Software Foundation, Inc.
This file is part of GNU Emacs.
GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>. */
#include <config.h>
#include <limits.h>
#include <fcntl.h>
#include "sysstdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef DARWIN_OS
#include <sys/attr.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#include <errno.h>
#ifdef HAVE_LIBSELINUX
#include <selinux/selinux.h>
#include <selinux/context.h>
#endif
#if USE_ACL && defined HAVE_ACL_SET_FILE
#include <sys/acl.h>
#endif
#include <c-ctype.h>
#include "lisp.h"
#include "composite.h"
#include "character.h"
#include "buffer.h"
#include "coding.h"
#include "window.h"
#include "blockinput.h"
#include "region-cache.h"
#include "frame.h"
#ifdef HAVE_LINUX_FS_H
# include <sys/ioctl.h>
# include <linux/fs.h>
#endif
#ifdef WINDOWSNT
#define NOMINMAX 1
#include <windows.h>
/* The redundant #ifdef is to avoid compiler warning about unused macro. */
#ifdef NOMINMAX
#undef NOMINMAX
#endif
#include <sys/file.h>
#include "w32.h"
#endif /* not WINDOWSNT */
#ifdef MSDOS
#include "msdos.h"
#include <sys/param.h>
#endif
#ifdef DOS_NT
/* On Windows, drive letters must be alphabetic - on DOS, the Netware
redirector allows the six letters between 'Z' and 'a' as well. */
#ifdef MSDOS
#define IS_DRIVE(x) ((x) >= 'A' && (x) <= 'z')
#endif
#ifdef WINDOWSNT
#define IS_DRIVE(x) c_isalpha (x)
#endif
/* Need to lower-case the drive letter, or else expanded
filenames will sometimes compare unequal, because
`expand-file-name' doesn't always down-case the drive letter. */
#define DRIVE_LETTER(x) c_tolower (x)
#endif
#include "systime.h"
#include <acl.h>
#include <allocator.h>
#include <careadlinkat.h>
#include <filename.h>
#include <fsusage.h>
#include <stat-time.h>
#include <tempname.h>
#include <binary-io.h>
#ifdef HPUX
#include <netio.h>
#endif
#include "commands.h"
/* True during writing of auto-save files. */
static bool auto_saving;
/* Emacs's real umask. */
static mode_t realmask;
/* Nonzero umask during creation of auto-save directories. */
static mode_t auto_saving_dir_umask;
/* Set by auto_save_1 to mode of original file so Fwrite_region will create
a new file with the same mode as the original. */
static mode_t auto_save_mode_bits;
/* Set by auto_save_1 if an error occurred during the last auto-save. */
static bool auto_save_error_occurred;
/* If VALID_TIMESTAMP_FILE_SYSTEM, then TIMESTAMP_FILE_SYSTEM is the device
number of a file system where time stamps were observed to work. */
static bool valid_timestamp_file_system;
static dev_t timestamp_file_system;
/* Each time an annotation function changes the buffer, the new buffer
is added here. */
static Lisp_Object Vwrite_region_annotation_buffers;
static Lisp_Object emacs_readlinkat (int, char const *);
static Lisp_Object file_name_directory (Lisp_Object);
static bool a_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
Lisp_Object *, struct coding_system *);
static bool e_write (int, Lisp_Object, ptrdiff_t, ptrdiff_t,
struct coding_system *);
/* Test whether FILE is accessible for AMODE.
Return true if successful, false (setting errno) otherwise. */
bool
file_access_p (char const *file, int amode)
{
#ifdef MSDOS
if (amode & W_OK)
{
/* FIXME: The MS-DOS faccessat implementation should handle this. */
struct stat st;
if (stat (file, &st) != 0)
return false;
errno = EPERM;
return st.st_mode & S_IWRITE || S_ISDIR (st.st_mode);
}
#endif
if (faccessat (AT_FDCWD, file, amode, AT_EACCESS) == 0)
return true;
#ifdef CYGWIN
/* Return success if faccessat failed because Cygwin couldn't
determine the file's UID or GID. */
int err = errno;
struct stat st;
if (stat (file, &st) == 0 && (st.st_uid == -1 || st.st_gid == -1))
return true;
errno = err;
#endif
return false;
}
/* Signal a file-access failure. STRING describes the failure,
NAME the file involved, and ERRORNO the errno value.
If NAME is neither null nor a pair, package it up as a singleton
list before reporting it; this saves report_file_errno's caller the
trouble of preserving errno before calling list1. */
Lisp_Object
get_file_errno_data (char const *string, Lisp_Object name, int errorno)
{
Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
char *str = emacs_strerror (errorno);
AUTO_STRING (unibyte_str, str);
Lisp_Object errstring
= code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
Lisp_Object errdata = Fcons (errstring, data);
if (errorno == EEXIST)
return Fcons (Qfile_already_exists, errdata);
else
return Fcons (errorno == ENOENT
? Qfile_missing
: (errorno == EACCES
? Qpermission_denied
: Qfile_error),
Fcons (build_string (string), errdata));
}
void
report_file_errno (char const *string, Lisp_Object name, int errorno)
{
Lisp_Object data = get_file_errno_data (string, name, errorno);
xsignal (Fcar (data), Fcdr (data));
}
/* Signal a file-access failure that set errno. STRING describes the
failure, NAME the file involved. When invoking this function, take
care to not use arguments such as build_string ("foo") that involve
side effects that may set errno. */
void
report_file_error (char const *string, Lisp_Object name)
{
report_file_errno (string, name, errno);
}
#ifdef USE_FILE_NOTIFY
/* Like report_file_error, but reports a file-notify-error instead. */
void
report_file_notify_error (const char *string, Lisp_Object name)
{
char *str = emacs_strerror (errno);
AUTO_STRING (unibyte_str, str);
Lisp_Object errstring
= code_convert_string_norecord (unibyte_str, Vlocale_coding_system, 0);
Lisp_Object data = CONSP (name) || NILP (name) ? name : list1 (name);
Lisp_Object errdata = Fcons (errstring, data);
xsignal (Qfile_notify_error, Fcons (build_string (string), errdata));
}
#endif
/* ACTION failed for FILE with errno ERR. Signal an error if ERR
means the file's metadata could not be retrieved even though it may
exist, otherwise return nil. */
static Lisp_Object
file_metadata_errno (char const *action, Lisp_Object file, int err)
{
if (err == ENOENT || err == ENOTDIR || err == 0)
return Qnil;
report_file_errno (action, file, err);
}
Lisp_Object
file_attribute_errno (Lisp_Object file, int err)
{
return file_metadata_errno ("Getting attributes", file, err);
}
void
close_file_unwind (int fd)
{
emacs_close (fd);
}
void
fclose_unwind (void *arg)
{
FILE *stream = arg;
fclose (stream);
}
/* Restore point, having saved it as a marker. */
void
restore_point_unwind (Lisp_Object location)
{
Fgoto_char (location);
unchain_marker (XMARKER (location));
}
DEFUN ("find-file-name-handler", Ffind_file_name_handler,
Sfind_file_name_handler, 2, 2, 0,
doc: /* Return FILENAME's handler function for OPERATION, if it has one.
Otherwise, return nil.
A file name is handled if one of the regular expressions in
`file-name-handler-alist' matches it.
If OPERATION equals `inhibit-file-name-operation', then ignore
any handlers that are members of `inhibit-file-name-handlers',
but still do run any other handlers. This lets handlers
use the standard functions without calling themselves recursively. */)
(Lisp_Object filename, Lisp_Object operation)
{
/* This function must not munge the match data. */
Lisp_Object chain, inhibited_handlers, result;
ptrdiff_t pos = -1;
result = Qnil;
CHECK_STRING (filename);
if (EQ (operation, Vinhibit_file_name_operation))
inhibited_handlers = Vinhibit_file_name_handlers;
else
inhibited_handlers = Qnil;
for (chain = Vfile_name_handler_alist; CONSP (chain);
chain = XCDR (chain))
{
Lisp_Object elt;
elt = XCAR (chain);
if (CONSP (elt))
{
Lisp_Object string = XCAR (elt);
ptrdiff_t match_pos;
Lisp_Object handler = XCDR (elt);
Lisp_Object operations = Qnil;
if (SYMBOLP (handler))
operations = Fget (handler, Qoperations);
if (STRINGP (string)
&& (match_pos = fast_string_match (string, filename)) > pos
&& (NILP (operations) || ! NILP (Fmemq (operation, operations))))
{
Lisp_Object tem;
handler = XCDR (elt);
tem = Fmemq (handler, inhibited_handlers);
if (NILP (tem))
{
result = handler;
pos = match_pos;
}
}
}
maybe_quit ();
}
return result;
}
DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
1, 1, 0,
doc: /* Return the directory component in file name FILENAME.
Return nil if FILENAME does not include a directory.
Otherwise return a directory name.
Given a Unix syntax file name, returns a string ending in slash. */)
(Lisp_Object filename)
{
Lisp_Object handler;
CHECK_STRING (filename);
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (filename, Qfile_name_directory);
if (!NILP (handler))
{
Lisp_Object handled_name = call2 (handler, Qfile_name_directory,
filename);
return STRINGP (handled_name) ? handled_name : Qnil;
}
return file_name_directory (filename);
}
/* Return the directory component of FILENAME, or nil if FILENAME does
not contain a directory component. */
static Lisp_Object
file_name_directory (Lisp_Object filename)
{
char *beg = SSDATA (filename);
char const *p = beg + SBYTES (filename);
while (p != beg && !IS_DIRECTORY_SEP (p[-1])
#ifdef DOS_NT
/* only recognize drive specifier at the beginning */
&& !(p[-1] == ':'
/* handle the "/:d:foo" and "/:foo" cases correctly */
&& ((p == beg + 2 && !IS_DIRECTORY_SEP (*beg))
|| (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
#endif
) p--;
if (p == beg)
return Qnil;
#ifdef DOS_NT
/* Expansion of "c:" to drive and default directory. */
Lisp_Object tem_fn;
USE_SAFE_ALLOCA;
SAFE_ALLOCA_STRING (beg, filename);
p = beg + (p - SSDATA (filename));
if (p[-1] == ':')
{
/* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir. */
char *res = alloca (MAXPATHLEN + 1);
char *r = res;
if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
{
memcpy (res, beg, 2);
beg += 2;
r += 2;
}
if (getdefdir (c_toupper (*beg) - 'A' + 1, r))
{
size_t l = strlen (res);
if (l > 3 || !IS_DIRECTORY_SEP (res[l - 1]))
strcat (res, "/");
beg = res;
p = beg + strlen (beg);
dostounix_filename (beg);
tem_fn = make_specified_string (beg, -1, p - beg,
STRING_MULTIBYTE (filename));
}
else
tem_fn = make_specified_string (beg - 2, -1, p - beg + 2,
STRING_MULTIBYTE (filename));
}
else if (STRING_MULTIBYTE (filename))
{
tem_fn = make_specified_string (beg, -1, p - beg, 1);
dostounix_filename (SSDATA (tem_fn));
#ifdef WINDOWSNT
if (!NILP (Vw32_downcase_file_names))
tem_fn = Fdowncase (tem_fn);
#endif
}
else
{
dostounix_filename (beg);
tem_fn = make_specified_string (beg, -1, p - beg, 0);
}
SAFE_FREE ();
return tem_fn;
#else /* DOS_NT */
return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
#endif /* DOS_NT */
}
DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
Sfile_name_nondirectory, 1, 1, 0,
doc: /* Return file name FILENAME sans its directory.
For example, in a Unix-syntax file name,
this is everything after the last slash,
or the entire name if it contains no slash. */)
(Lisp_Object filename)
{
register const char *beg, *p, *end;
Lisp_Object handler;
CHECK_STRING (filename);
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
if (!NILP (handler))
{
Lisp_Object handled_name = call2 (handler, Qfile_name_nondirectory,
filename);
if (STRINGP (handled_name))
return handled_name;
error ("Invalid handler in `file-name-handler-alist'");
}
beg = SSDATA (filename);
end = p = beg + SBYTES (filename);
while (p != beg && !IS_DIRECTORY_SEP (p[-1])
#ifdef DOS_NT
/* only recognize drive specifier at beginning */
&& !(p[-1] == ':'
/* handle the "/:d:foo" case correctly */
&& (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
#endif
)
p--;
return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
}
DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
Sunhandled_file_name_directory, 1, 1, 0,
doc: /* Return a directly usable directory name somehow associated with FILENAME.
A `directly usable' directory name is one that may be used without the
intervention of any file name handler.
If FILENAME is a directly usable file itself, return
\(file-name-as-directory FILENAME).
If FILENAME refers to a file which is not accessible from a local process,
then this should return nil.
The `call-process' and `start-process' functions use this function to
get a current directory to run processes in. */)
(Lisp_Object filename)
{
Lisp_Object handler;
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
if (!NILP (handler))
{
Lisp_Object handled_name = call2 (handler, Qunhandled_file_name_directory,
filename);
return STRINGP (handled_name) ? handled_name : Qnil;
}
return Ffile_name_as_directory (filename);
}
/* Maximum number of bytes that DST will be longer than SRC
in file_name_as_directory. This occurs when SRCLEN == 0. */
enum { file_name_as_directory_slop = 2 };
/* Convert from file name SRC of length SRCLEN to directory name in
DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
string. On UNIX, just make sure there is a terminating /. Return
the length of DST in bytes. */
static ptrdiff_t
file_name_as_directory (char *dst, const char *src, ptrdiff_t srclen,
bool multibyte)
{
if (srclen == 0)
{
dst[0] = '.';
dst[1] = '/';
dst[2] = '\0';
return 2;
}
memcpy (dst, src, srclen);
if (!IS_DIRECTORY_SEP (dst[srclen - 1]))
dst[srclen++] = DIRECTORY_SEP;
dst[srclen] = 0;
#ifdef DOS_NT
dostounix_filename (dst);
#endif
return srclen;
}
DEFUN ("file-name-as-directory", Ffile_name_as_directory,
Sfile_name_as_directory, 1, 1, 0,
doc: /* Return a string representing the file name FILE interpreted as a directory.
This operation exists because a directory is also a file, but its name as
a directory is different from its name as a file.
The result can be used as the value of `default-directory'
or passed as second argument to `expand-file-name'.
For a Unix-syntax file name, just appends a slash unless a trailing slash
is already present. */)
(Lisp_Object file)
{
char *buf;
ptrdiff_t length;
Lisp_Object handler, val;
USE_SAFE_ALLOCA;
CHECK_STRING (file);
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
if (!NILP (handler))
{
Lisp_Object handled_name = call2 (handler, Qfile_name_as_directory,
file);
if (STRINGP (handled_name))
return handled_name;
error ("Invalid handler in `file-name-handler-alist'");
}
#ifdef WINDOWSNT
if (!NILP (Vw32_downcase_file_names))
file = Fdowncase (file);
#endif
buf = SAFE_ALLOCA (SBYTES (file) + file_name_as_directory_slop + 1);
length = file_name_as_directory (buf, SSDATA (file), SBYTES (file),
STRING_MULTIBYTE (file));
val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (file));
SAFE_FREE ();
return val;
}
/* Convert from directory name SRC of length SRCLEN to file name in
DST. MULTIBYTE non-zero means the file name in SRC is a multibyte
string. On UNIX, just make sure there isn't a terminating /.
Return the length of DST in bytes. */
static ptrdiff_t
directory_file_name (char *dst, char *src, ptrdiff_t srclen, bool multibyte)
{
/* In Unix-like systems, just remove any final slashes. However, if
they are all slashes, leave "/" and "//" alone, and treat "///"
and longer as if they were "/". */
if (! (srclen == 2 && IS_DIRECTORY_SEP (src[0])))
while (srclen > 1
#ifdef DOS_NT
&& !(srclen > 2 && IS_DEVICE_SEP (src[srclen - 2]))
#endif
&& IS_DIRECTORY_SEP (src[srclen - 1]))
srclen--;
memcpy (dst, src, srclen);
dst[srclen] = 0;
#ifdef DOS_NT
dostounix_filename (dst);
#endif
return srclen;
}
DEFUN ("directory-name-p", Fdirectory_name_p, Sdirectory_name_p, 1, 1, 0,
doc: /* Return non-nil if NAME ends with a directory separator character. */)
(Lisp_Object name)
{
CHECK_STRING (name);
ptrdiff_t namelen = SBYTES (name);
unsigned char c = namelen ? SREF (name, namelen - 1) : 0;
return IS_DIRECTORY_SEP (c) ? Qt : Qnil;
}
/* Return the expansion of NEWNAME, except that if NEWNAME is a
directory name then return the expansion of FILE's basename under
NEWNAME. This resembles how 'cp FILE NEWNAME' works, except that
it requires NEWNAME to be a directory name (typically, by ending in
"/"). */
static Lisp_Object
expand_cp_target (Lisp_Object file, Lisp_Object newname)
{
return (!NILP (Fdirectory_name_p (newname))
? Fexpand_file_name (Ffile_name_nondirectory (file), newname)
: Fexpand_file_name (newname, Qnil));
}
DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
1, 1, 0,
doc: /* Returns the file name of the directory named DIRECTORY.
This is the name of the file that holds the data for the directory DIRECTORY.
This operation exists because a directory is also a file, but its name as
a directory is different from its name as a file.
In Unix-syntax, this function just removes the final slash. */)
(Lisp_Object directory)
{
char *buf;
ptrdiff_t length;
Lisp_Object handler, val;
USE_SAFE_ALLOCA;
CHECK_STRING (directory);
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
if (!NILP (handler))
{
Lisp_Object handled_name = call2 (handler, Qdirectory_file_name,
directory);
if (STRINGP (handled_name))
return handled_name;
error ("Invalid handler in `file-name-handler-alist'");
}
#ifdef WINDOWSNT
if (!NILP (Vw32_downcase_file_names))
directory = Fdowncase (directory);
#endif
buf = SAFE_ALLOCA (SBYTES (directory) + 1);
length = directory_file_name (buf, SSDATA (directory), SBYTES (directory),
STRING_MULTIBYTE (directory));
val = make_specified_string (buf, -1, length, STRING_MULTIBYTE (directory));
SAFE_FREE ();
return val;
}
DEFUN ("make-temp-file-internal", Fmake_temp_file_internal,
Smake_temp_file_internal, 4, 4, 0,
doc: /* Generate a new file whose name starts with PREFIX, a string.
Return the name of the generated file. If DIR-FLAG is zero, do not
create the file, just its name. Otherwise, if DIR-FLAG is non-nil,
create an empty directory. The file name should end in SUFFIX.
Do not expand PREFIX; a non-absolute PREFIX is relative to the Emacs
working directory. If TEXT is a string, insert it into the newly
created file.
Signal an error if the file could not be created.
This function does not grok magic file names. */)
(Lisp_Object prefix, Lisp_Object dir_flag, Lisp_Object suffix,
Lisp_Object text)
{
CHECK_STRING (prefix);
CHECK_STRING (suffix);
Lisp_Object encoded_prefix = ENCODE_FILE (prefix);
Lisp_Object encoded_suffix = ENCODE_FILE (suffix);
ptrdiff_t prefix_len = SBYTES (encoded_prefix);
ptrdiff_t suffix_len = SBYTES (encoded_suffix);
if (INT_MAX < suffix_len)
args_out_of_range (prefix, suffix);
int nX = 6;
Lisp_Object val = make_uninit_string (prefix_len + nX + suffix_len);
char *data = SSDATA (val);
memcpy (data, SSDATA (encoded_prefix), prefix_len);
memset (data + prefix_len, 'X', nX);
memcpy (data + prefix_len + nX, SSDATA (encoded_suffix), suffix_len);
int kind = (NILP (dir_flag) ? GT_FILE
: BASE_EQ (dir_flag, make_fixnum (0)) ? GT_NOCREATE
: GT_DIR);
int fd = gen_tempname (data, suffix_len, O_BINARY | O_CLOEXEC, kind);
bool failed = fd < 0;
if (!failed)
{
specpdl_ref count = SPECPDL_INDEX ();
record_unwind_protect_int (close_file_unwind, fd);
val = DECODE_FILE (val);
if (STRINGP (text) && SBYTES (text) != 0)
write_region (text, Qnil, val, Qnil, Qnil, Qnil, Qnil, fd);
failed = NILP (dir_flag) && emacs_close (fd) != 0;
/* Discard the unwind protect. */
specpdl_ptr = specpdl_ref_to_ptr (count);
}
if (failed)
{
static char const kind_message[][32] =
{
[GT_FILE] = "Creating file with prefix",
[GT_DIR] = "Creating directory with prefix",
[GT_NOCREATE] = "Creating file name with prefix"
};
report_file_error (kind_message[kind], prefix);
}
return val;
}
DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
doc: /* Generate temporary file name (string) starting with PREFIX (a string).
This function tries to choose a name that has no existing file.
For this to work, PREFIX should be an absolute file name, and PREFIX
and the returned string should both be non-magic.
There is a race condition between calling `make-temp-name' and
later creating the file, which opens all kinds of security holes.
For that reason, you should normally use `make-temp-file' instead. */)
(Lisp_Object prefix)
{
return Fmake_temp_file_internal (prefix, make_fixnum (0),
empty_unibyte_string, Qnil);
}
DEFUN ("file-name-concat", Ffile_name_concat, Sfile_name_concat, 1, MANY, 0,
doc: /* Append COMPONENTS to DIRECTORY and return the resulting string.
Elements in COMPONENTS must be a string or nil.
DIRECTORY or the non-final elements in COMPONENTS may or may not end
with a slash -- if they don't end with a slash, a slash will be
inserted before contatenating.
usage: (record DIRECTORY &rest COMPONENTS) */)
(ptrdiff_t nargs, Lisp_Object *args)
{
ptrdiff_t chars = 0, bytes = 0, multibytes = 0, eargs = 0;
Lisp_Object *elements = args;
Lisp_Object result;
ptrdiff_t i;
/* First go through the list to check the types and see whether
they're all of the same multibytedness. */
for (i = 0; i < nargs; i++)
{
Lisp_Object arg = args[i];
/* Skip empty and nil elements. */
if (NILP (arg))
continue;
CHECK_STRING (arg);
if (SCHARS (arg) == 0)
continue;
eargs++;
/* Multibyte and non-ASCII. */
if (STRING_MULTIBYTE (arg) && SCHARS (arg) != SBYTES (arg))
multibytes++;
/* We're not adding a slash to the final part. */
if (i == nargs - 1
|| IS_DIRECTORY_SEP (*(SSDATA (arg) + SBYTES (arg) - 1)))
{
bytes += SBYTES (arg);
chars += SCHARS (arg);
}
else
{
bytes += SBYTES (arg) + 1;
chars += SCHARS (arg) + 1;
}
}
/* Convert if needed. */
if ((multibytes != 0 && multibytes != nargs)
|| eargs != nargs)
{
int j = 0;
elements = xmalloc (eargs * sizeof *elements);
bytes = 0;
chars = 0;
/* Filter out nil/"". */
for (i = 0; i < nargs; i++)
{
Lisp_Object arg = args[i];
if (!NILP (arg) && SCHARS (arg) != 0)
elements[j++] = arg;
}
for (i = 0; i < eargs; i++)
{
Lisp_Object arg = elements[i];
/* Use multibyte or all-ASCII strings as is. */
if (!STRING_MULTIBYTE (arg) && !string_ascii_p (arg))
elements[i] = Fstring_to_multibyte (arg);
arg = elements[i];
/* We have to recompute the number of bytes. */
if (i == eargs - 1
|| IS_DIRECTORY_SEP (*(SSDATA (arg) + SBYTES (arg) - 1)))
{
bytes += SBYTES (arg);
chars += SCHARS (arg);
}
else
{
bytes += SBYTES (arg) + 1;
chars += SCHARS (arg) + 1;
}
}
}
/* Allocate an empty string. */
if (multibytes == 0)
result = make_uninit_string (chars);
else
result = make_uninit_multibyte_string (chars, bytes);
/* Null-terminate the string. */
*(SSDATA (result) + SBYTES (result)) = 0;
/* Copy over the data. */
char *p = SSDATA (result);
for (i = 0; i < eargs; i++)
{
Lisp_Object arg = elements[i];
memcpy (p, SSDATA (arg), SBYTES (arg));
p += SBYTES (arg);
/* The last element shouldn't have a slash added at the end. */
if (i < eargs - 1 && !IS_DIRECTORY_SEP (*(p - 1)))
*p++ = DIRECTORY_SEP;
}
if (elements != args)
xfree (elements);
return result;
}
/* NAME must be a string. */
static bool
file_name_absolute_no_tilde_p (Lisp_Object name)
{
return IS_ABSOLUTE_FILE_NAME (SSDATA (name));
}
/* Return the home directory of the user NAME, or a null pointer if
NAME is empty or the user does not exist or the user's home
directory is not an absolute file name. NAME is an array of bytes
that continues up to (but not including) the next NUL byte or
directory separator. The returned string lives in storage good
until the next call to this or similar functions. */
static char *
user_homedir (char const *name)
{
ptrdiff_t length;
for (length = 0; name[length] && !IS_DIRECTORY_SEP (name[length]); length++)
continue;
if (length == 0)
return NULL;
USE_SAFE_ALLOCA;
char *p = SAFE_ALLOCA (length + 1);
memcpy (p, name, length);
p[length] = 0;
struct passwd *pw = getpwnam (p);
SAFE_FREE ();
if (!pw || (pw->pw_dir && !IS_ABSOLUTE_FILE_NAME (pw->pw_dir)))
return NULL;
return pw->pw_dir;
}
DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
doc: /* Convert filename NAME to absolute, and canonicalize it.
Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
\(does not start with slash or tilde); both the directory name and
a directory's file name are accepted. If DEFAULT-DIRECTORY is nil or
missing, the current buffer's value of `default-directory' is used.
NAME should be a string that is a valid file name for the underlying
filesystem.
File name components that are `.' are removed, and so are file name
components followed by `..', along with the `..' itself; note that
these simplifications are done without checking the resulting file
names in the file system.
Multiple consecutive slashes are collapsed into a single slash, except
at the beginning of the file name when they are significant (e.g., UNC
file names on MS-Windows.)
An initial \"~\" in NAME expands to your home directory.
An initial \"~USER\" in NAME expands to USER's home directory. If
USER doesn't exist, \"~USER\" is not expanded.
To do other file name substitutions, see `substitute-in-file-name'.
For technical reasons, this function can return correct but
non-intuitive results for the root directory; for instance,
\(expand-file-name ".." "/") returns "/..". For this reason, use
\(directory-file-name (file-name-directory dirname)) to traverse a
filesystem tree, not (expand-file-name ".." dirname). Note: make
sure DIRNAME in this example doesn't end in a slash, unless it's
the root directory. */)
(Lisp_Object name, Lisp_Object default_directory)
{
/* These point to SDATA and need to be careful with string-relocation
during GC (via DECODE_FILE). */
char *nm;
char *nmlim;
const char *newdir;
const char *newdirlim;
/* This should only point to alloca'd data. */
char *target;
ptrdiff_t tlen;
#ifdef DOS_NT
int drive = 0;
bool collapse_newdir = true;
bool is_escaped = 0;
#endif /* DOS_NT */
ptrdiff_t length, nbytes;
Lisp_Object handler, result, handled_name;
bool multibyte;
Lisp_Object hdir;
USE_SAFE_ALLOCA;
CHECK_STRING (name);
CHECK_STRING_NULL_BYTES (name);
/* If the file name has special constructs in it,
call the corresponding file name handler. */
handler = Ffind_file_name_handler (name, Qexpand_file_name);
if (!NILP (handler))
{
handled_name = call3 (handler, Qexpand_file_name,
name, default_directory);
if (STRINGP (handled_name))
return handled_name;
error ("Invalid handler in `file-name-handler-alist'");
}
/* As a last resort, we may have to use the root as
default_directory below. */
Lisp_Object root;
#ifdef DOS_NT
/* "/" is not considered a root directory on DOS_NT, so using it
as default_directory causes an infinite recursion in, e.g.,
the following:
(let (default-directory)
(expand-file-name "a"))
To avoid this, we use the root of the current drive. */
root = build_string (emacs_root_dir ());
#else
root = build_string ("/");
#endif
/* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted. */
if (NILP (default_directory))
{
Lisp_Object dir = BVAR (current_buffer, directory);
/* The buffer's default-directory should be absolute or should
start with `~'. If it isn't absolute, we replace it by its
expansion relative to a known absolute name ABSDIR, which is
the invocation-directory if the latter is absolute, or the
root otherwise.
In case default-directory starts with `~' or `~user', where
USER is a valid user name, this correctly expands it (and
ABSDIR plays no role). If USER is not a valid user name, the
leading `~' loses its special meaning and is retained as part
of the expanded name. */
if (STRINGP (dir))
{