clean-temp.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. /* Temporary directories and temporary files with automatic cleanup.
  2. Copyright (C) 2001, 2003, 2006-2007, 2009-2016 Free Software Foundation,
  3. Inc.
  4. Written by Bruno Haible <bruno@clisp.org>, 2006.
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  15. #include <config.h>
  16. /* Specification. */
  17. #include "clean-temp.h"
  18. #include <errno.h>
  19. #include <fcntl.h>
  20. #include <limits.h>
  21. #include <stdbool.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  26. # define WIN32_LEAN_AND_MEAN /* avoid including junk */
  27. # include <windows.h>
  28. #endif
  29. #include "error.h"
  30. #include "fatal-signal.h"
  31. #include "pathmax.h"
  32. #include "tmpdir.h"
  33. #include "xalloc.h"
  34. #include "xmalloca.h"
  35. #include "gl_xlist.h"
  36. #include "gl_linkedhash_list.h"
  37. #include "gettext.h"
  38. #if GNULIB_FWRITEERROR
  39. # include "fwriteerror.h"
  40. #endif
  41. #if GNULIB_CLOSE_STREAM
  42. # include "close-stream.h"
  43. #endif
  44. #if GNULIB_FCNTL_SAFER
  45. # include "fcntl--.h"
  46. #endif
  47. #if GNULIB_FOPEN_SAFER
  48. # include "stdio--.h"
  49. #endif
  50. #define _(str) gettext (str)
  51. /* GNU Hurd doesn't have PATH_MAX. Use a fallback.
  52. Temporary directory names are usually not that long. */
  53. #ifndef PATH_MAX
  54. # define PATH_MAX 1024
  55. #endif
  56. #ifndef uintptr_t
  57. # define uintptr_t unsigned long
  58. #endif
  59. /* The use of 'volatile' in the types below (and ISO C 99 section 5.1.2.3.(5))
  60. ensure that while constructing or modifying the data structures, the field
  61. values are written to memory in the order of the C statements. So the
  62. signal handler can rely on these field values to be up to date. */
  63. /* Registry for a single temporary directory.
  64. 'struct temp_dir' from the public header file overlaps with this. */
  65. struct tempdir
  66. {
  67. /* The absolute pathname of the directory. */
  68. char * volatile dirname;
  69. /* Whether errors during explicit cleanup are reported to standard error. */
  70. bool cleanup_verbose;
  71. /* Absolute pathnames of subdirectories. */
  72. gl_list_t /* <char *> */ volatile subdirs;
  73. /* Absolute pathnames of files. */
  74. gl_list_t /* <char *> */ volatile files;
  75. };
  76. /* List of all temporary directories. */
  77. static struct
  78. {
  79. struct tempdir * volatile * volatile tempdir_list;
  80. size_t volatile tempdir_count;
  81. size_t tempdir_allocated;
  82. } cleanup_list /* = { NULL, 0, 0 } */;
  83. /* List of all open file descriptors to temporary files. */
  84. static gl_list_t /* <int> */ volatile descriptors;
  85. /* For the subdirs and for the files, we use a gl_list_t of type LINKEDHASH.
  86. Why? We need a data structure that
  87. 1) Can contain an arbitrary number of 'char *' values. The strings
  88. are compared via strcmp, not pointer comparison.
  89. 2) Has insertion and deletion operations that are fast: ideally O(1),
  90. or possibly O(log n). This is important for GNU sort, which may
  91. create a large number of temporary files.
  92. 3) Allows iteration through all elements from within a signal handler.
  93. 4) May or may not allow duplicates. It doesn't matter here, since
  94. any file or subdir can only be removed once.
  95. Criterion 1) would allow any gl_list_t or gl_oset_t implementation.
  96. Criterion 2) leaves only GL_LINKEDHASH_LIST, GL_TREEHASH_LIST, or
  97. GL_TREE_OSET.
  98. Criterion 3) puts at disadvantage GL_TREEHASH_LIST and GL_TREE_OSET.
  99. Namely, iteration through the elements of a binary tree requires access
  100. to many ->left, ->right, ->parent pointers. However, the rebalancing
  101. code for insertion and deletion in an AVL or red-black tree is so
  102. complicated that we cannot assume that >left, ->right, ->parent pointers
  103. are in a consistent state throughout these operations. Therefore, to
  104. avoid a crash in the signal handler, all destructive operations to the
  105. lists would have to be protected by a
  106. block_fatal_signals ();
  107. ...
  108. unblock_fatal_signals ();
  109. pair. Which causes extra system calls.
  110. Criterion 3) would also discourage GL_ARRAY_LIST and GL_CARRAY_LIST,
  111. if they were not already excluded. Namely, these implementations use
  112. xrealloc(), leaving a time window in which in the list->elements pointer
  113. points to already deallocated memory. To avoid a crash in the signal
  114. handler at such a moment, all destructive operations would have to
  115. protected by block/unblock_fatal_signals (), in this case too.
  116. A list of type GL_LINKEDHASH_LIST without duplicates fulfills all
  117. requirements:
  118. 2) Insertion and deletion are O(1) on average.
  119. 3) The gl_list_iterator, gl_list_iterator_next implementations do
  120. not trigger memory allocations, nor other system calls, and are
  121. therefore safe to be called from a signal handler.
  122. Furthermore, since SIGNAL_SAFE_LIST is defined, the implementation
  123. of the destructive functions ensures that the list structure is
  124. safe to be traversed at any moment, even when interrupted by an
  125. asynchronous signal.
  126. */
  127. /* String equality and hash code functions used by the lists. */
  128. static bool
  129. string_equals (const void *x1, const void *x2)
  130. {
  131. const char *s1 = (const char *) x1;
  132. const char *s2 = (const char *) x2;
  133. return strcmp (s1, s2) == 0;
  134. }
  135. #define SIZE_BITS (sizeof (size_t) * CHAR_BIT)
  136. /* A hash function for NUL-terminated char* strings using
  137. the method described by Bruno Haible.
  138. See http://www.haible.de/bruno/hashfunc.html. */
  139. static size_t
  140. string_hash (const void *x)
  141. {
  142. const char *s = (const char *) x;
  143. size_t h = 0;
  144. for (; *s; s++)
  145. h = *s + ((h << 9) | (h >> (SIZE_BITS - 9)));
  146. return h;
  147. }
  148. /* The signal handler. It gets called asynchronously. */
  149. static void
  150. cleanup ()
  151. {
  152. size_t i;
  153. /* First close all file descriptors to temporary files. */
  154. {
  155. gl_list_t fds = descriptors;
  156. if (fds != NULL)
  157. {
  158. gl_list_iterator_t iter;
  159. const void *element;
  160. iter = gl_list_iterator (fds);
  161. while (gl_list_iterator_next (&iter, &element, NULL))
  162. {
  163. int fd = (int) (uintptr_t) element;
  164. close (fd);
  165. }
  166. gl_list_iterator_free (&iter);
  167. }
  168. }
  169. for (i = 0; i < cleanup_list.tempdir_count; i++)
  170. {
  171. struct tempdir *dir = cleanup_list.tempdir_list[i];
  172. if (dir != NULL)
  173. {
  174. gl_list_iterator_t iter;
  175. const void *element;
  176. /* First cleanup the files in the subdirectories. */
  177. iter = gl_list_iterator (dir->files);
  178. while (gl_list_iterator_next (&iter, &element, NULL))
  179. {
  180. const char *file = (const char *) element;
  181. unlink (file);
  182. }
  183. gl_list_iterator_free (&iter);
  184. /* Then cleanup the subdirectories. */
  185. iter = gl_list_iterator (dir->subdirs);
  186. while (gl_list_iterator_next (&iter, &element, NULL))
  187. {
  188. const char *subdir = (const char *) element;
  189. rmdir (subdir);
  190. }
  191. gl_list_iterator_free (&iter);
  192. /* Then cleanup the temporary directory itself. */
  193. rmdir (dir->dirname);
  194. }
  195. }
  196. }
  197. /* Create a temporary directory.
  198. PREFIX is used as a prefix for the name of the temporary directory. It
  199. should be short and still give an indication about the program.
  200. PARENTDIR can be used to specify the parent directory; if NULL, a default
  201. parent directory is used (either $TMPDIR or /tmp or similar).
  202. CLEANUP_VERBOSE determines whether errors during explicit cleanup are
  203. reported to standard error.
  204. Return a fresh 'struct temp_dir' on success. Upon error, an error message
  205. is shown and NULL is returned. */
  206. struct temp_dir *
  207. create_temp_dir (const char *prefix, const char *parentdir,
  208. bool cleanup_verbose)
  209. {
  210. struct tempdir * volatile *tmpdirp = NULL;
  211. struct tempdir *tmpdir;
  212. size_t i;
  213. char *xtemplate;
  214. char *tmpdirname;
  215. /* See whether it can take the slot of an earlier temporary directory
  216. already cleaned up. */
  217. for (i = 0; i < cleanup_list.tempdir_count; i++)
  218. if (cleanup_list.tempdir_list[i] == NULL)
  219. {
  220. tmpdirp = &cleanup_list.tempdir_list[i];
  221. break;
  222. }
  223. if (tmpdirp == NULL)
  224. {
  225. /* See whether the array needs to be extended. */
  226. if (cleanup_list.tempdir_count == cleanup_list.tempdir_allocated)
  227. {
  228. /* Note that we cannot use xrealloc(), because then the cleanup()
  229. function could access an already deallocated array. */
  230. struct tempdir * volatile *old_array = cleanup_list.tempdir_list;
  231. size_t old_allocated = cleanup_list.tempdir_allocated;
  232. size_t new_allocated = 2 * cleanup_list.tempdir_allocated + 1;
  233. struct tempdir * volatile *new_array =
  234. XNMALLOC (new_allocated, struct tempdir * volatile);
  235. if (old_allocated == 0)
  236. /* First use of this facility. Register the cleanup handler. */
  237. at_fatal_signal (&cleanup);
  238. else
  239. {
  240. /* Don't use memcpy() here, because memcpy takes non-volatile
  241. arguments and is therefore not guaranteed to complete all
  242. memory stores before the next statement. */
  243. size_t k;
  244. for (k = 0; k < old_allocated; k++)
  245. new_array[k] = old_array[k];
  246. }
  247. cleanup_list.tempdir_list = new_array;
  248. cleanup_list.tempdir_allocated = new_allocated;
  249. /* Now we can free the old array. */
  250. if (old_array != NULL)
  251. free ((struct tempdir **) old_array);
  252. }
  253. tmpdirp = &cleanup_list.tempdir_list[cleanup_list.tempdir_count];
  254. /* Initialize *tmpdirp before incrementing tempdir_count, so that
  255. cleanup() will skip this entry before it is fully initialized. */
  256. *tmpdirp = NULL;
  257. cleanup_list.tempdir_count++;
  258. }
  259. /* Initialize a 'struct tempdir'. */
  260. tmpdir = XMALLOC (struct tempdir);
  261. tmpdir->dirname = NULL;
  262. tmpdir->cleanup_verbose = cleanup_verbose;
  263. tmpdir->subdirs = gl_list_create_empty (GL_LINKEDHASH_LIST,
  264. string_equals, string_hash, NULL,
  265. false);
  266. tmpdir->files = gl_list_create_empty (GL_LINKEDHASH_LIST,
  267. string_equals, string_hash, NULL,
  268. false);
  269. /* Create the temporary directory. */
  270. xtemplate = (char *) xmalloca (PATH_MAX);
  271. if (path_search (xtemplate, PATH_MAX, parentdir, prefix, parentdir == NULL))
  272. {
  273. error (0, errno,
  274. _("cannot find a temporary directory, try setting $TMPDIR"));
  275. goto quit;
  276. }
  277. block_fatal_signals ();
  278. tmpdirname = mkdtemp (xtemplate);
  279. if (tmpdirname != NULL)
  280. {
  281. tmpdir->dirname = tmpdirname;
  282. *tmpdirp = tmpdir;
  283. }
  284. unblock_fatal_signals ();
  285. if (tmpdirname == NULL)
  286. {
  287. error (0, errno,
  288. _("cannot create a temporary directory using template \"%s\""),
  289. xtemplate);
  290. goto quit;
  291. }
  292. /* Replace tmpdir->dirname with a copy that has indefinite extent.
  293. We cannot do this inside the block_fatal_signals/unblock_fatal_signals
  294. block because then the cleanup handler would not remove the directory
  295. if xstrdup fails. */
  296. tmpdir->dirname = xstrdup (tmpdirname);
  297. freea (xtemplate);
  298. return (struct temp_dir *) tmpdir;
  299. quit:
  300. freea (xtemplate);
  301. return NULL;
  302. }
  303. /* Register the given ABSOLUTE_FILE_NAME as being a file inside DIR, that
  304. needs to be removed before DIR can be removed.
  305. Should be called before the file ABSOLUTE_FILE_NAME is created. */
  306. void
  307. register_temp_file (struct temp_dir *dir,
  308. const char *absolute_file_name)
  309. {
  310. struct tempdir *tmpdir = (struct tempdir *)dir;
  311. /* Add absolute_file_name to tmpdir->files, without duplicates. */
  312. if (gl_list_search (tmpdir->files, absolute_file_name) == NULL)
  313. gl_list_add_first (tmpdir->files, xstrdup (absolute_file_name));
  314. }
  315. /* Unregister the given ABSOLUTE_FILE_NAME as being a file inside DIR, that
  316. needs to be removed before DIR can be removed.
  317. Should be called when the file ABSOLUTE_FILE_NAME could not be created. */
  318. void
  319. unregister_temp_file (struct temp_dir *dir,
  320. const char *absolute_file_name)
  321. {
  322. struct tempdir *tmpdir = (struct tempdir *)dir;
  323. gl_list_t list = tmpdir->files;
  324. gl_list_node_t node;
  325. node = gl_list_search (list, absolute_file_name);
  326. if (node != NULL)
  327. {
  328. char *old_string = (char *) gl_list_node_value (list, node);
  329. gl_list_remove_node (list, node);
  330. free (old_string);
  331. }
  332. }
  333. /* Register the given ABSOLUTE_DIR_NAME as being a subdirectory inside DIR,
  334. that needs to be removed before DIR can be removed.
  335. Should be called before the subdirectory ABSOLUTE_DIR_NAME is created. */
  336. void
  337. register_temp_subdir (struct temp_dir *dir,
  338. const char *absolute_dir_name)
  339. {
  340. struct tempdir *tmpdir = (struct tempdir *)dir;
  341. /* Add absolute_dir_name to tmpdir->subdirs, without duplicates. */
  342. if (gl_list_search (tmpdir->subdirs, absolute_dir_name) == NULL)
  343. gl_list_add_first (tmpdir->subdirs, xstrdup (absolute_dir_name));
  344. }
  345. /* Unregister the given ABSOLUTE_DIR_NAME as being a subdirectory inside DIR,
  346. that needs to be removed before DIR can be removed.
  347. Should be called when the subdirectory ABSOLUTE_DIR_NAME could not be
  348. created. */
  349. void
  350. unregister_temp_subdir (struct temp_dir *dir,
  351. const char *absolute_dir_name)
  352. {
  353. struct tempdir *tmpdir = (struct tempdir *)dir;
  354. gl_list_t list = tmpdir->subdirs;
  355. gl_list_node_t node;
  356. node = gl_list_search (list, absolute_dir_name);
  357. if (node != NULL)
  358. {
  359. char *old_string = (char *) gl_list_node_value (list, node);
  360. gl_list_remove_node (list, node);
  361. free (old_string);
  362. }
  363. }
  364. /* Remove a file, with optional error message.
  365. Return 0 upon success, or -1 if there was some problem. */
  366. static int
  367. do_unlink (struct temp_dir *dir, const char *absolute_file_name)
  368. {
  369. if (unlink (absolute_file_name) < 0 && dir->cleanup_verbose
  370. && errno != ENOENT)
  371. {
  372. error (0, errno, _("cannot remove temporary file %s"), absolute_file_name);
  373. return -1;
  374. }
  375. return 0;
  376. }
  377. /* Remove a directory, with optional error message.
  378. Return 0 upon success, or -1 if there was some problem. */
  379. static int
  380. do_rmdir (struct temp_dir *dir, const char *absolute_dir_name)
  381. {
  382. if (rmdir (absolute_dir_name) < 0 && dir->cleanup_verbose
  383. && errno != ENOENT)
  384. {
  385. error (0, errno,
  386. _("cannot remove temporary directory %s"), absolute_dir_name);
  387. return -1;
  388. }
  389. return 0;
  390. }
  391. /* Remove the given ABSOLUTE_FILE_NAME and unregister it.
  392. Return 0 upon success, or -1 if there was some problem. */
  393. int
  394. cleanup_temp_file (struct temp_dir *dir,
  395. const char *absolute_file_name)
  396. {
  397. int err;
  398. err = do_unlink (dir, absolute_file_name);
  399. unregister_temp_file (dir, absolute_file_name);
  400. return err;
  401. }
  402. /* Remove the given ABSOLUTE_DIR_NAME and unregister it.
  403. Return 0 upon success, or -1 if there was some problem. */
  404. int
  405. cleanup_temp_subdir (struct temp_dir *dir,
  406. const char *absolute_dir_name)
  407. {
  408. int err;
  409. err = do_rmdir (dir, absolute_dir_name);
  410. unregister_temp_subdir (dir, absolute_dir_name);
  411. return err;
  412. }
  413. /* Remove all registered files and subdirectories inside DIR.
  414. Return 0 upon success, or -1 if there was some problem. */
  415. int
  416. cleanup_temp_dir_contents (struct temp_dir *dir)
  417. {
  418. struct tempdir *tmpdir = (struct tempdir *)dir;
  419. int err = 0;
  420. gl_list_t list;
  421. gl_list_iterator_t iter;
  422. const void *element;
  423. gl_list_node_t node;
  424. /* First cleanup the files in the subdirectories. */
  425. list = tmpdir->files;
  426. iter = gl_list_iterator (list);
  427. while (gl_list_iterator_next (&iter, &element, &node))
  428. {
  429. char *file = (char *) element;
  430. err |= do_unlink (dir, file);
  431. gl_list_remove_node (list, node);
  432. /* Now only we can free file. */
  433. free (file);
  434. }
  435. gl_list_iterator_free (&iter);
  436. /* Then cleanup the subdirectories. */
  437. list = tmpdir->subdirs;
  438. iter = gl_list_iterator (list);
  439. while (gl_list_iterator_next (&iter, &element, &node))
  440. {
  441. char *subdir = (char *) element;
  442. err |= do_rmdir (dir, subdir);
  443. gl_list_remove_node (list, node);
  444. /* Now only we can free subdir. */
  445. free (subdir);
  446. }
  447. gl_list_iterator_free (&iter);
  448. return err;
  449. }
  450. /* Remove all registered files and subdirectories inside DIR and DIR itself.
  451. DIR cannot be used any more after this call.
  452. Return 0 upon success, or -1 if there was some problem. */
  453. int
  454. cleanup_temp_dir (struct temp_dir *dir)
  455. {
  456. struct tempdir *tmpdir = (struct tempdir *)dir;
  457. int err = 0;
  458. size_t i;
  459. err |= cleanup_temp_dir_contents (dir);
  460. err |= do_rmdir (dir, tmpdir->dirname);
  461. for (i = 0; i < cleanup_list.tempdir_count; i++)
  462. if (cleanup_list.tempdir_list[i] == tmpdir)
  463. {
  464. /* Remove cleanup_list.tempdir_list[i]. */
  465. if (i + 1 == cleanup_list.tempdir_count)
  466. {
  467. while (i > 0 && cleanup_list.tempdir_list[i - 1] == NULL)
  468. i--;
  469. cleanup_list.tempdir_count = i;
  470. }
  471. else
  472. cleanup_list.tempdir_list[i] = NULL;
  473. /* Now only we can free the tmpdir->dirname, tmpdir->subdirs,
  474. tmpdir->files, and tmpdir itself. */
  475. gl_list_free (tmpdir->files);
  476. gl_list_free (tmpdir->subdirs);
  477. free (tmpdir->dirname);
  478. free (tmpdir);
  479. return err;
  480. }
  481. /* The user passed an invalid DIR argument. */
  482. abort ();
  483. }
  484. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  485. /* On Windows, opening a file with _O_TEMPORARY has the effect of passing
  486. the FILE_FLAG_DELETE_ON_CLOSE flag to CreateFile(), which has the effect
  487. of deleting the file when it is closed - even when the program crashes.
  488. But (according to the Cygwin sources) it works only on Windows NT or newer.
  489. So we cache the info whether we are running on Windows NT or newer. */
  490. static bool
  491. supports_delete_on_close ()
  492. {
  493. static int known; /* 1 = yes, -1 = no, 0 = unknown */
  494. /* M4 wants to close and later reopen a temporary file, so
  495. delete-on-close must not be used. */
  496. known = -1;
  497. if (!known)
  498. {
  499. OSVERSIONINFO v;
  500. /* According to
  501. <http://msdn.microsoft.com/en-us/library/windows/desktop/ms724451(v=vs.85).aspx>
  502. this structure must be initialized as follows: */
  503. v.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  504. if (GetVersionEx (&v))
  505. known = (v.dwPlatformId == VER_PLATFORM_WIN32_NT ? 1 : -1);
  506. else
  507. known = -1;
  508. }
  509. return (known > 0);
  510. }
  511. #endif
  512. /* Register a file descriptor to be closed. */
  513. static void
  514. register_fd (int fd)
  515. {
  516. if (descriptors == NULL)
  517. descriptors = gl_list_create_empty (GL_LINKEDHASH_LIST, NULL, NULL, NULL,
  518. false);
  519. gl_list_add_first (descriptors, (void *) (uintptr_t) fd);
  520. }
  521. /* Unregister a file descriptor to be closed. */
  522. static void
  523. unregister_fd (int fd)
  524. {
  525. gl_list_t fds = descriptors;
  526. gl_list_node_t node;
  527. if (fds == NULL)
  528. /* descriptors should already contain fd. */
  529. abort ();
  530. node = gl_list_search (fds, (void *) (uintptr_t) fd);
  531. if (node == NULL)
  532. /* descriptors should already contain fd. */
  533. abort ();
  534. gl_list_remove_node (fds, node);
  535. }
  536. /* Open a temporary file in a temporary directory.
  537. Registers the resulting file descriptor to be closed. */
  538. int
  539. open_temp (const char *file_name, int flags, mode_t mode)
  540. {
  541. int fd;
  542. int saved_errno;
  543. block_fatal_signals ();
  544. /* Note: 'open' here is actually open() or open_safer(). */
  545. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  546. /* Use _O_TEMPORARY when possible, to increase the chances that the
  547. temporary file is removed when the process crashes. */
  548. if (supports_delete_on_close ())
  549. fd = open (file_name, flags | _O_TEMPORARY, mode);
  550. else
  551. #endif
  552. fd = open (file_name, flags, mode);
  553. saved_errno = errno;
  554. if (fd >= 0)
  555. register_fd (fd);
  556. unblock_fatal_signals ();
  557. errno = saved_errno;
  558. return fd;
  559. }
  560. /* Open a temporary file in a temporary directory.
  561. Registers the resulting file descriptor to be closed. */
  562. FILE *
  563. fopen_temp (const char *file_name, const char *mode)
  564. {
  565. FILE *fp;
  566. int saved_errno;
  567. block_fatal_signals ();
  568. /* Note: 'fopen' here is actually fopen() or fopen_safer(). */
  569. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  570. /* Use _O_TEMPORARY when possible, to increase the chances that the
  571. temporary file is removed when the process crashes. */
  572. if (supports_delete_on_close ())
  573. {
  574. size_t mode_len = strlen (mode);
  575. char *augmented_mode = (char *) xmalloca (mode_len + 2);
  576. memcpy (augmented_mode, mode, mode_len);
  577. memcpy (augmented_mode + mode_len, "D", 2);
  578. fp = fopen (file_name, augmented_mode);
  579. saved_errno = errno;
  580. freea (augmented_mode);
  581. }
  582. else
  583. #endif
  584. {
  585. fp = fopen (file_name, mode);
  586. saved_errno = errno;
  587. }
  588. if (fp != NULL)
  589. {
  590. /* It is sufficient to register fileno (fp) instead of the entire fp,
  591. because at cleanup time there is no need to do an fflush (fp); a
  592. close (fileno (fp)) will be enough. */
  593. int fd = fileno (fp);
  594. if (!(fd >= 0))
  595. abort ();
  596. register_fd (fd);
  597. }
  598. unblock_fatal_signals ();
  599. errno = saved_errno;
  600. return fp;
  601. }
  602. /* Close a temporary file in a temporary directory.
  603. Unregisters the previously registered file descriptor. */
  604. int
  605. close_temp (int fd)
  606. {
  607. if (fd >= 0)
  608. {
  609. /* No blocking of signals is needed here, since a double close of a
  610. file descriptor is harmless. */
  611. int result = close (fd);
  612. int saved_errno = errno;
  613. /* No race condition here: we assume a single-threaded program, hence
  614. fd cannot be re-opened here. */
  615. unregister_fd (fd);
  616. errno = saved_errno;
  617. return result;
  618. }
  619. else
  620. return close (fd);
  621. }
  622. /* Close a temporary file in a temporary directory.
  623. Unregisters the previously registered file descriptor. */
  624. int
  625. fclose_temp (FILE *fp)
  626. {
  627. int fd = fileno (fp);
  628. /* No blocking of signals is needed here, since a double close of a
  629. file descriptor is harmless. */
  630. int result = fclose (fp);
  631. int saved_errno = errno;
  632. /* No race condition here: we assume a single-threaded program, hence
  633. fd cannot be re-opened here. */
  634. unregister_fd (fd);
  635. errno = saved_errno;
  636. return result;
  637. }
  638. #if GNULIB_FWRITEERROR
  639. /* Like fwriteerror.
  640. Unregisters the previously registered file descriptor. */
  641. int
  642. fwriteerror_temp (FILE *fp)
  643. {
  644. int fd = fileno (fp);
  645. /* No blocking of signals is needed here, since a double close of a
  646. file descriptor is harmless. */
  647. int result = fwriteerror (fp);
  648. int saved_errno = errno;
  649. /* No race condition here: we assume a single-threaded program, hence
  650. fd cannot be re-opened here. */
  651. unregister_fd (fd);
  652. errno = saved_errno;
  653. return result;
  654. }
  655. #endif
  656. #if GNULIB_CLOSE_STREAM
  657. /* Like close_stream.
  658. Unregisters the previously registered file descriptor. */
  659. int
  660. close_stream_temp (FILE *fp)
  661. {
  662. int fd = fileno (fp);
  663. /* No blocking of signals is needed here, since a double close of a
  664. file descriptor is harmless. */
  665. int result = close_stream (fp);
  666. int saved_errno = errno;
  667. /* No race condition here: we assume a single-threaded program, hence
  668. fd cannot be re-opened here. */
  669. unregister_fd (fd);
  670. errno = saved_errno;
  671. return result;
  672. }
  673. #endif