blob: aca4b936e87246c1479f9a3f2777520a6c4a2cf5 [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
Ted Kremenekb169dfa2008-04-07 22:01:32 +0000280std::string Path::getDirname() const {
281 return getDirnameCharSep(path, '/');
282}
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000283
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000284std::string
285Path::getBasename() const {
286 // Find the last slash
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000287 std::string::size_type slash = path.rfind('/');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 if (slash == std::string::npos)
289 slash = 0;
290 else
291 slash++;
292
Ted Kremenek4a4f5ed2008-04-07 21:53:57 +0000293 std::string::size_type dot = path.rfind('.');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 if (dot == std::string::npos || dot < slash)
295 return path.substr(slash);
296 else
297 return path.substr(slash, dot - slash);
298}
299
300bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
301 assert(len < 1024 && "Request for magic string too long");
302 char* buf = (char*) alloca(1 + len);
303 int fd = ::open(path.c_str(), O_RDONLY);
304 if (fd < 0)
305 return false;
306 ssize_t bytes_read = ::read(fd, buf, len);
307 ::close(fd);
308 if (ssize_t(len) != bytes_read) {
309 Magic.clear();
310 return false;
311 }
312 Magic.assign(buf,len);
313 return true;
314}
315
316bool
317Path::exists() const {
318 return 0 == access(path.c_str(), F_OK );
319}
320
321bool
Ted Kremenek65149be2007-12-18 19:46:22 +0000322Path::isDirectory() const {
323 struct stat buf;
324 if (0 != stat(path.c_str(), &buf))
325 return false;
326 return buf.st_mode & S_IFDIR ? true : false;
327}
328
329bool
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330Path::canRead() const {
331 return 0 == access(path.c_str(), F_OK | R_OK );
332}
333
334bool
335Path::canWrite() const {
336 return 0 == access(path.c_str(), F_OK | W_OK );
337}
338
339bool
340Path::canExecute() const {
341 if (0 != access(path.c_str(), R_OK | X_OK ))
342 return false;
343 struct stat buf;
344 if (0 != stat(path.c_str(), &buf))
345 return false;
346 if (!S_ISREG(buf.st_mode))
347 return false;
348 return true;
349}
350
351std::string
352Path::getLast() const {
353 // Find the last slash
354 size_t pos = path.rfind('/');
355
356 // Handle the corner cases
357 if (pos == std::string::npos)
358 return path;
359
360 // If the last character is a slash
361 if (pos == path.length()-1) {
362 // Find the second to last slash
363 size_t pos2 = path.rfind('/', pos-1);
364 if (pos2 == std::string::npos)
365 return path.substr(0,pos);
366 else
367 return path.substr(pos2+1,pos-pos2-1);
368 }
369 // Return everything after the last slash
370 return path.substr(pos+1);
371}
372
373const FileStatus *
374PathWithStatus::getFileStatus(bool update, std::string *ErrStr) const {
375 if (!fsIsValid || update) {
376 struct stat buf;
377 if (0 != stat(path.c_str(), &buf)) {
378 MakeErrMsg(ErrStr, path + ": can't get status of file");
379 return 0;
380 }
381 status.fileSize = buf.st_size;
382 status.modTime.fromEpochTime(buf.st_mtime);
383 status.mode = buf.st_mode;
384 status.user = buf.st_uid;
385 status.group = buf.st_gid;
386 status.uniqueID = uint64_t(buf.st_ino);
387 status.isDir = S_ISDIR(buf.st_mode);
388 status.isFile = S_ISREG(buf.st_mode);
389 fsIsValid = true;
390 }
391 return &status;
392}
393
394static bool AddPermissionBits(const Path &File, int bits) {
395 // Get the umask value from the operating system. We want to use it
396 // when changing the file's permissions. Since calling umask() sets
397 // the umask and returns its old value, we must call it a second
398 // time to reset it to the user's preference.
399 int mask = umask(0777); // The arg. to umask is arbitrary.
400 umask(mask); // Restore the umask.
401
402 // Get the file's current mode.
403 struct stat buf;
404 if (0 != stat(File.toString().c_str(), &buf))
405 return false;
406 // Change the file to have whichever permissions bits from 'bits'
407 // that the umask would not disable.
408 if ((chmod(File.c_str(), (buf.st_mode | (bits & ~mask)))) == -1)
409 return false;
410 return true;
411}
412
413bool Path::makeReadableOnDisk(std::string* ErrMsg) {
414 if (!AddPermissionBits(*this, 0444))
415 return MakeErrMsg(ErrMsg, path + ": can't make file readable");
416 return false;
417}
418
419bool Path::makeWriteableOnDisk(std::string* ErrMsg) {
420 if (!AddPermissionBits(*this, 0222))
421 return MakeErrMsg(ErrMsg, path + ": can't make file writable");
422 return false;
423}
424
425bool Path::makeExecutableOnDisk(std::string* ErrMsg) {
426 if (!AddPermissionBits(*this, 0111))
427 return MakeErrMsg(ErrMsg, path + ": can't make file executable");
428 return false;
429}
430
431bool
432Path::getDirectoryContents(std::set<Path>& result, std::string* ErrMsg) const {
433 DIR* direntries = ::opendir(path.c_str());
434 if (direntries == 0)
435 return MakeErrMsg(ErrMsg, path + ": can't open directory");
436
437 std::string dirPath = path;
438 if (!lastIsSlash(dirPath))
439 dirPath += '/';
440
441 result.clear();
442 struct dirent* de = ::readdir(direntries);
443 for ( ; de != 0; de = ::readdir(direntries)) {
444 if (de->d_name[0] != '.') {
445 Path aPath(dirPath + (const char*)de->d_name);
446 struct stat st;
447 if (0 != lstat(aPath.path.c_str(), &st)) {
448 if (S_ISLNK(st.st_mode))
449 continue; // dangling symlink -- ignore
450 return MakeErrMsg(ErrMsg,
451 aPath.path + ": can't determine file object type");
452 }
453 result.insert(aPath);
454 }
455 }
456
457 closedir(direntries);
458 return false;
459}
460
461bool
462Path::set(const std::string& a_path) {
463 if (a_path.empty())
464 return false;
465 std::string save(path);
466 path = a_path;
467 if (!isValid()) {
468 path = save;
469 return false;
470 }
471 return true;
472}
473
474bool
475Path::appendComponent(const std::string& name) {
476 if (name.empty())
477 return false;
478 std::string save(path);
479 if (!lastIsSlash(path))
480 path += '/';
481 path += name;
482 if (!isValid()) {
483 path = save;
484 return false;
485 }
486 return true;
487}
488
489bool
490Path::eraseComponent() {
491 size_t slashpos = path.rfind('/',path.size());
492 if (slashpos == 0 || slashpos == std::string::npos) {
493 path.erase();
494 return true;
495 }
496 if (slashpos == path.size() - 1)
497 slashpos = path.rfind('/',slashpos-1);
498 if (slashpos == std::string::npos) {
499 path.erase();
500 return true;
501 }
502 path.erase(slashpos);
503 return true;
504}
505
506bool
507Path::appendSuffix(const std::string& suffix) {
508 std::string save(path);
509 path.append(".");
510 path.append(suffix);
511 if (!isValid()) {
512 path = save;
513 return false;
514 }
515 return true;
516}
517
518bool
519Path::eraseSuffix() {
520 std::string save = path;
521 size_t dotpos = path.rfind('.',path.size());
522 size_t slashpos = path.rfind('/',path.size());
523 if (dotpos != std::string::npos) {
524 if (slashpos == std::string::npos || dotpos > slashpos+1) {
525 path.erase(dotpos, path.size()-dotpos);
526 return true;
527 }
528 }
529 if (!isValid())
530 path = save;
531 return false;
532}
533
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000534static bool createDirectoryHelper(char* beg, char* end, bool create_parents) {
535
536 if (access(beg, F_OK | R_OK | W_OK) == 0)
537 return false;
538
539 if (create_parents) {
540
541 char* c = end;
542
543 for (; c != beg; --c)
544 if (*c == '/') {
545
546 // Recurse to handling the parent directory.
547 *c = '\0';
548 bool x = createDirectoryHelper(beg, c, create_parents);
549 *c = '/';
550
551 // Return if we encountered an error.
552 if (x)
553 return true;
554
555 break;
556 }
557 }
558
559 return mkdir(beg, S_IRWXU | S_IRWXG) != 0;
560}
561
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562bool
563Path::createDirectoryOnDisk( bool create_parents, std::string* ErrMsg ) {
564 // Get a writeable copy of the path name
565 char pathname[MAXPATHLEN];
566 path.copy(pathname,MAXPATHLEN);
567
568 // Null-terminate the last component
Ted Kremenekf8cce7d2008-04-03 16:11:31 +0000569 int lastchar = path.length() - 1 ;
570
571 if (pathname[lastchar] != '/')
572 ++lastchar;
573
574 pathname[lastchar] = 0;
575
576 if (createDirectoryHelper(pathname, pathname+lastchar, create_parents))
577 return MakeErrMsg(ErrMsg,
578 std::string(pathname) + ": can't create directory");
579
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580 return false;
581}
582
583bool
584Path::createFileOnDisk(std::string* ErrMsg) {
585 // Create the file
586 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
587 if (fd < 0)
588 return MakeErrMsg(ErrMsg, path + ": can't create file");
589 ::close(fd);
590 return false;
591}
592
593bool
594Path::createTemporaryFileOnDisk(bool reuse_current, std::string* ErrMsg) {
595 // Make this into a unique file name
596 if (makeUnique( reuse_current, ErrMsg ))
597 return true;
598
599 // create the file
600 int fd = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
601 if (fd < 0)
602 return MakeErrMsg(ErrMsg, path + ": can't create temporary file");
603 ::close(fd);
604 return false;
605}
606
607bool
608Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
609 // Get the status so we can determin if its a file or directory
610 struct stat buf;
611 if (0 != stat(path.c_str(), &buf)) {
612 MakeErrMsg(ErrStr, path + ": can't get status of file");
613 return true;
614 }
615
616 // Note: this check catches strange situations. In all cases, LLVM should
617 // only be involved in the creation and deletion of regular files. This
618 // check ensures that what we're trying to erase is a regular file. It
619 // effectively prevents LLVM from erasing things like /dev/null, any block
620 // special file, or other things that aren't "regular" files.
621 if (S_ISREG(buf.st_mode)) {
622 if (unlink(path.c_str()) != 0)
623 return MakeErrMsg(ErrStr, path + ": can't destroy file");
624 return false;
625 }
626
627 if (!S_ISDIR(buf.st_mode)) {
628 if (ErrStr) *ErrStr = "not a file or directory";
629 return true;
630 }
631
632 if (remove_contents) {
633 // Recursively descend the directory to remove its contents.
634 std::string cmd = "/bin/rm -rf " + path;
635 system(cmd.c_str());
636 return false;
637 }
638
639 // Otherwise, try to just remove the one directory.
640 char pathname[MAXPATHLEN];
641 path.copy(pathname, MAXPATHLEN);
642 int lastchar = path.length() - 1 ;
643 if (pathname[lastchar] == '/')
644 pathname[lastchar] = 0;
645 else
646 pathname[lastchar+1] = 0;
647
648 if (rmdir(pathname) != 0)
649 return MakeErrMsg(ErrStr,
650 std::string(pathname) + ": can't erase directory");
651 return false;
652}
653
654bool
655Path::renamePathOnDisk(const Path& newName, std::string* ErrMsg) {
656 if (0 != ::rename(path.c_str(), newName.c_str()))
657 return MakeErrMsg(ErrMsg, std::string("can't rename '") + path + "' as '" +
658 newName.toString() + "' ");
659 return false;
660}
661
662bool
663Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
664 struct utimbuf utb;
665 utb.actime = si.modTime.toPosixTime();
666 utb.modtime = utb.actime;
667 if (0 != ::utime(path.c_str(),&utb))
668 return MakeErrMsg(ErrStr, path + ": can't set file modification time");
669 if (0 != ::chmod(path.c_str(),si.mode))
670 return MakeErrMsg(ErrStr, path + ": can't set mode");
671 return false;
672}
673
674bool
675sys::CopyFile(const sys::Path &Dest, const sys::Path &Src, std::string* ErrMsg){
676 int inFile = -1;
677 int outFile = -1;
678 inFile = ::open(Src.c_str(), O_RDONLY);
679 if (inFile == -1)
680 return MakeErrMsg(ErrMsg, Src.toString() +
681 ": can't open source file to copy");
682
683 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
684 if (outFile == -1) {
685 ::close(inFile);
686 return MakeErrMsg(ErrMsg, Dest.toString() +
687 ": can't create destination file for copy");
688 }
689
690 char Buffer[16*1024];
691 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
692 if (Amt == -1) {
693 if (errno != EINTR && errno != EAGAIN) {
694 ::close(inFile);
695 ::close(outFile);
696 return MakeErrMsg(ErrMsg, Src.toString()+": can't read source file: ");
697 }
698 } else {
699 char *BufPtr = Buffer;
700 while (Amt) {
701 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
702 if (AmtWritten == -1) {
703 if (errno != EINTR && errno != EAGAIN) {
704 ::close(inFile);
705 ::close(outFile);
706 return MakeErrMsg(ErrMsg, Dest.toString() +
707 ": can't write destination file: ");
708 }
709 } else {
710 Amt -= AmtWritten;
711 BufPtr += AmtWritten;
712 }
713 }
714 }
715 }
716 ::close(inFile);
717 ::close(outFile);
718 return false;
719}
720
721bool
722Path::makeUnique(bool reuse_current, std::string* ErrMsg) {
723 if (reuse_current && !exists())
724 return false; // File doesn't exist already, just use it!
725
726 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
727 // mktemp or our own implementation.
728 char *FNBuffer = (char*) alloca(path.size()+8);
729 path.copy(FNBuffer,path.size());
730 strcpy(FNBuffer+path.size(), "-XXXXXX");
731
732#if defined(HAVE_MKSTEMP)
733 int TempFD;
734 if ((TempFD = mkstemp(FNBuffer)) == -1)
735 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
736
737 // We don't need to hold the temp file descriptor... we will trust that no one
738 // will overwrite/delete the file before we can open it again.
739 close(TempFD);
740
741 // Save the name
742 path = FNBuffer;
743#elif defined(HAVE_MKTEMP)
744 // If we don't have mkstemp, use the old and obsolete mktemp function.
745 if (mktemp(FNBuffer) == 0)
746 return MakeErrMsg(ErrMsg, path + ": can't make unique filename");
747
748 // Save the name
749 path = FNBuffer;
750#else
751 // Okay, looks like we have to do it all by our lonesome.
752 static unsigned FCounter = 0;
753 unsigned offset = path.size() + 1;
754 while ( FCounter < 999999 && exists()) {
755 sprintf(FNBuffer+offset,"%06u",++FCounter);
756 path = FNBuffer;
757 }
758 if (FCounter > 999999)
759 return MakeErrMsg(ErrMsg,
760 path + ": can't make unique filename: too many files");
761#endif
762 return false;
763}
764
Chris Lattner157d70a2008-04-01 06:00:12 +0000765const char *Path::MapInFilePages(int FD, uint64_t FileSize) {
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000766 int Flags = MAP_PRIVATE;
767#ifdef MAP_FILE
768 Flags |= MAP_FILE;
769#endif
770 void *BasePtr = ::mmap(0, FileSize, PROT_READ, Flags, FD, 0);
771 if (BasePtr == MAP_FAILED)
772 return 0;
Chris Lattner116abbf2008-04-01 06:25:23 +0000773 return (const char*)BasePtr;
Chris Lattner157d70a2008-04-01 06:00:12 +0000774}
775
Chris Lattner7bbb6d62008-04-01 06:16:24 +0000776void Path::UnMapFilePages(const char *BasePtr, uint64_t FileSize) {
Chris Lattner116abbf2008-04-01 06:25:23 +0000777 ::munmap((void*)BasePtr, FileSize);
Chris Lattner157d70a2008-04-01 06:00:12 +0000778}
779
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000780} // end llvm namespace
781