blob: 2f24b893c64819ffd4c79921896a42bd9faea6b7 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Unix specific portion of the Path class.
11//
12//===----------------------------------------------------------------------===//
13
14//===----------------------------------------------------------------------===//
15//=== WARNING: Implementation here must contain only generic UNIX code that
16//=== is guaranteed to work on *all* UNIX variants.
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Config/alloca.h"
20#include "Unix.h"
21#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
24#if HAVE_FCNTL_H
25#include <fcntl.h>
26#endif
Chris Lattner116abbf2008-04-01 06:25:23 +000027#ifdef HAVE_SYS_MMAN_H
28#include <sys/mman.h>
29#endif
30#ifdef HAVE_SYS_STAT_H
31#include <sys/stat.h>
32#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#if HAVE_UTIME_H
34#include <utime.h>
35#endif
36#if HAVE_TIME_H
37#include <time.h>
38#endif
39#if HAVE_DIRENT_H
40# include <dirent.h>
41# define NAMLEN(dirent) strlen((dirent)->d_name)
42#else
43# define dirent direct
44# define NAMLEN(dirent) (dirent)->d_namlen
45# if HAVE_SYS_NDIR_H
46# include <sys/ndir.h>
47# endif
48# if HAVE_SYS_DIR_H
49# include <sys/dir.h>
50# endif
51# if HAVE_NDIR_H
52# include <ndir.h>
53# endif
54#endif
55
Chris Lattner365f2202008-03-03 02:55:43 +000056#if HAVE_DLFCN_H
57#include <dlfcn.h>
58#endif
59
Dan Gohmanf17a25c2007-07-18 16:29:46 +000060// Put in a hack for Cygwin which falsely reports that the mkdtemp function
61// is available when it is not.
62#ifdef __CYGWIN__
63# undef HAVE_MKDTEMP
64#endif
65
66namespace {
67inline bool lastIsSlash(const std::string& path) {
68 return !path.empty() && path[path.length() - 1] == '/';
69}
70
71}
72
73namespace llvm {
74using namespace sys;
75
Chris Lattner4b8f1c62008-02-27 06:17:10 +000076extern const char sys::PathSeparator = ':';
77
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078bool
79Path::isValid() const {
80 // Check some obvious things
81 if (path.empty())
82 return false;
83 else if (path.length() >= MAXPATHLEN)
84 return false;
85
86 // Check that the characters are ascii chars
87 size_t len = path.length();
88 unsigned i = 0;
89 while (i < len && isascii(path[i]))
90 ++i;
91 return i >= len;
92}
93
94bool
95Path::isAbsolute() const {
96 if (path.empty())
97 return false;
98 return path[0] == '/';
99}
100Path
101Path::GetRootDirectory() {
102 Path result;
103 result.set("/");
104 return result;
105}
106
107Path
108Path::GetTemporaryDirectory(std::string* ErrMsg ) {
109#if defined(HAVE_MKDTEMP)
110 // The best way is with mkdtemp but that's not available on many systems,
111 // Linux and FreeBSD have it. Others probably won't.
112 char pathname[MAXPATHLEN];
113 strcpy(pathname,"/tmp/llvm_XXXXXX");
114 if (0 == mkdtemp(pathname)) {
115 MakeErrMsg(ErrMsg,
116 std::string(pathname) + ": can't create temporary directory");
117 return Path();
118 }
119 Path result;
120 result.set(pathname);
121 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
122 return result;
123#elif defined(HAVE_MKSTEMP)
124 // If no mkdtemp is available, mkstemp can be used to create a temporary file
125 // which is then removed and created as a directory. We prefer this over
126 // mktemp because of mktemp's inherent security and threading risks. We still
127 // have a slight race condition from the time the temporary file is created to
128 // the time it is re-created as a directoy.
129 char pathname[MAXPATHLEN];
130 strcpy(pathname, "/tmp/llvm_XXXXXX");
131 int fd = 0;
132 if (-1 == (fd = mkstemp(pathname))) {
133 MakeErrMsg(ErrMsg,
134 std::string(pathname) + ": can't create temporary directory");
135 return Path();
136 }
137 ::close(fd);
138 ::unlink(pathname); // start race condition, ignore errors
139 if (-1 == ::mkdir(pathname, S_IRWXU)) { // end race condition
140 MakeErrMsg(ErrMsg,
141 std::string(pathname) + ": can't create temporary directory");
142 return Path();
143 }
144 Path result;
145 result.set(pathname);
146 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
147 return result;
148#elif defined(HAVE_MKTEMP)
149 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
150 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
151 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
152 // the XXXXXX with the pid of the process and a letter. That leads to only
153 // twenty six temporary files that can be generated.
154 char pathname[MAXPATHLEN];
155 strcpy(pathname, "/tmp/llvm_XXXXXX");
156 char *TmpName = ::mktemp(pathname);
157 if (TmpName == 0) {
158 MakeErrMsg(ErrMsg,
159 std::string(TmpName) + ": can't create unique directory name");
160 return Path();
161 }
162 if (-1 == ::mkdir(TmpName, S_IRWXU)) {
163 MakeErrMsg(ErrMsg,
164 std::string(TmpName) + ": can't create temporary directory");
165 return Path();
166 }
167 Path result;
168 result.set(TmpName);
169 assert(result.isValid() && "mktemp didn't create a valid pathname!");
170 return result;
171#else
172 // This is the worst case implementation. tempnam(3) leaks memory unless its
173 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
174 // issues. The mktemp(3) function doesn't have enough variability in the
175 // temporary name generated. So, we provide our own implementation that
176 // increments an integer from a random number seeded by the current time. This
177 // should be sufficiently unique that we don't have many collisions between
178 // processes. Generally LLVM processes don't run very long and don't use very
179 // many temporary files so this shouldn't be a big issue for LLVM.
180 static time_t num = ::time(0);
181 char pathname[MAXPATHLEN];
182 do {
183 num++;
184 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
185 } while ( 0 == access(pathname, F_OK ) );
186 if (-1 == ::mkdir(pathname, S_IRWXU)) {
187 MakeErrMsg(ErrMsg,
188 std::string(pathname) + ": can't create temporary directory");
189 return Path();
190 }
191 Path result;
192 result.set(pathname);
193 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
194 return result;
195#endif
196}
197
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198void
199Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
200#ifdef LTDL_SHLIBPATH_VAR
201 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
202 if (env_var != 0) {
203 getPathList(env_var,Paths);
204 }
205#endif
206 // FIXME: Should this look at LD_LIBRARY_PATH too?
207 Paths.push_back(sys::Path("/usr/local/lib/"));
208 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
209 Paths.push_back(sys::Path("/usr/lib/"));
210 Paths.push_back(sys::Path("/lib/"));
211}
212
213void
214Path::GetBitcodeLibraryPaths(std::vector<sys::Path>& Paths) {
215 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
216 if (env_var != 0) {
217 getPathList(env_var,Paths);
218 }
219#ifdef LLVM_LIBDIR
220 {
221 Path tmpPath;
222 if (tmpPath.set(LLVM_LIBDIR))
223 if (tmpPath.canRead())
224 Paths.push_back(tmpPath);
225 }
226#endif
227 GetSystemLibraryPaths(Paths);
228}
229
230Path
231Path::GetLLVMDefaultConfigDir() {
232 return Path("/etc/llvm/");
233}
234
235Path
236Path::GetUserHomeDirectory() {
237 const char* home = getenv("HOME");
238 if (home) {
239 Path result;
240 if (result.set(home))
241 return result;
242 }
243 return GetRootDirectory();
244}
245
Ted Kremenekb05c9352007-12-18 22:07:33 +0000246Path
247Path::GetCurrentDirectory() {
248 char pathname[MAXPATHLEN];
249 if (!getcwd(pathname,MAXPATHLEN)) {
250 assert (false && "Could not query current working directory.");
251 return Path("");
252 }
253
254 return Path(pathname);
255}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256
Chris Lattner365f2202008-03-03 02:55:43 +0000257/// GetMainExecutable - Return the path to the main executable, given the
258/// value of argv[0] from program startup.
259Path Path::GetMainExecutable(const char *argv0, void *MainAddr) {
Chris Lattnerc9aca312008-03-13 05:22:05 +0000260#if defined(__CYGWIN__)
261 char exe_link[64];
262 snprintf(exe_link, sizeof(exe_link), "/proc/%d/exe", getpid());
263 char exe_path[MAXPATHLEN];
264 ssize_t len = readlink(exe_link, exe_path, sizeof(exe_path));
265 if (len > 0 && len < MAXPATHLEN - 1) {
266 exe_path[len] = '\0';
267 return Path(std::string(exe_path));
268 }
269#elif defined(HAVE_DLFCN_H)
Chris Lattner365f2202008-03-03 02:55:43 +0000270 // Use dladdr to get executable path if available.
Chris Lattner365f2202008-03-03 02:55:43 +0000271 Dl_info DLInfo;
272 int err = dladdr(MainAddr, &DLInfo);
273 if (err != 0)
274 return Path(std::string(DLInfo.dli_fname));
275#endif
276 return Path();
277}
278
279
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280std::string
281Path::getBasename() const {
282 // Find the last slash
283 size_t slash = path.rfind('/');
284 if (slash == std::string::npos)
285 slash = 0;
286 else
287 slash++;
288
289 size_t dot = path.rfind('.');
290 if (dot == std::string::npos || dot < slash)
291 return path.substr(slash);
292 else
293 return path.substr(slash, dot - slash);
294}
295
296bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
297 assert(len < 1024 && "Request for magic string too long");
298 char* buf = (char*) alloca(1 + len);
299 int fd = ::open(path.c_str(), O_RDONLY);
300 if (fd < 0)
301 return false;
302 ssize_t bytes_read = ::read(fd, buf, len);
303 ::close(fd);
304 if (ssize_t(len) != bytes_read) {
305 Magic.clear();
306 return false;
307 }
308 Magic.assign(buf,len);
309 return true;
310}
311
312bool
313Path::exists() const {
314 return 0 == access(path.c_str(), F_OK );
315}
316
317bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000318Path::isDirectory() const {
319 struct stat buf;
320 if (0 != stat(path.c_str(), &buf))
321 return false;
322 return buf.st_mode & S_IFDIR ? true : false;
323}
324
325bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326Path::canRead() const {
327 return 0 == access(path.c_str(), F_OK | R_OK );
328}
329
330bool
331Path::canWrite() const {
332 return 0 == access(path.c_str(), F_OK | W_OK );
333}
334
335bool
336Path::canExecute() const {
337 if (0 != access(path.c_str(), R_OK | X_OK ))
338 return false;
339 struct stat buf;
340 if (0 != stat(path.c_str(), &buf))
341 return false;
342 if (!S_ISREG(buf.st_mode))
343 return false;
344 return true;
345}
346
347std::string
348Path::getLast() const {
349 // Find the last slash
350 size_t pos = path.rfind('/');
351
352 // Handle the corner cases
353 if (pos == std::string::npos)
354 return path;
355
356 // If the last character is a slash
357 if (pos == path.length()-1) {
358 // Find the second to last slash
359 size_t pos2 = path.rfind('/', pos-1);
360 if (pos2 == std::string::npos)
361 return path.substr(0,pos);
362 else
363 return path.substr(pos2+1,pos-pos2-1);
364 }
365 // Return everything after the last slash
366 return path.substr(pos+1);
367}
368
369const FileStatus *
370PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
371 if (!fsIsValid || update) {
372 struct stat buf;
373 if (0 != stat(path.c_str(), &buf)) {
374 MakeErrMsg(ErrStr, path + ": can't get status of file");
375 return 0;
376 }
377 status.fileSize = buf.st_size;
378 status.modTime.fromEpochTime(buf.st_mtime);
379 status.mode = buf.st_mode;
380 status.user = buf.st_uid;
381 status.group = buf.st_gid;
382 status.uniqueID = uint64_t(buf.st_ino);
383 status.isDir = S_ISDIR(buf.st_mode);
384 status.isFile = S_ISREG(buf.st_mode);
385 fsIsValid = true;
386 }
387 return &status;
388}
389
390static bool AddPermissionBits(const Path &File, int bits) {
391 // Get the umask value from the operating system. We want to use it
392 // when changing the file's permissions. Since calling umask() sets
393 // the umask and returns its old value, we must call it a second
394 // time to reset it to the user's preference.
395 int mask = umask(0777); // The arg. to umask is arbitrary.
396 umask(mask); // Restore the umask.
397
398 // Get the file's current mode.
399 struct stat buf;
400 if (0 != stat(File.toString().c_str(), &buf))
401 return false;
402 // Change the file to have whichever permissions bits from 'bits'
403 // that the umask would not disable.
404 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
405 return false;
406 return true;
407}
408
409bool Path::makeReadableOnDisk(std::string* ErrMsg) {
410 if (!AddPermissionBits(*this, 0444))
411 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
412 return false;
413}
414
415bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
416 if (!AddPermissionBits(*this, 0222))
417 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
418 return false;
419}
420
421bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
422 if (!AddPermissionBits(*this, 0111))
423 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
424 return false;
425}
426
427bool
428Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
429 DIR* direntries = ::opendir(path.c_str());
430 if (direntries == 0)
431 return MakeErrMsg(ErrMsg, path + ": can't open directory");
432
433 std::string dirPath = path;
434 if (!lastIsSlash(dirPath))
435 dirPath += '/';
436
437 result.clear();
438 struct dirent* de = ::readdir(direntries);
439 for ( ; de != 0; de = ::readdir(direntries)) {
440 if (de->d_name[0] != '.') {
441 Path aPath(dirPath + (const char*)de->d_name);
442 struct stat st;
443 if (0 != lstat(aPath.path.c_str(), &st)) {
444 if (S_ISLNK(st.st_mode))
445 continue; // dangling symlink -- ignore
446 return MakeErrMsg(ErrMsg,
447 aPath.path + ": can't determine file object type");
448 }
449 result.insert(aPath);
450 }
451 }
452
453 closedir(direntries);
454 return false;
455}
456
457bool
458Path::set(const std::string& a_path) {
459 if (a_path.empty())
460 return false;
461 std::string save(path);
462 path = a_path;
463 if (!isValid()) {
464 path = save;
465 return false;
466 }
467 return true;
468}
469
470bool
471Path::appendComponent(const std::string& name) {
472 if (name.empty())
473 return false;
474 std::string save(path);
475 if (!lastIsSlash(path))
476 path += '/';
477 path += name;
478 if (!isValid()) {
479 path = save;
480 return false;
481 }
482 return true;
483}
484
485bool
486Path::eraseComponent() {
487 size_t slashpos = path.rfind('/',path.size());
488 if (slashpos == 0 || slashpos == std::string::npos) {
489 path.erase();
490 return true;
491 }
492 if (slashpos == path.size() - 1)
493 slashpos = path.rfind('/',slashpos-1);
494 if (slashpos == std::string::npos) {
495 path.erase();
496 return true;
497 }
498 path.erase(slashpos);
499 return true;
500}
501
502bool
503Path::appendSuffix(const std::string& suffix) {
504 std::string save(path);
505 path.append(".");
506 path.append(suffix);
507 if (!isValid()) {
508 path = save;
509 return false;
510 }
511 return true;
512}
513
514bool
515Path::eraseSuffix() {
516 std::string save = path;
517 size_t dotpos = path.rfind('.',path.size());
518 size_t slashpos = path.rfind('/',path.size());
519 if (dotpos != std::string::npos) {
520 if (slashpos == std::string::npos || dotpos > slashpos+1) {
521 path.erase(dotpos, path.size()-dotpos);
522 return true;
523 }
524 }
525 if (!isValid())
526 path = save;
527 return false;
528}
529
530bool
531Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
532 // Get a writeable copy of the path name
533 char pathname[MAXPATHLEN];
534 path.copy(pathname,MAXPATHLEN);
535
536 // Null-terminate the last component
537 int lastchar = path.length() - 1 ;
538 if (pathname[lastchar] == '/')
539 pathname[lastchar] = 0;
540 else
541 pathname[lastchar+1] = 0;
542
543 // If we're supposed to create intermediate directories
544 if ( create_parents ) {
545 // Find the end of the initial name component
546 char * next = strchr(pathname,'/');
547 if ( pathname[0] == '/')
548 next = strchr(&pathname[1],'/');
549
550 // Loop through the directory components until we're done
551 while ( next != 0 ) {
552 *next = 0;
553 if (0 != access(pathname, F_OK | R_OK | W_OK))
554 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
555 return MakeErrMsg(ErrMsg,
556 std::string(pathname) + ": can't create directory");
557 }
558 char* save = next;
559 next = strchr(next+1,'/');
560 *save = '/';
561 }
562 }
563
564 if (0 != access(pathname, F_OK | R_OK))
565 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG)) {
566 return MakeErrMsg(ErrMsg,
567 std::string(pathname) + ": can't create directory");
568 }
569 return false;
570}
571
572bool
573Path::createFileOnDisk(std::string* ErrMsg) {
574 // Create the file
575 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
576 if (fd < 0)
577 return MakeErrMsg(ErrMsg, path + ": can't create file");
578 ::close(fd);
579 return false;
580}
581
582bool
583Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
584 // Make this into a unique file name
585 if (makeUnique( reuse_current, ErrMsg ))
586 return true;
587
588 // create the file
589 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
590 if (fd < 0)
591 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
592 ::close(fd);
593 return false;
594}
595
596bool
597Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
598 // Get the status so we can determin if its a file or directory
599 struct stat buf;
600 if (0 != stat(path.c_str(), &buf)) {
601 MakeErrMsg(ErrStr, path + ": can't get status of file");
602 return true;
603 }
604
605 // Note: this check catches strange situations. In all cases, LLVM should
606 // only be involved in the creation and deletion of regular files. This
607 // check ensures that what we're trying to erase is a regular file. It
608 // effectively prevents LLVM from erasing things like /dev/null, any block
609 // special file, or other things that aren't "regular" files.
610 if (S_ISREG(buf.st_mode)) {
611 if (unlink(path.c_str()) != 0)
612 return MakeErrMsg(ErrStr, path + ": can't destroy file");
613 return false;
614 }
615
616 if (!S_ISDIR(buf.st_mode)) {
617 if (ErrStr) *ErrStr = "not a file or directory";
618 return true;
619 }
620
621 if (remove_contents) {
622 // Recursively descend the directory to remove its contents.
623 std::string cmd = "/bin/rm -rf " + path;
624 system(cmd.c_str());
625 return false;
626 }
627
628 // Otherwise, try to just remove the one directory.
629 char pathname[MAXPATHLEN];
630 path.copy(pathname, MAXPATHLEN);
631 int lastchar = path.length() - 1 ;
632 if (pathname[lastchar] == '/')
633 pathname[lastchar] = 0;
634 else
635 pathname[lastchar+1] = 0;
636
637 if (rmdir(pathname) != 0)
638 return MakeErrMsg(ErrStr,
639 std::string(pathname) + ": can't erase directory");
640 return false;
641}
642
643bool
644Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
645 if (0 != ::rename(path.c_str(), newName.c_str()))
646 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
647 newName.toString() + "' ");
648 return false;
649}
650
651bool
652Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
653 struct utimbuf utb;
654 utb.actime = si.modTime.toPosixTime();
655 utb.modtime = utb.actime;
656 if (0 != ::utime(path.c_str(),&utb))
657 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
658 if (0 != ::chmod(path.c_str(),si.mode))
659 return MakeErrMsg(ErrStr, path + ": can't set mode");
660 return false;
661}
662
663bool
664sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
665 int inFile = -1;
666 int outFile = -1;
667 inFile = ::open(Src.c_str(), O_RDONLY);
668 if (inFile == -1)
669 return MakeErrMsg(ErrMsg, Src.toString() +
670 ": can't open source file to copy");
671
672 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
673 if (outFile == -1) {
674 ::close(inFile);
675 return MakeErrMsg(ErrMsg, Dest.toString() +
676 ": can't create destination file for copy");
677 }
678
679 char Buffer[16*1024];
680 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
681 if (Amt == -1) {
682 if (errno != EINTR && errno != EAGAIN) {
683 ::close(inFile);
684 ::close(outFile);
685 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
686 }
687 } else {
688 char *BufPtr = Buffer;
689 while (Amt) {
690 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
691 if (AmtWritten == -1) {
692 if (errno != EINTR && errno != EAGAIN) {
693 ::close(inFile);
694 ::close(outFile);
695 return MakeErrMsg(ErrMsg, Dest.toString() +
696 ": can't write destination file: ");
697 }
698 } else {
699 Amt -= AmtWritten;
700 BufPtr += AmtWritten;
701 }
702 }
703 }
704 }
705 ::close(inFile);
706 ::close(outFile);
707 return false;
708}
709
710bool
711Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
712 if (reuse_current && !exists())
713 return false; // File doesn't exist already, just use it!
714
715 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
716 // mktemp or our own implementation.
717 char *FNBuffer = (char*) alloca(path.size()+8);
718 path.copy(FNBuffer,path.size());
719 strcpy(FNBuffer+path.size(), "-XXXXXX");
720
721#if defined(HAVE_MKSTEMP)
722 int TempFD;
723 if ((TempFD = mkstemp(FNBuffer)) == -1)
724 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
725
726 // We don't need to hold the temp file descriptor... we will trust that no one
727 // will overwrite/delete the file before we can open it again.
728 close(TempFD);
729
730 // Save the name
731 path = FNBuffer;
732#elif defined(HAVE_MKTEMP)
733 // If we don't have mkstemp, use the old and obsolete mktemp function.
734 if (mktemp(FNBuffer) == 0)
735 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
736
737 // Save the name
738 path = FNBuffer;
739#else
740 // Okay, looks like we have to do it all by our lonesome.
741 static unsigned FCounter = 0;
742 unsigned offset = path.size() + 1;
743 while ( FCounter < 999999 && exists()) {
744 sprintf(FNBuffer+offset,"%06u",++FCounter);
745 path = FNBuffer;
746 }
747 if (FCounter > 999999)
748 return MakeErrMsg(ErrMsg,
749 path + ": can't make unique filename: too many files");
750#endif
751 return false;
752}
753
Chris Lattner157d70a2008-04-01 06:00:12 +0000754const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000755 int Flags = MAP_PRIVATE;
756#ifdef MAP_FILE
757 Flags |= MAP_FILE;
758#endif
759 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
760 if (BasePtr == MAP_FAILED)
761 return 0;
Chris Lattner116abbf2008-04-01 06:25:23 +0000762 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000763}
764
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000765void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000766 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000767}
768
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769} // end llvm namespace
770