fileio.c 176 KB
Newer Older
Jim Blandy's avatar
Jim Blandy committed
1
/* File IO for GNU Emacs.
Glenn Morris's avatar
Glenn Morris committed
2

3
Copyright (C) 1985-1988, 1993-2011  Free Software Foundation, Inc.
Jim Blandy's avatar
Jim Blandy committed
4 5 6

This file is part of GNU Emacs.

7
GNU Emacs is free software: you can redistribute it and/or modify
Jim Blandy's avatar
Jim Blandy committed
8
it under the terms of the GNU General Public License as published by
9 10
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jim Blandy's avatar
Jim Blandy committed
11 12 13 14 15 16 17

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
18
along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.  */
Jim Blandy's avatar
Jim Blandy committed
19

20
#include <config.h>
21
#include <limits.h>
22
#include <fcntl.h>
23
#include <stdio.h>
Jim Blandy's avatar
Jim Blandy committed
24 25
#include <sys/types.h>
#include <sys/stat.h>
26
#include <setjmp.h>
27 28
#include <unistd.h>

29 30 31 32
#if !defined (S_ISLNK) && defined (S_IFLNK)
#  define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
#endif

33 34 35 36
#if !defined (S_ISFIFO) && defined (S_IFIFO)
#  define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO)
#endif

37 38 39 40
#if !defined (S_ISREG) && defined (S_IFREG)
#  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
#endif

41
#ifdef HAVE_PWD_H
Jim Blandy's avatar
Jim Blandy committed
42
#include <pwd.h>
Jim Blandy's avatar
Jim Blandy committed
43 44
#endif

Jim Blandy's avatar
Jim Blandy committed
45 46 47
#include <ctype.h>
#include <errno.h>

Karel Klíc's avatar
Karel Klíc committed
48 49 50 51 52
#ifdef HAVE_LIBSELINUX
#include <selinux/selinux.h>
#include <selinux/context.h>
#endif

Jim Blandy's avatar
Jim Blandy committed
53
#include "lisp.h"
54
#include "intervals.h"
Jim Blandy's avatar
Jim Blandy committed
55
#include "buffer.h"
56
#include "character.h"
Karl Heuer's avatar
Karl Heuer committed
57
#include "coding.h"
Jim Blandy's avatar
Jim Blandy committed
58
#include "window.h"
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
59
#include "blockinput.h"
Karoly Lorentey's avatar
Karoly Lorentey committed
60 61
#include "frame.h"
#include "dispextern.h"
Jim Blandy's avatar
Jim Blandy committed
62

63 64 65 66 67 68
#ifdef WINDOWSNT
#define NOMINMAX 1
#include <windows.h>
#include <fcntl.h>
#endif /* not WINDOWSNT */

Eli Zaretskii's avatar
Eli Zaretskii committed
69 70 71 72 73 74
#ifdef MSDOS
#include "msdos.h"
#include <sys/param.h>
#include <fcntl.h>
#endif

75 76 77 78 79 80 81 82 83
#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) isalpha (x)
#endif
84 85 86 87
/* Need to lower-case the drive letter, or else expanded
   filenames will sometimes compare inequal, because
   `expand-file-name' doesn't always down-case the drive letter.  */
#define DRIVE_LETTER(x) (tolower (x))
88 89
#endif

Jim Blandy's avatar
Jim Blandy committed
90
#include "systime.h"
Jim Blandy's avatar
Jim Blandy committed
91 92 93

#ifdef HPUX
#include <netio.h>
94
#endif
Jim Blandy's avatar
Jim Blandy committed
95

96 97
#include "commands.h"

98 99 100 101
#ifndef S_ISLNK
#  define lstat stat
#endif

102 103 104 105
#ifndef FILE_SYSTEM_CASE
#define FILE_SYSTEM_CASE(filename)  (filename)
#endif

Jim Blandy's avatar
Jim Blandy committed
106 107 108 109 110 111 112
/* Nonzero during writing of auto-save files */
int auto_saving;

/* 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 */
int auto_save_mode_bits;

113 114 115
/* Set by auto_save_1 if an error occurred during the last auto-save. */
int auto_save_error_occurred;

116 117 118 119 120 121 122
/* The symbol bound to coding-system-for-read when
   insert-file-contents is called for recovering a file.  This is not
   an actual coding system name, but just an indicator to tell
   insert-file-contents to use `emacs-mule' with a special flag for
   auto saving and recovering a file.  */
Lisp_Object Qauto_save_coding;

123 124 125 126
/* Property name of a file name handler,
   which gives a list of operations it handles..  */
Lisp_Object Qoperations;

127 128 129
/* Lisp functions for translating file formats */
Lisp_Object Qformat_decode, Qformat_annotate_function;

130
/* Lisp function for setting buffer-file-coding-system and the
131
   multibyteness of the current buffer after inserting a file.  */
132
Lisp_Object Qafter_insert_file_set_coding;
133

