static char* get_temp_file(const char* prefix, const char* suffix) { int fd; char* tmp = strmake("%s-XXXXXX%s", prefix, suffix); #ifdef HAVE_SIGPROCMASK sigset_t old_set; /* block signals while manipulating the temp files list */ sigprocmask( SIG_BLOCK, &signal_mask, &old_set ); #endif fd = mkstemps( tmp, strlen(suffix) ); if (fd == -1) { /* could not create it in current directory, try in /tmp */ free(tmp); tmp = strmake("/tmp/%s-XXXXXX%s", prefix, suffix); fd = mkstemps( tmp, strlen(suffix) ); if (fd == -1) error( "could not create temp file\n" ); } close( fd ); strarray_add(tmp_files, tmp); #ifdef HAVE_SIGPROCMASK sigprocmask( SIG_SETMASK, &old_set, NULL ); #endif return tmp; }
/* get a name for a temp file, automatically cleaned up on exit */ char *get_temp_file_name( const char *prefix, const char *suffix ) { char *name; const char *ext; int fd; assert( nb_tmp_files < MAX_TMP_FILES ); if (!nb_tmp_files && !save_temps) atexit( cleanup_tmp_files ); if (!prefix || !prefix[0]) prefix = "winebuild"; if (!suffix) suffix = ""; if (!(ext = strchr( prefix, '.' ))) ext = prefix + strlen(prefix); name = xmalloc( sizeof("/tmp/") + (ext - prefix) + sizeof(".XXXXXX") + strlen(suffix) ); strcpy( name, "/tmp/" ); memcpy( name + 5, prefix, ext - prefix ); strcpy( name + 5 + (ext - prefix), ".XXXXXX" ); strcat( name, suffix ); /* first try without the /tmp/ prefix */ if ((fd = mkstemps( name + 5, strlen(suffix) )) != -1) name += 5; else if ((fd = mkstemps( name, strlen(suffix) )) == -1) fatal_error( "could not generate a temp file\n" ); close( fd ); tmp_files[nb_tmp_files++] = name; return name; }
/** * \brief Save an image in the directory, return the short name */ std::string ImageDirectory::save(astro::image::ImagePtr image) { debug(LOG_DEBUG, DEBUG_LOG, 0, "saving an image"); // create a temporary file name in the base directory char buffer[1024]; snprintf(buffer, sizeof(buffer), "%s/XXXXXXXX.fits", basedir().c_str()); int fd = mkstemps(buffer, 5); if (fd < 0) { std::string cause = stringprintf("cannot create a tmp " "image file: %s", strerror(errno)); debug(LOG_ERR, DEBUG_LOG, 0, "%s", cause.c_str()); throw std::runtime_error(cause); } unlink(buffer); close(fd); std::string fullname(buffer); // construct the filename std::string filename = basename(fullname); debug(LOG_DEBUG, DEBUG_LOG, 0, "image full name: %s, filename: %s", fullname.c_str(), filename.c_str()); // write the file ImageDirectory::write(image, filename); // return the filename debug(LOG_DEBUG, DEBUG_LOG, 0, "image short name: %s", filename.c_str()); return filename; }
/* parse into a temporary file */ int wpp_parse_temp( const char *input, const char *output_base, char **output_name ) { FILE *output; int ret, fd; char *temp_name; if (!output_base || !output_base[0]) output_base = "wpptmp"; temp_name = pp_xmalloc( strlen(output_base) + 8 ); strcpy( temp_name, output_base ); strcat( temp_name, ".XXXXXX" ); if((fd = mkstemps( temp_name, 0 )) == -1) { fprintf(stderr, "Could not generate a temp name from %s\n", temp_name); exit(2); } if (!(output = fdopen(fd, "wt"))) { fprintf(stderr,"Could not open fd %s for writing\n", temp_name); exit(2); } *output_name = temp_name; ret = wpp_parse( input, output ); fclose( output ); return ret; }
static int open_file(char *file_name, float alpha, unsigned int fft_nbits, unsigned int use_logscale, GtkImage *canvas) { int ret, tmp_file; char tmp_audio_fname[] = "/tmp/spektro_XXXXXX.wav"; // create tempfile for f32le pcm tmp_file = mkstemps(tmp_audio_fname, 4); if (tmp_file == -1) { g_warning("open_file(): mkstemps() failed"); return -1; } audio_fname = strdup(tmp_audio_fname); close(tmp_file); // create tempfile for image tmp_file = generate_tmp_image_fd(); if (tmp_file == -1) { g_warning("open_file(): mkstemps() failed"); return -1; } // error checking for extract_raw_audio() if ((ret = extract_raw_audio(file_name, tmp_audio_fname)) == 0) { create_rdft_image(alpha, fft_nbits, use_logscale, tmp_audio_fname, tmp_file); set_image(canvas, image_fname); } return ret; }
void open_blob_editor(const char *id, const char *name, unsigned int lineno) { const char *blob_argv[] = { "git", "cat-file", "blob", id, NULL }; char file[SIZEOF_STR]; int fd; if (!name) name = "unknown"; if (!string_format(file, "%s/tigblob.XXXXXX.%s", get_temp_dir(), name)) { report("Temporary file name is too long"); return; } fd = mkstemps(file, strlen(name) + 1); if (fd == -1) report("Failed to create temporary file"); else if (!io_run_append(blob_argv, fd)) report("Failed to save blob data to file"); else open_editor(file, lineno); if (fd != -1) unlink(file); }
static int basl_open(struct basl_fio *bf, int suffix) { int err; err = 0; if (suffix) { strlcpy(bf->f_name, basl_stemplate, MAXPATHLEN); bf->fd = mkstemps(bf->f_name, strlen(BHYVE_ASL_SUFFIX)); } else { strlcpy(bf->f_name, basl_template, MAXPATHLEN); bf->fd = mkstemp(bf->f_name); } if (bf->fd > 0) { bf->fp = fdopen(bf->fd, "w+"); if (bf->fp == NULL) { unlink(bf->f_name); close(bf->fd); } } else { err = 1; } return (err); }
static int os_buf_to_tmp_file_posix(Buf *contents, Buf *suffix, Buf *out_tmp_path) { const char *tmp_dir = getenv("TMPDIR"); if (!tmp_dir) { tmp_dir = P_tmpdir; } buf_resize(out_tmp_path, 0); buf_appendf(out_tmp_path, "%s/XXXXXX%s", tmp_dir, buf_ptr(suffix)); int fd = mkstemps(buf_ptr(out_tmp_path), buf_len(suffix)); if (fd < 0) { return ErrorFileSystem; } FILE *f = fdopen(fd, "wb"); if (!f) { zig_panic("fdopen failed"); } size_t amt_written = fwrite(buf_ptr(contents), 1, buf_len(contents), f); if (amt_written != (size_t)buf_len(contents)) zig_panic("write failed: %s", strerror(errno)); if (fclose(f)) zig_panic("close failed"); return 0; }
// create and open a temporary file static FILE *tmpfile(std::string *pathOut, const std::string &ext) { #ifdef _WIN32 if(apptempdir[0] == 0) { char wintmpdir[MAX_PATH]; if (!GetTempPath(MAX_PATH, wintmpdir)) { fprintf(stderr, "Can't determine temporary directory\n"); exit(-1); } sprintf(apptempdir, "%s\\alcas_%u\\", wintmpdir, unsigned(GetCurrentProcessId())); // If this directory wasn't release the last time this process id was used we need to flush it RemoveDirectory(apptempdir); } // Create a unique temp file inside the app temp dir char tempfilepath[MAX_PATH]; unsigned id = GetTempFileName(apptempdir, "alc", 0, tempfilepath); if(id == 0) { fprintf(stderr, "Can't create temporary file\n"); exit(-1); } // Append the ".as" suffix to the temp file name char tempfilepathex[MAX_PATH]; sprintf(tempfilepathex, "%s.as", tempfilepath); // Now go and create the real temp file HANDLE h = CreateFile(tempfilepathex, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (h == INVALID_HANDLE_VALUE) { fprintf(stderr, "Can't create temporary file handle\n"); exit(-1); } // Close the windows file handle, we want to re-open it with a posix call CloseHandle(h); // finally get the FILE* to the temp file return fopen(tempfilepathex, "wb+"); #else char buf[PATH_MAX]; strcpy(buf, "/tmp/alcasXXXXXXXX"); int suffixLen = 0; if (ext.length() > 0) { strcat(buf, "."); strcat(buf, ext.c_str()); suffixLen = ext.length() + 1; } int fd = mkstemps(buf, suffixLen); if(fd < 0) { perror("mkstemps"); fprintf(stderr, "Can't open temporary file: %s\n", buf); exit(-1); } pathOut->append(buf); return fdopen(fd, "wb+"); #endif }
std::string create_temporary_file_name(std::string prefix, std::string suffix) { char *env = getenv("IMP_BUILD_ROOT"); std::string imp_tmp; if (env) { imp_tmp = internal::get_concatenated_path(env, "build/tmp"); } #if defined _MSC_VER std::string tpathstr; if (imp_tmp.empty()) { TCHAR tpath[MAX_PATH]; DWORD dwRetVal = GetTempPath(MAX_PATH, tpath); if (dwRetVal > MAX_PATH || (dwRetVal == 0)) { IMP_THROW("Unable to find temporary path", IOException); } tpathstr = tpath; } else { tpathstr = imp_tmp; } char filename[MAX_PATH]; if (GetTempFileName(tpathstr.c_str(), prefix.c_str(), 0, filename) == 0) { IMP_THROW("Unable to create temp file in " << tpathstr, IOException); } return std::string(filename) + suffix; #else std::string pathprefix; if (imp_tmp.empty()) { pathprefix = "/tmp"; } else { pathprefix = imp_tmp; } std::string templ = internal::get_concatenated_path(pathprefix, prefix + ".XXXXXX"); boost::scoped_array<char> filename; filename.reset(new char[templ.size() + suffix.size() + 1]); std::copy(templ.begin(), templ.end(), filename.get()); #ifdef __APPLE__ std::copy(suffix.begin(), suffix.end(), filename.get() + templ.size()); filename[templ.size() + suffix.size()] = '\0'; int fd = mkstemps(filename.get(), suffix.size()); if (fd == -1) { IMP_THROW("Unable to create temporary file: " << filename.get(), IOException); } close(fd); #else filename[templ.size()] = '\0'; int fd = mkstemp(filename.get()); if (fd == -1) { IMP_THROW("Unable to create temporary file: " << filename.get(), IOException); } close(fd); std::copy(suffix.begin(), suffix.end(), filename.get() + templ.size()); filename[templ.size() + suffix.size()] = '\0'; #endif return std::string(filename.get()); #endif }
int createSafeFileDescriptor(const char* fileRoot) { // Creates temporary file safely char flacFile[FILENAME_MAX] = ""; snprintf(flacFile, FILENAME_MAX, "%sXXXXXX.wav", fileRoot); // the 5 is for the length of the suffix ".wav" return mkstemps(flacFile, 4); }
static int get_tempfile_if_not_exists(int ini_fd, char ini_path[]) { if (ini_fd == -1) { ini_fd = mkstemps(ini_path, 4); // keep the .ini suffix if (ini_fd == -1) { fprintf(stderr, "Error: unable to open temporary file"); exit(EXIT_FAILURE); } } return ini_fd; }
bool check_xattr_trusted(const char *upper) { char tmp_path[PATH_MAX]; strcpy(tmp_path, upper); strcat(tmp_path, "/.xattr_test_XXXXXX.tmp"); int tmp_file = mkstemps(tmp_path, 4); if (tmp_file < 0) { return false; } bool ret = real_check_xattr_trusted(tmp_path, tmp_file); unlink(tmp_path); return ret; }
void ShellCompiler::init() { // Initialize the base classes CompilerInternal::init(); // Read options string compiler = getOption("compiler").toString(); string compiler_setup = getOption("compiler_setup").toString(); vector<string> flags; if (hasSetOption("flags")) flags = getOption("flags"); // Construct the compiler command stringstream cmd; cmd << compiler << " " << compiler_setup; for (vector<string>::const_iterator i=flags.begin(); i!=flags.end(); ++i) { cmd << " " << *i; } // C/C++ source file cmd << " " << name_; // Name of temporary file #ifdef HAVE_MKSTEMPS // Preferred solution char bin_name[] = "tmp_casadi_compiler_shell_XXXXXX.so"; if (mkstemps(bin_name, 3) == -1) { casadi_error("Failed to create a temporary file name"); } bin_name_ = bin_name; #else // Fallback, may result in deprecation warnings char* bin_name = tempnam(0, "tmp_casadi_compiler_shell_"); bin_name_ = bin_name; free(bin_name); #endif // Have relative paths start with ./ if (bin_name_.at(0)!='/') { bin_name_ = "./" + bin_name_; } // Temporary file cmd << " -o " << bin_name_; // Compile into a shared library if (system(cmd.str().c_str())) { casadi_error("Compilation failed. Tried \"" + cmd.str() + "\""); } // Load shared library handle_ = dlopen(bin_name_.c_str(), RTLD_LAZY); casadi_assert_message(handle_!=0, "CommonExternal: Cannot open function: " << bin_name_ << ". error code: "<< dlerror()); // reset error dlerror(); }
int pocl_mk_tempname (char *output, const char *prefix, const char *suffix, int *ret_fd) { #if defined(_MSC_VER) || defined(__MINGW32__) #error "making temporary files on Windows not implemented" #elif defined(HAVE_MKOSTEMPS) || defined(HAVE_MKSTEMPS) || defined(__ANDROID__) /* using mkstemp() instead of tmpnam() has no real benefit * here, as we have to pass the filename to llvm, * but tmpnam() generates an annoying warning... */ int fd; strncpy (output, prefix, POCL_FILENAME_LENGTH); size_t len = strlen (prefix); strncpy (output + len, "_XXXXXX", (POCL_FILENAME_LENGTH - len)); #ifdef __ANDROID__ fd = pocl_mkstemp (output); #else if (suffix) { len += 7; strncpy (output + len, suffix, (POCL_FILENAME_LENGTH - len)); #ifdef HAVE_MKOSTEMPS fd = mkostemps (output, strlen (suffix), O_CLOEXEC); #else fd = mkstemps (output, strlen (suffix)); #endif } else #ifdef HAVE_MKOSTEMPS fd = mkostemp (output, O_CLOEXEC); #else fd = mkstemp (output); #endif #endif if (fd < 0) { POCL_MSG_ERR ("mkstemp() failed\n"); return errno; } int err = 0; if (ret_fd) *ret_fd = fd; else { err = close (fd); } return err ? errno : 0; #else #error mkostemps() / mkstemps() both unavailable #endif }
void send_capcha(Tox *tox, uint32_t friend_number,const unsigned char gif[gifsize], const unsigned char l[6]) { FILE *capchafile = NULL; char capchafilename[] = "/tmp/capcha-XXXXXX.gif"; int fd = mkstemps(capchafilename, 4); close(fd); capchafile = fopen(capchafilename, "wb"); fwrite(gif,gifsize,1,capchafile); fclose(capchafile); add_filesender(tox, friend_number, capchafilename); }
static int getTemporaryFile(char *fileName, size_t fileNameLength) { char* tempDirectory = getenv("TMPDIR"); if (!tempDirectory) tempDirectory = getenv("TEMP"); if (tempDirectory) snprintf(fileName, fileNameLength, "%s/ImageDiffXXXXXX.png", tempDirectory); else { #if __linux__ strcpy(fileName, "/dev/shm/ImageDiffXXXXXX.png"); const int fileDescriptor = mkstemps(fileName, sizeof(".png") - 1); if (fileDescriptor >= 0) return fileDescriptor; #endif // __linux__ strcpy(fileName, "ImageDiffXXXXXX.png"); } return mkstemps(fileName, sizeof(".png") - 1); }
int gen_tmp_file(const char *templ, char *path_out, FILE **fp_out) { int rc = -1; #ifdef _WIN32 // TODO: implement me #else int fd, i_XXXXXX, suffix_len; // TODO: secure this string crap char path[64]; get_tmp_path(path, sizeof(path)); strcat(path, "/"); strcat(path, templ); // find length of suffix for(i_XXXXXX=0; i_XXXXXX < strlen(path)-5; i_XXXXXX++) { //debug("at idx=%d looking at: %s\n", i_XXXXXX, path+i_XXXXXX); if(0 == strncmp(path+i_XXXXXX, "XXXXXX", 6)) { break; } } if(i_XXXXXX >= strlen(path)-5) { //debug("ERROR: couldn't find XXXXXX in \"%s\"\n", path); goto cleanup; } suffix_len = strlen(path) - (i_XXXXXX+6); //debug("sending mkstemp \"%s\" with suffix length %d\n", path, suffix_len); fd = mkstemps(path, suffix_len); if(fd < 0) { //debug("ERROR: mkstemp() returned %d\n", fd); goto cleanup; } strcpy(path_out, path); /* file descriptor is linux specific int inside proc_struct, convert this to stdlib file pointer */ *fp_out = fdopen(fd, "w"); if(*fp_out == NULL) { //debug("ERROR: fdopen()\n"); goto cleanup; } #endif rc = 0; cleanup: return rc; }
void processAndLogNewSpawnException(SpawnException &e, const Options &options, ResourceLocator &resourceLocator, RandomGenerator &randomGenerator) { ErrorRenderer renderer(resourceLocator); string errorId = randomGenerator.generateHexString(4); string appMessage = e.getErrorPage(); char filename[PATH_MAX]; stringstream stream; e.set("ERROR_ID", errorId); if (appMessage.empty()) { appMessage = "none"; } try { int fd = -1; FdGuard guard(fd, true); string errorPage; errorPage = renderer.renderWithDetails(appMessage, options, &e); #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) snprintf(filename, PATH_MAX, "%s/passenger-error-XXXXXX.html", getSystemTempDir()); fd = mkstemps(filename, sizeof(".html") - 1); #else snprintf(filename, PATH_MAX, "%s/passenger-error.XXXXXX", getSystemTempDir()); fd = mkstemp(filename); #endif if (fd == -1) { int e = errno; throw SystemException("Cannot generate a temporary filename", e); } writeExact(fd, errorPage); } catch (const SystemException &e2) { filename[0] = '\0'; P_ERROR("Cannot render an error page: " << e2.what() << "\n" << e2.backtrace()); } stream << "Could not spawn process for application " << options.appRoot << ": " << e.what() << "\n" << " Error ID: " << errorId << "\n"; if (filename[0] != '\0') { stream << " Error details saved to: " << filename << "\n"; } stream << " Message from application: " << appMessage << "\n"; P_ERROR(stream.str()); }
TemporaryFile(const std::string &prefix, const std::string &suffix = "", std::string tempdir = "") : autodelete(true) { if (tempdir.size() == 0) { const char* tmpdir_parent = std::getenv("TMPDIR"); if (tmpdir_parent == NULL) tempdir = "/tmp"; else tempdir = tmpdir_parent; } std::snprintf(tempfilepath, sizeof(tempfilepath)-1, "%s/%s-XXXXXX%s", tempdir.c_str(), prefix.c_str(), suffix.c_str()); if (mkstemps(tempfilepath, suffix.size()) == -1) { bzero(tempfilepath, sizeof(tempfilepath)); } }
int write_jpeg_image(char *fn, Pixel (*frame)[MAX_Y][MAX_X]) { FILE *jpegout; struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; int x, y; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); if (fn) jpegout = fopen(fn, "wb"); else { int fd = mkstemps("XXX.jpeg", 5); jpegout = fdopen(fd, "w"); } if (jpegout == NULL) { perror("can't open jpeg"); return 0; } jpeg_stdio_dest(&cinfo, jpegout); cinfo.image_width = MAX_X; /* image width and height, in pixels */ cinfo.image_height = MAX_Y; cinfo.input_components = 3; /* # of color components per pixel */ cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ cinfo.dct_method = JDCT_ISLOW; /* slow, high accuracy encoding */ jpeg_set_defaults(&cinfo); jpeg_set_quality (&cinfo, 100, 1); /* highest quality encoding, w. baseline */ jpeg_start_compress(&cinfo, TRUE); for (y=0; y<MAX_Y; y++) { Pixel *in_row = &((*frame)[MAX_Y - y - 1][0]); JSAMPLE row[MAX_X*3]; JSAMPROW row_pointer[1]; row_pointer[0] = &row[0]; for (x=0; x<MAX_X; x++) { row[x*3] = in_row[x].r; row[x*3+1] = in_row[x].g; row[x*3+2] = in_row[x].b; } jpeg_write_scanlines(&cinfo, row_pointer, 1); } jpeg_finish_compress(&cinfo); fclose(jpegout); jpeg_destroy_compress(&cinfo); return 1; }
/* create a temp file for anonymous mappings */ struct file *create_temp_file( int access ) { char tmpfn[16]; int fd; sprintf( tmpfn, "anonmap.XXXXXX" ); /* create it in the server directory */ fd = mkstemps( tmpfn, 0 ); if (fd == -1) { file_set_error(); return NULL; } unlink( tmpfn ); return create_file_for_fd( fd, access, 0 ); }
/** * If the modulo parameter \p mod is \c NULL, then no modulo reduction is done. * * @param[in] f The arithmetic circuit. * @param[in] m Array of messages. * @param[in] m_len Length of the array of messages. * @param[in] mod Value of the modulo. * * @return The evaluated message, or \c NULL if an error ocorred. * @todo Error codes. * @note * This looks slower than native arith_circ_eval(): * * degree 100 polynomial evaluation: * - pinocchio: ~800ms * - native: ~10ms * * degree 200 polynomial evaluation: * - pinocchio: ~5500ms * - native: ~60ms * * degree 300 polynomial evaluation: * - pinocchio: ~10000ms * - native: ~110ms */ cf_errno arith_circ_eval_pinocchio(cf_mpi_t *msg, const arith_circ_t f, cf_mpi_t *m, size_t m_len, const cf_mpi_t mod) { assert(f && f->fn); assert(m); cf_mpi_t *output = NULL; size_t output_len = 0; char in[17] = "/tmp/cfXXXXXX.in\0"; char out[18] = "/tmp/cfXXXXXX.out\0"; int in_fd = mkstemps(in, 3); int out_fd = mkstemps(out, 4); assert(in_fd != -1 && out_fd != -1); arith_circ_write_io(in, m, m_len); // create process to aritheval.py pid_t pid = fork(); int status; if(pid == 0) { execl("/usr/bin/python2", "/usr/bin/python2", PINOCCHIO_AC_EVAL, f->fn, in, out, NULL); } waitpid(pid, &status, 0); output = arith_circ_parse_io(out, &output_len); assert(output_len == 1); remove(in); remove(out); if(mod != NULL) { cf_mpi_mod(&(output[0]), output[0], mod); } // free unused memory cf_mpi_copy(msg, *output); cf_messages_free(output, output_len); return E_NOERR; }
static int get_tempfile_if_not_exists(int ini_fd, char ini_path[]) { if (ini_fd == -1) { #ifdef _MSC_VER // MSVC doesn't require the characters to be the last // 6 in the string. ini_fd = open(mktemp(ini_path), O_RDWR | O_EXCL); #else ini_fd = mkstemps(ini_path, 4); // keep the .ini suffix #endif if (ini_fd == -1) { fprintf(stderr, "Error: unable to open temporary file"); exit(EXIT_FAILURE); } } return ini_fd; }
void GenerateTempFileName ( char alter * tempFileNameOut, char const * extension ) { #ifdef _MSC_VER char temp_dir[_MAX_DIR]; DWORD dir_len = 0; dir_len = GetTempPathA(_MAX_DIR, temp_dir); assert(dir_len != 0); assert(dir_len <= _MAX_DIR); UINT res = 0; res = GetTempFileNameA(temp_dir, "HOOPS", 0, tempFileNameOut); assert(res != 0); // if extension specified, replace .tmp with user-provided value if (extension) { char *old_extension = strrchr(tempFileNameOut, '.'); if (extension[0] == '.') old_extension[0] = 0; else old_extension[1] = 0; strcat(tempFileNameOut, extension); } #else strcpy(tempFileNameOut, "/tmp/tmpXXXXXX"); int ext_len = 0; if (extension) { if (extension[0] != '.') { strcat(tempFileNameOut, "."); ext_len += 1; } strcat(tempFileNameOut, extension); ext_len += strlen(extension); } else { strcat(tempFileNameOut, ".tmp"); ext_len += 4; } int fileDescriptor = mkstemps(tempFileNameOut, ext_len); if (fileDescriptor == -1) { printf("mkstemps call failed.\nerrno: %d\t%s\n", errno, strerror(errno)); tempFileNameOut[0] = 0; } else close(fileDescriptor); #endif }
/* check if the current directory allows exec mappings */ static int check_current_dir_for_exec(void) { int fd; char tmpfn[] = "anonmap.XXXXXX"; void *ret = MAP_FAILED; fd = mkstemps( tmpfn, 0 ); if (fd == -1) return 0; if (grow_file( fd, 1 )) { ret = mmap( NULL, get_page_size(), PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0 ); if (ret != MAP_FAILED) munmap( ret, get_page_size() ); } close( fd ); unlink( tmpfn ); return (ret != MAP_FAILED); }
/* Generate a temporary file name based on OBJ, FLAGS, and NAME. Return NULL if we were unable to reserve a temporary filename. If non-NULL, the result is either allocated with malloc, or the same pointer as NAME. */ static char * temp_file (struct pex_obj *obj, int flags, char *name) { if (name == NULL) { if (obj->tempbase == NULL) { name = make_temp_file (NULL); } else { int len = strlen (obj->tempbase); int out; if (len >= 6 && strcmp (obj->tempbase + len - 6, "XXXXXX") == 0) name = xstrdup (obj->tempbase); else name = concat (obj->tempbase, "XXXXXX", NULL); out = mkstemps (name, 0); if (out < 0) { free (name); return NULL; } /* This isn't obj->funcs->close because we got the descriptor from mkstemps, not from a function in obj->funcs. Calling close here is just like what make_temp_file does. */ close (out); } } else if ((flags & PEX_SUFFIX) != 0) { if (obj->tempbase == NULL) name = make_temp_file (name); else name = concat (obj->tempbase, name, NULL); } return name; }
intptr_t SystemNative_MksTemps(char* pathTemplate, int32_t suffixLength) { intptr_t result; #if HAVE_MKSTEMPS while ((result = mkstemps(pathTemplate, suffixLength)) < 0 && errno == EINTR); #elif HAVE_MKSTEMP // mkstemps is not available bionic/Android, but mkstemp is // mkstemp doesn't allow the suffix that msktemps does allow, so we'll need to // remove that before passisng pathTemplate to mkstemp int32_t pathTemplateLength = (int32_t)strlen(pathTemplate); // pathTemplate must include at least XXXXXX (6 characters) which are not part of // the suffix if (suffixLength < 0 || suffixLength > pathTemplateLength - 6) { errno = EINVAL; return -1; } // Make mkstemp ignore the suffix by setting the first char of the suffix to \0, // if there is a suffix int32_t firstSuffixIndex = 0; char firstSuffixChar = 0; if (suffixLength > 0) { firstSuffixIndex = pathTemplateLength - suffixLength; firstSuffixChar = pathTemplate[firstSuffixIndex]; pathTemplate[firstSuffixIndex] = 0; } while ((result = mkstemp(pathTemplate)) < 0 && errno == EINTR); // Reset the first char of the suffix back to its original value, if there is a suffix if (suffixLength > 0) { pathTemplate[firstSuffixIndex] = firstSuffixChar; } #else #error "Cannot find mkstemps nor mkstemp on this platform" #endif return result; }
/* create a temp file for anonymous mappings */ static int create_temp_file( file_pos_t size ) { char tmpfn[16]; int fd; sprintf( tmpfn, "anonmap.XXXXXX" ); /* create it in the server directory */ fd = mkstemps( tmpfn, 0 ); if (fd != -1) { if (!grow_file( fd, size )) { close( fd ); fd = -1; } unlink( tmpfn ); } else file_set_error(); return fd; }
std::string file_make_temp(const std::string &prefix, const std::string &suffix) { internal_assert(prefix.find("/") == string::npos && prefix.find("\\") == string::npos && suffix.find("/") == string::npos && suffix.find("\\") == string::npos); #ifdef _WIN32 // Windows implementations of mkstemp() try to create the file in the root // directory, which is... problematic. char tmp_path[MAX_PATH], tmp_file[MAX_PATH]; DWORD ret = GetTempPathA(MAX_PATH, tmp_path); internal_assert(ret != 0); // Note that GetTempFileNameA() actually creates the file. ret = GetTempFileNameA(tmp_path, prefix.c_str(), 0, tmp_file); internal_assert(ret != 0); return std::string(tmp_file); #else std::string templ = "/tmp/" + prefix + "XXXXXX" + suffix; // Copy into a temporary buffer, since mkstemp modifies the buffer in place. std::vector<char> buf(templ.size() + 1); strcpy(&buf[0], templ.c_str()); int fd = mkstemps(&buf[0], suffix.size()); internal_assert(fd != -1) << "Unable to create temp file for (" << &buf[0] << ")\n"; close(fd); return std::string(&buf[0]); #endif }