#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_SYS_FILE_H
#include <sys/file.h>
#endif
#ifndef R_OK
#define R_OK 4
#define W_OK 2
#define X_OK 1
#endif
#include "libiberty.h"
extern int mkstemps PARAMS ((char *, int));
#ifndef DIR_SEPARATOR
#define DIR_SEPARATOR '/'
#endif
#define TEMP_FILE "ccXXXXXX"
#define TEMP_FILE_LEN (sizeof(TEMP_FILE) - 1)
static inline const char *try PARAMS ((const char *, const char *));
static inline const char *
try (dir, base)
const char *dir, *base;
{
if (base != 0)
return base;
if (dir != 0
&& access (dir, R_OK | W_OK | X_OK) == 0)
return dir;
return 0;
}
static const char tmp[] = { DIR_SEPARATOR, 't', 'm', 'p', 0 };
static const char usrtmp[] =
{ DIR_SEPARATOR, 'u', 's', 'r', DIR_SEPARATOR, 't', 'm', 'p', 0 };
static const char vartmp[] =
{ DIR_SEPARATOR, 'v', 'a', 'r', DIR_SEPARATOR, 't', 'm', 'p', 0 };
static char *memoized_tmpdir;
char *
choose_tmpdir ()
{
const char *base = 0;
char *tmpdir;
unsigned int len;
if (memoized_tmpdir)
return memoized_tmpdir;
base = try (getenv ("TMPDIR"), base);
base = try (getenv ("TMP"), base);
base = try (getenv ("TEMP"), base);
#ifdef P_tmpdir
base = try (P_tmpdir, base);
#endif
base = try (vartmp, base);
base = try (usrtmp, base);
base = try (tmp, base);
if (base == 0)
base = ".";
len = strlen (base);
tmpdir = xmalloc (len + 2);
strcpy (tmpdir, base);
tmpdir[len] = DIR_SEPARATOR;
tmpdir[len+1] = '\0';
memoized_tmpdir = tmpdir;
return tmpdir;
}
char *
make_temp_file (suffix)
const char *suffix;
{
const char *base = choose_tmpdir ();
char *temp_filename;
int base_len, suffix_len;
int fd;
if (suffix == 0)
suffix = "";
base_len = strlen (base);
suffix_len = strlen (suffix);
temp_filename = xmalloc (base_len
+ TEMP_FILE_LEN
+ suffix_len + 1);
strcpy (temp_filename, base);
strcpy (temp_filename + base_len, TEMP_FILE);
strcpy (temp_filename + base_len + TEMP_FILE_LEN, suffix);
fd = mkstemps (temp_filename, suffix_len);
if (fd == -1)
abort ();
if (close (fd))
abort ();
return temp_filename;
}