134
Lisp_Object Qwrite_region_annotate_functions;
135 136 137 138
/* Each time an annotation function changes the buffer, the new buffer
   is added here.  */
Lisp_Object Vwrite_region_annotation_buffers;

139 140 141
#ifdef HAVE_FSYNC
#endif

142 143
Lisp_Object Qdelete_by_moving_to_trash;

144 145 146
/* Lisp function for moving files to trash.  */
Lisp_Object Qmove_file_to_trash;

147 148 149 150 151 152
/* Lisp function for recursively copying directories.  */
Lisp_Object Qcopy_directory;

/* Lisp function for recursively deleting directories.  */
Lisp_Object Qdelete_directory;

153 154 155
#ifdef WINDOWSNT
#endif

156
Lisp_Object Qfile_error, Qfile_already_exists, Qfile_date_error;
Richard M. Stallman's avatar
Richard M. Stallman committed
157
Lisp_Object Qexcl;
158 159
Lisp_Object Qfile_name_history;

160 161
Lisp_Object Qcar_less_than_car;

162 163 164
static int a_write (int, Lisp_Object, int, int,
                    Lisp_Object *, struct coding_system *);
static int e_write (int, Lisp_Object, int, int, struct coding_system *);
165

166

167
void
168
report_file_error (const char *string, Lisp_Object data)
Jim Blandy's avatar
Jim Blandy committed
169 170
{
  Lisp_Object errstring;
Richard M. Stallman's avatar
Richard M. Stallman committed
171
  int errorno = errno;
172
  char *str;
Jim Blandy's avatar
Jim Blandy committed
173

174
  synchronize_system_messages_locale ();
175 176 177
  str = strerror (errorno);
  errstring = code_convert_string_norecord (make_unibyte_string (str,
								 strlen (str)),
178 179
					    Vlocale_coding_system, 0);

Jim Blandy's avatar
Jim Blandy committed
180
  while (1)
Richard M. Stallman's avatar
Richard M. Stallman committed
181 182 183
    switch (errorno)
      {
      case EEXIST:
184
	xsignal (Qfile_already_exists, Fcons (errstring, data));
Richard M. Stallman's avatar
Richard M. Stallman committed
185 186 187
	break;
      default:
	/* System error messages are capitalized.  Downcase the initial
188 189
	   unless it is followed by a slash.  (The slash case caters to
	   error messages that begin with "I/O" or, in German, "E/A".)  */
190 191
	if (STRING_MULTIBYTE (errstring)
	    && ! EQ (Faref (errstring, make_number (1)), make_number ('/')))
192 193 194
	  {
	    int c;

195
	    str = SSDATA (errstring);
196
	    c = STRING_CHAR (str);
Stefan Monnier's avatar
Stefan Monnier committed
197
	    Faset (errstring, make_number (0), make_number (DOWNCASE (c)));
198
	  }
Richard M. Stallman's avatar
Richard M. Stallman committed
199

200
	xsignal (Qfile_error,
Richard M. Stallman's avatar
Richard M. Stallman committed
201 202
		 Fcons (build_string (string), Fcons (errstring, data)));
      }
Jim Blandy's avatar
Jim Blandy committed
203
}
204

205
Lisp_Object
206
close_file_unwind (Lisp_Object fd)
207
{
208
  emacs_close (XFASTINT (fd));
209
  return Qnil;
210
}
211 212 213

/* Restore point, having saved it as a marker.  */

Andreas Schwab's avatar
Andreas Schwab committed
214
Lisp_Object
215
restore_point_unwind (Lisp_Object location)
216
{
217
  Fgoto_char (location);
218
  Fset_marker (location, Qnil, Qnil);
219
  return Qnil;
220
}
221

Jim Blandy's avatar
Jim Blandy committed
222

223
Lisp_Object Qexpand_file_name;
224
Lisp_Object Qsubstitute_in_file_name;
225 226 227
Lisp_Object Qdirectory_file_name;
Lisp_Object Qfile_name_directory;
Lisp_Object Qfile_name_nondirectory;
228
Lisp_Object Qunhandled_file_name_directory;
229
Lisp_Object Qfile_name_as_directory;
230
Lisp_Object Qcopy_file;
231
Lisp_Object Qmake_directory_internal;
232
Lisp_Object Qmake_directory;
233
Lisp_Object Qdelete_directory_internal;
234 235 236 237 238 239 240 241
Lisp_Object Qdelete_file;
Lisp_Object Qrename_file;
Lisp_Object Qadd_name_to_file;
Lisp_Object Qmake_symbolic_link;
Lisp_Object Qfile_exists_p;
Lisp_Object Qfile_executable_p;
Lisp_Object Qfile_readable_p;
Lisp_Object Qfile_writable_p;
242 243
Lisp_Object Qfile_symlink_p;
Lisp_Object Qaccess_file;
244
Lisp_Object Qfile_directory_p;
245
Lisp_Object Qfile_regular_p;
246 247 248
Lisp_Object Qfile_accessible_directory_p;
Lisp_Object Qfile_modes;
Lisp_Object Qset_file_modes;
249
Lisp_Object Qset_file_times;
Karel Klíc's avatar
Karel Klíc committed
250 251
Lisp_Object Qfile_selinux_context;
Lisp_Object Qset_file_selinux_context;
252 253 254 255
Lisp_Object Qfile_newer_than_file_p;
Lisp_Object Qinsert_file_contents;
Lisp_Object Qwrite_region;
Lisp_Object Qverify_visited_file_modtime;
256
Lisp_Object Qset_visited_file_modtime;
257

258
DEFUN ("find-file-name-handler", Ffind_file_name_handler, Sfind_file_name_handler, 2, 2, 0,
259 260 261 262 263 264 265 266 267
       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 we ignore
any handlers that are members of `inhibit-file-name-handlers',
but we still do run any other handlers.  This lets handlers
use the standard functions without calling themselves recursively.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
268
  (Lisp_Object filename, Lisp_Object operation)
269
{
270
  /* This function must not munge the match data.  */
271
  Lisp_Object chain, inhibited_handlers, result;
272
  int pos = -1;
273

274
  result = Qnil;
275
  CHECK_STRING (filename);
276

277 278 279 280
  if (EQ (operation, Vinhibit_file_name_operation))
    inhibited_handlers = Vinhibit_file_name_handlers;
  else
    inhibited_handlers = Qnil;
281

282
  for (chain = Vfile_name_handler_alist; CONSP (chain);
283
       chain = XCDR (chain))
284 285
    {
      Lisp_Object elt;
286
      elt = XCAR (chain);
287
      if (CONSP (elt))
288
	{
289
	  Lisp_Object string = XCAR (elt);
290
	  int match_pos;
291
	  Lisp_Object handler = XCDR (elt);
292 293 294 295
	  Lisp_Object operations = Qnil;

	  if (SYMBOLP (handler))
	    operations = Fget (handler, Qoperations);
296

297
	  if (STRINGP (string)
298 299
	      && (match_pos = fast_string_match (string, filename)) > pos
	      && (NILP (operations) || ! NILP (Fmemq (operation, operations))))
300
	    {
301
	      Lisp_Object tem;
302

303
	      handler = XCDR (elt);
304 305
	      tem = Fmemq (handler, inhibited_handlers);
	      if (NILP (tem))
306 307 308 309
		{
		  result = handler;
		  pos = match_pos;
		}
310
	    }
311
	}
312 313

      QUIT;
314
    }
315
  return result;
316 317
}

Jim Blandy's avatar
Jim Blandy committed
318
DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory,
319 320 321
       1, 1, 0,
       doc: /* Return the directory component in file name FILENAME.
Return nil if FILENAME does not include a directory.
322
Otherwise return a directory name.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
323
Given a Unix syntax file name, returns a string ending in slash.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
324
  (Lisp_Object filename)
Jim Blandy's avatar
Jim Blandy committed
325
{
326
#ifndef DOS_NT
327
  register const unsigned char *beg;
328 329 330
#else
  register unsigned char *beg;
#endif
331
  register const unsigned char *p;
332
  Lisp_Object handler;
Jim Blandy's avatar
Jim Blandy committed
333

334
  CHECK_STRING (filename);
Jim Blandy's avatar
Jim Blandy committed
335

336 337
  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
338
  handler = Ffind_file_name_handler (filename, Qfile_name_directory);
339
  if (!NILP (handler))
340
    return call2 (handler, Qfile_name_directory, filename);
341

342
  filename = FILE_SYSTEM_CASE (filename);
343
#ifdef DOS_NT
344
  beg = (unsigned char *) alloca (SBYTES (filename) + 1);
345
  memcpy (beg, SDATA (filename), SBYTES (filename) + 1);
346 347
#else
  beg = SDATA (filename);
348
#endif
349
  p = beg + SBYTES (filename);
Jim Blandy's avatar
Jim Blandy committed
350

351 352
  while (p != beg && !IS_DIRECTORY_SEP (p[-1])
#ifdef DOS_NT
353 354 355 356 357
	 /* only recognise 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))))
358
#endif
Jim Blandy's avatar
Jim Blandy committed
359 360 361 362
	 ) p--;

  if (p == beg)
    return Qnil;
363
#ifdef DOS_NT
364
  /* Expansion of "c:" to drive and default directory.  */
365
  if (p[-1] == ':')
366 367
    {
      /* MAXPATHLEN+1 is guaranteed to be enough space for getdefdir.  */
368
      unsigned char *res = alloca (MAXPATHLEN + 1);
369 370 371 372 373 374 375 376 377 378
      unsigned char *r = res;

      if (p == beg + 4 && IS_DIRECTORY_SEP (*beg) && beg[1] == ':')
	{
	  strncpy (res, beg, 2);
	  beg += 2;
	  r += 2;
	}

      if (getdefdir (toupper (*beg) - 'A' + 1, r))
379
	{
380
	  if (!IS_DIRECTORY_SEP (res[strlen (res) - 1]))
381 382 383 384 385
	    strcat (res, "/");
	  beg = res;
	  p = beg + strlen (beg);
	}
    }
386
  dostounix_filename (beg);
387
#endif /* DOS_NT */
388

389
  return make_specified_string (beg, -1, p - beg, STRING_MULTIBYTE (filename));
Jim Blandy's avatar
Jim Blandy committed
390 391
}

392 393
DEFUN ("file-name-nondirectory", Ffile_name_nondirectory,
       Sfile_name_nondirectory, 1, 1, 0,
394 395 396 397
       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.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
398
  (Lisp_Object filename)
Jim Blandy's avatar
Jim Blandy committed
399
{
400
  register const unsigned char *beg, *p, *end;
401
  Lisp_Object handler;
Jim Blandy's avatar
Jim Blandy committed
402

403
  CHECK_STRING (filename);
Jim Blandy's avatar
Jim Blandy committed
404

405 406
  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
407
  handler = Ffind_file_name_handler (filename, Qfile_name_nondirectory);
408
  if (!NILP (handler))
409
    return call2 (handler, Qfile_name_nondirectory, filename);
410

411 412
  beg = SDATA (filename);
  end = p = beg + SBYTES (filename);
Jim Blandy's avatar
Jim Blandy committed
413

414 415 416
  while (p != beg && !IS_DIRECTORY_SEP (p[-1])
#ifdef DOS_NT
	 /* only recognise drive specifier at beginning */
417 418 419
	 && !(p[-1] == ':'
	      /* handle the "/:d:foo" case correctly  */
	      && (p == beg + 2 || (p == beg + 4 && IS_DIRECTORY_SEP (*beg))))
420
#endif
421 422
	 )
    p--;
Jim Blandy's avatar
Jim Blandy committed
423

424
  return make_specified_string (p, -1, end - p, STRING_MULTIBYTE (filename));
Jim Blandy's avatar
Jim Blandy committed
425
}
426

427 428
DEFUN ("unhandled-file-name-directory", Funhandled_file_name_directory,
       Sunhandled_file_name_directory, 1, 1, 0,
429 430 431 432 433
       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 handler.
If FILENAME is a directly usable file itself, return
\(file-name-directory FILENAME).
Stefan Monnier's avatar
Stefan Monnier committed
434 435
If FILENAME refers to a file which is not accessible from a local process,
then this should return nil.
436 437
The `call-process' and `start-process' functions use this function to
get a current directory to run processes in.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
438
  (Lisp_Object filename)
439 440 441 442 443
{
  Lisp_Object handler;

  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
444
  handler = Ffind_file_name_handler (filename, Qunhandled_file_name_directory);
445 446 447 448 449 450
  if (!NILP (handler))
    return call2 (handler, Qunhandled_file_name_directory, filename);

  return Ffile_name_directory (filename);
}

Jim Blandy's avatar
Jim Blandy committed
451 452

char *
453
file_name_as_directory (char *out, char *in)
Jim Blandy's avatar
Jim Blandy committed
454 455 456 457 458
{
  int size = strlen (in) - 1;

  strcpy (out, in);

459 460
  if (size < 0)
    {
461 462 463
      out[0] = '.';
      out[1] = '/';
      out[2] = 0;
464 465 466
      return out;
    }

Jim Blandy's avatar
Jim Blandy committed
467
  /* For Unix syntax, Append a slash if necessary */
468
  if (!IS_DIRECTORY_SEP (out[size]))
469
    {
470
      out[size + 1] = DIRECTORY_SEP;
471 472
      out[size + 2] = '\0';
    }
473
#ifdef DOS_NT
474
  dostounix_filename (out);
475
#endif
Jim Blandy's avatar
Jim Blandy committed
476 477 478 479 480
  return out;
}

DEFUN ("file-name-as-directory", Ffile_name_as_directory,
       Sfile_name_as_directory, 1, 1, 0,
481
       doc: /* Return a string representing the file name FILE interpreted as a directory.
482 483 484 485
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'.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
486
For a Unix-syntax file name, just appends a slash.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
487
  (Lisp_Object file)
Jim Blandy's avatar
Jim Blandy committed
488 489
{
  char *buf;
490
  Lisp_Object handler;
Jim Blandy's avatar
Jim Blandy committed
491

492
  CHECK_STRING (file);
Jim Blandy's avatar
Jim Blandy committed
493
  if (NILP (file))
Jim Blandy's avatar
Jim Blandy committed
494
    return Qnil;
495 496 497

  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
498
  handler = Ffind_file_name_handler (file, Qfile_name_as_directory);
499 500 501
  if (!NILP (handler))
    return call2 (handler, Qfile_name_as_directory, file);

502
  buf = (char *) alloca (SBYTES (file) + 10);
503
  file_name_as_directory (buf, SSDATA (file));
504 505
  return make_specified_string (buf, -1, strlen (buf),
				STRING_MULTIBYTE (file));
Jim Blandy's avatar
Jim Blandy committed
506 507 508 509
}

/*
 * Convert from directory name to filename.
510
 * On UNIX, it's simple: just make sure there isn't a terminating /
Jim Blandy's avatar
Jim Blandy committed
511 512 513 514

 * Value is nonzero if the string output is different from the input.
 */

Andreas Schwab's avatar
Andreas Schwab committed
515
int
516
directory_file_name (char *src, char *dst)
Jim Blandy's avatar
Jim Blandy committed
517 518 519 520
{
  long slen;

  slen = strlen (src);
Dan Nicolaescu's avatar
Dan Nicolaescu committed
521

Jim Blandy's avatar
Jim Blandy committed
522 523 524
  /* Process as Unix format: just remove any final slash.
     But leave "/" unchanged; do not change it to "".  */
  strcpy (dst, src);
525
  if (slen > 1
526
      && IS_DIRECTORY_SEP (dst[slen - 1])
527 528 529 530
#ifdef DOS_NT
      && !IS_ANY_SEP (dst[slen - 2])
#endif
      )
Jim Blandy's avatar
Jim Blandy committed
531
    dst[slen - 1] = 0;
532
#ifdef DOS_NT
533
  dostounix_filename (dst);
534
#endif
Jim Blandy's avatar
Jim Blandy committed
535 536 537 538
  return 1;
}

DEFUN ("directory-file-name", Fdirectory_file_name, Sdirectory_file_name,
539 540 541 542 543
       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.
Dan Nicolaescu's avatar
Dan Nicolaescu committed
544
In Unix-syntax, this function just removes the final slash.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
545
  (Lisp_Object directory)
Jim Blandy's avatar
Jim Blandy committed
546 547
{
  char *buf;
548
  Lisp_Object handler;
Jim Blandy's avatar
Jim Blandy committed
549

550
  CHECK_STRING (directory);
Jim Blandy's avatar
Jim Blandy committed
551

Jim Blandy's avatar
Jim Blandy committed
552
  if (NILP (directory))
Jim Blandy's avatar
Jim Blandy committed
553
    return Qnil;
554 555 556

  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
557
  handler = Ffind_file_name_handler (directory, Qdirectory_file_name);
558 559 560
  if (!NILP (handler))
    return call2 (handler, Qdirectory_file_name, directory);

561
  buf = (char *) alloca (SBYTES (directory) + 20);
562
  directory_file_name (SSDATA (directory), buf);
563 564
  return make_specified_string (buf, -1, strlen (buf),
				STRING_MULTIBYTE (directory));
Jim Blandy's avatar
Jim Blandy committed
565 566
}

567
static const char make_temp_name_tbl[64] =
568 569 570 571 572 573 574 575 576 577
{
  'A','B','C','D','E','F','G','H',
  'I','J','K','L','M','N','O','P',
  'Q','R','S','T','U','V','W','X',
  'Y','Z','a','b','c','d','e','f',
  'g','h','i','j','k','l','m','n',
  'o','p','q','r','s','t','u','v',
  'w','x','y','z','0','1','2','3',
  '4','5','6','7','8','9','-','_'
};
578

579 580
static unsigned make_temp_name_count, make_temp_name_count_initialized_p;

581
/* Value is a temporary file name starting with PREFIX, a string.
582

583 584 585 586 587
   The Emacs process number forms part of the result, so there is
   no danger of generating a name being used by another process.
   In addition, this function makes an attempt to choose a name
   which has no existing file.  To make this work, PREFIX should be
   an absolute file name.
588

589 590 591 592 593 594 595 596 597
   BASE64_P non-zero means add the pid as 3 characters in base64
   encoding.  In this case, 6 characters will be added to PREFIX to
   form the file name.  Otherwise, if Emacs is running on a system
   with long file names, add the pid as a decimal number.

   This function signals an error if no unique file name could be
   generated.  */

Lisp_Object
598
make_temp_name (Lisp_Object prefix, int base64_p)
Jim Blandy's avatar
Jim Blandy committed
599 600
{
  Lisp_Object val;
601
  int len, clen;
602 603 604 605
  int pid;
  unsigned char *p, *data;
  char pidbuf[20];
  int pidlen;
606

607
  CHECK_STRING (prefix);
608 609 610 611 612 613 614 615

  /* VAL is created by adding 6 characters to PREFIX.  The first
     three are the PID of this process, in base 64, and the second
     three are incremented if the file already exists.  This ensures
     262144 unique file names per PID per PREFIX.  */

  pid = (int) getpid ();

616 617 618 619 620 621 622 623 624
  if (base64_p)
    {
      pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidlen = 3;
    }
  else
    {
625
#ifdef HAVE_LONG_FILE_NAMES
626 627
      sprintf (pidbuf, "%d", pid);
      pidlen = strlen (pidbuf);
628
#else
629 630 631 632
      pidbuf[0] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidbuf[1] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidbuf[2] = make_temp_name_tbl[pid & 63], pid >>= 6;
      pidlen = 3;
633
#endif
634
    }
635

636 637 638 639
  len = SBYTES (prefix); clen = SCHARS (prefix);
  val = make_uninit_multibyte_string (clen + 3 + pidlen, len + 3 + pidlen);
  if (!STRING_MULTIBYTE (prefix))
    STRING_SET_UNIBYTE (val);
640
  data = SDATA (val);
641
  memcpy (data, SDATA (prefix), len);
642 643
  p = data + len;

644
  memcpy (p, pidbuf, pidlen);
645 646 647 648 649
  p += pidlen;

  /* Here we try to minimize useless stat'ing when this function is
     invoked many times successively with the same PREFIX.  We achieve
     this by initializing count to a random value, and incrementing it
Richard M. Stallman's avatar
Richard M. Stallman committed
650 651 652 653 654 655
     afterwards.

     We don't want make-temp-name to be called while dumping,
     because then make_temp_name_count_initialized_p would get set
     and then make_temp_name_count would not be set when Emacs starts.  */

656 657 658 659 660 661 662 663 664
  if (!make_temp_name_count_initialized_p)
    {
      make_temp_name_count = (unsigned) time (NULL);
      make_temp_name_count_initialized_p = 1;
    }

  while (1)
    {
      struct stat ignored;
665
      unsigned num = make_temp_name_count;
666 667 668 669 670

      p[0] = make_temp_name_tbl[num & 63], num >>= 6;
      p[1] = make_temp_name_tbl[num & 63], num >>= 6;
      p[2] = make_temp_name_tbl[num & 63], num >>= 6;

671 672 673 674 675
      /* Poor man's congruential RN generator.  Replace with
         ++make_temp_name_count for debugging.  */
      make_temp_name_count += 25229;
      make_temp_name_count %= 225307;

676 677 678 679 680 681 682 683 684 685
      if (stat (data, &ignored) < 0)
	{
	  /* We want to return only if errno is ENOENT.  */
	  if (errno == ENOENT)
	    return val;
	  else
	    /* The error here is dubious, but there is little else we
	       can do.  The alternatives are to return nil, which is
	       as bad as (and in many cases worse than) throwing the
	       error, or to ignore the error, which will likely result
686
	       in looping through 225307 stat's, which is not only
687 688
	       dog-slow, but also useless since eventually nil would
	       have to be returned anyway.  */
689
	    report_file_error ("Cannot create temporary name for prefix",
690 691 692 693
			       Fcons (prefix, Qnil));
	  /* not reached */
	}
    }
Jim Blandy's avatar
Jim Blandy committed
694
}
695

696 697

DEFUN ("make-temp-name", Fmake_temp_name, Smake_temp_name, 1, 1, 0,
698 699 700 701 702 703 704 705 706 707
       doc: /* Generate temporary file name (string) starting with PREFIX (a string).
The Emacs process number forms part of the result,
so there is no danger of generating a name being used by another process.

In addition, this function makes an attempt to choose a name
which has no existing file.  To make this work,
PREFIX should be an absolute file name.

There is a race condition between calling `make-temp-name' and creating the
file which opens all kinds of security holes.  For that reason, you should
708 709 710 711 712
probably use `make-temp-file' instead, except in three circumstances:

* If you are creating the file in the user's home directory.
* If you are creating a directory rather than an ordinary file.
* If you are taking special precautions as `make-temp-file' does.  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
713
  (Lisp_Object prefix)
714 715 716 717 718
{
  return make_temp_name (prefix, 0);
}


Jim Blandy's avatar
Jim Blandy committed
719 720

DEFUN ("expand-file-name", Fexpand_file_name, Sexpand_file_name, 1, 2, 0,
721 722
       doc: /* Convert filename NAME to absolute, and canonicalize it.
Second arg DEFAULT-DIRECTORY is directory to start with if NAME is relative
723
\(does not start with slash or tilde); if DEFAULT-DIRECTORY is nil or missing,
724
the current buffer's value of `default-directory' is used.
725 726
NAME should be a string that is a valid file name for the underlying
filesystem.
727 728 729 730
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.
731 732 733
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.)
734 735
An initial `~/' expands to your home directory.
An initial `~USER/' expands to USER's home directory.
Chong Yidong's avatar
Chong Yidong committed
736 737 738 739 740
See also the function `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
741
\(directory-file-name (file-name-directory dirname)) to traverse a
Chong Yidong's avatar
Chong Yidong committed
742
filesystem tree, not (expand-file-name ".."  dirname).  */)
Dan Nicolaescu's avatar
Dan Nicolaescu committed
743
  (Lisp_Object name, Lisp_Object default_directory)
Jim Blandy's avatar
Jim Blandy committed
744
{
745 746 747 748 749
  /* These point to SDATA and need to be careful with string-relocation
     during GC (via DECODE_FILE).  */
  unsigned char *nm, *newdir;
  /* This should only point to alloca'd data.  */
  unsigned char *target;
750

Jim Blandy's avatar
Jim Blandy committed
751 752
  int tlen;
  struct passwd *pw;
753
#ifdef DOS_NT
754
  int drive = 0;
755
  int collapse_newdir = 1;
756
  int is_escaped = 0;
757
#endif /* DOS_NT */
758
  int length;
759
  Lisp_Object handler, result;
760
  int multibyte;
761
  Lisp_Object hdir;
762

763
  CHECK_STRING (name);
Jim Blandy's avatar
Jim Blandy committed
764

765 766
  /* If the file name has special constructs in it,
     call the corresponding file handler.  */
767
  handler = Ffind_file_name_handler (name, Qexpand_file_name);
768
  if (!NILP (handler))
769
    return call3 (handler, Qexpand_file_name, name, default_directory);
770

771 772 773
  /* Use the buffer's default-directory if DEFAULT_DIRECTORY is omitted.  */
  if (NILP (default_directory))
    default_directory = current_buffer->directory;
774
  if (! STRINGP (default_directory))
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
    {
#ifdef DOS_NT
      /* "/" is not considered a root directory on DOS_NT, so using "/"
	 here causes an infinite recursion in, e.g., the following:

            (let (default-directory)
	      (expand-file-name "a"))

	 To avoid this, we set default_directory to the root of the
	 current drive.  */
      default_directory = build_string (emacs_root_dir ());
#else
      default_directory = build_string ("/");
#endif
    }
790

791
  if (!NILP (default_directory))
792
    {
793
      handler = Ffind_file_name_handler (default_directory, Qexpand_file_name);
794
      if (!NILP (handler))
795
	return call3 (handler, Qexpand_file_name, name, default_directory);
796
    }
797

798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
  {
    unsigned char *o = SDATA (default_directory);

    /* Make sure DEFAULT_DIRECTORY is properly expanded.
       It would be better to do this down below where we actually use
       default_directory.  Unfortunately, calling Fexpand_file_name recursively
       could invoke GC, and the strings might be relocated.  This would
       be annoying because we have pointers into strings lying around
       that would need adjusting, and people would add new pointers to
       the code and forget to adjust them, resulting in intermittent bugs.
       Putting this call here avoids all that crud.

       The EQ test avoids infinite recursion.  */
    if (! NILP (default_directory) && !EQ (default_directory, name)
	/* Save time in some common cases - as long as default_directory
	   is not relative, it can be canonicalized with name below (if it
	   is needed at all) without requiring it to be expanded now.  */
815
#ifdef DOS_NT
816 817 818
	/* Detect MSDOS file names with drive specifiers.  */
	&& ! (IS_DRIVE (o[0]) && IS_DEVICE_SEP (o[1])
	      && IS_DIRECTORY_SEP (o[2]))
819
#ifdef WINDOWSNT
820 821
	/* Detect Windows file names in UNC format.  */
	&& ! (IS_DIRECTORY_SEP (o[0]) && IS_DIRECTORY_SEP (o[1]))
822
#endif
823 824 825
#else /* not DOS_NT */
      /* Detect Unix absolute file names (/... alone is not absolute on
	 DOS or Windows).  */
826
	&& ! (IS_DIRECTORY_SEP (o[0]))
827
#endif /* not DOS_NT */
828 829 830
	)
      {
	struct gcpro gcpro1;
831

832 833 834 835 836
	GCPRO1 (name);
	default_directory = Fexpand_file_name (default_directory, Qnil);
	UNGCPRO;
      }
  }
837
  name = FILE_SYSTEM_CASE (name);
838
  multibyte = STRING_MULTIBYTE (name);
839 840 841 842 843 844 845 846 847 848 849
  if (multibyte != STRING_MULTIBYTE (default_directory))
    {
      if (multibyte)
	default_directory = string_to_multibyte (default_directory);
      else
	{
	  name = string_to_multibyte (name);
	  multibyte = 1;
	}
    }

850
  /* Make a local copy of nm[] to protect it from GC in DECODE_FILE below. */
851
  nm = (unsigned char *) alloca (SBYTES (name) + 1);
852
  memcpy (nm, SDATA (name), SBYTES (name) + 1);
853

854
#ifdef DOS_NT
855 856 857 858 859 860 861
  /* Note if special escape prefix is present, but remove for now.  */
  if (nm[0] == '/' && nm[1] == ':')
    {
      is_escaped = 1;
      nm += 2;
    }

862
  /* Find and remove drive specifier if present; this makes nm absolute
863 864 865 866 867 868 869
     even if the rest of the name appears to be relative.  Only look for
     drive specifier at the beginning.  */
  if (IS_DRIVE (nm[0]) && IS_DEVICE_SEP (nm[1]))
    {
      drive = nm[0];
      nm += 2;
    }
870 871 872 873 874 875 876

#ifdef WINDOWSNT
  /* If we see "c://somedir", we want to strip the first slash after the
     colon when stripping the drive letter.  Otherwise, this expands to
     "//somedir".  */
  if (drive && IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
    nm++;
877

878 879 880 881 882
  /* Discard any previous drive specifier if nm is now in UNC format. */
  if (IS_DIRECTORY_SEP (nm[0]) && IS_DIRECTORY_SEP (nm[1]))
    {
      drive = 0;
    }
883 884
#endif /* WINDOWSNT */
#endif /* DOS_NT */
885

886 887 888
  /* If nm is absolute, look for `/./' or `/../' or `//''sequences; if
     none are found, we can probably return right away.  We will avoid
     allocating a new string if name is already fully expanded.  */
Jim Blandy's avatar
Jim Blandy committed
889
  if (
890
      IS_DIRECTORY_SEP (nm[0])
891
#ifdef MSDOS
892
      && drive && !is_escaped
893 894
#endif
#ifdef WINDOWSNT
895
      && (drive || IS_DIRECTORY_SEP (nm[1])) && !is_escaped
896
#endif
Jim Blandy's avatar
Jim Blandy committed
897 898
      )
    {
899 900 901 902 903 904 905
      /* If it turns out that the filename we want to return is just a
	 suffix of FILENAME, we don't need to go through and edit
	 things; we just need to construct a new string using data
	 starting at the middle of FILENAME.  If we set lose to a
	 non-zero value, that means we've discovered that we can't do
	 that cool trick.  */
      int lose = 0;
906
      unsigned char *p = nm;
907

Jim Blandy's avatar
Jim Blandy committed
908 909
      while (*p)
	{
910
	  /* Since we know the name is absolute, we can assume that each
911 912 913
	     element starts with a "/".  */

	  /* "." and ".." are hairy.  */
914
	  if (IS_DIRECTORY_SEP (p[0])
915
	      && p[1] == '.'
916
	      && (IS_DIRECTORY_SEP (p[2])
917
		  || p[2] == 0
918
		  || (p[2] == '.' && (IS_DIRECTORY_SEP (p[3])
919
				      || p[3] == 0))))
Jim Blandy's avatar
Jim Blandy committed
920
	    lose = 1;
921 922 923 924 925 926
	  /* We want to replace multiple `/' in a row with a single
	     slash.  */
	  else if (p > nm
		   && IS_DIRECTORY_SEP (p[0])
		   && IS_DIRECTORY_SEP (p[1]))
	    lose = 1;
Jim Blandy's avatar
Jim Blandy committed
927 928 929 930
	  p++;
	}
      if (!lose)
	{
931
#ifdef DOS_NT
932 933 934
	  /* Make sure directories are all separated with /, but
	     avoid allocation of a new string when not required. */
	  dostounix_filename (nm);
935 936 937
#ifdef WINDOWSNT
	  if (IS_DIRECTORY_SEP (nm[1]))
	    {
938
	      if (strcmp (nm, SSDATA (name)) != 0)
939
		name = make_specified_string (nm, -1, strlen (nm), multibyte);
940 941 942 943
	    }
	  else
#endif
	  /* drive must be set, so this is okay */
944
	  if (strcmp (nm - 2, SDATA (name)) != 0)
945
	    {
946 947
	      char temp[] = " :";

948
	      name = make_specified_string (nm, -1, p - nm, multibyte);
949 950
	      temp[0] = DRIVE_LETTER (drive);
	      name = concat2 (build_string (temp), name);
951 952 953
	    }
	  return name;
#else /* not DOS_NT */
954
	  if (strcmp (nm, SSDATA (name)) == 0)
Jim Blandy's avatar
Jim Blandy committed
955
	    return name;
956
	  return make_specified_string (nm, -1, strlen (nm), multibyte);
957
#endif /* not DOS_NT */
Jim Blandy's avatar
Jim Blandy committed
958 959 960
	}
    }

961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
  /* At this point, nm might or might not be an absolute file name.  We
     need to expand ~ or ~user if present, otherwise prefix nm with
     default_directory if nm is not absolute, and finally collapse /./
     and /foo/../ sequences.

     We set newdir to be the appropriate prefix if one is needed:
       - the relevant user directory if nm starts with ~ or ~user
       - the specified drive's working dir (DOS/NT only) if nm does not
         start with /
       - the value of default_directory.

     Note that these prefixes are not guaranteed to be absolute (except
     for the working dir of a drive).  Therefore, to ensure we always
     return an absolute name, if the final prefix is not absolute we
     append it to the current working directory.  */
Jim Blandy's avatar
Jim Blandy committed
976 977 978 979

  newdir = 0;

  if (nm[0] == '~')		/* prefix ~ */
980
    {
981
      if (IS_DIRECTORY_SEP (nm[1])
982 983
	  || nm[1] == 0)	/* ~ by itself */
	{
984 985
	  Lisp_Object tem;

986 987
	  if (!(newdir = (unsigned char *) egetenv ("HOME")))
	    newdir = (unsigned char *) "";