blob: f26315cea623049633eb3bc6e98e144e088f22db [file] [log] [blame]
Reid Spencer814ba572004-08-25 06:20:07 +00001//===- llvm/System/Unix/Path.cpp - Unix Path Implementation -----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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
Reid Spencer6df221d2004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencer814ba572004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukmanf06cb1d2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencer814ba572004-08-25 06:20:07 +000020#include "Unix.h"
Reid Spencerd103e082004-12-27 06:17:15 +000021#if HAVE_SYS_STAT_H
Reid Spencer814ba572004-08-25 06:20:07 +000022#include <sys/stat.h>
Reid Spencerd103e082004-12-27 06:17:15 +000023#endif
24#if HAVE_FCNTL_H
Reid Spencer814ba572004-08-25 06:20:07 +000025#include <fcntl.h>
Reid Spencerd103e082004-12-27 06:17:15 +000026#endif
27#if HAVE_UTIME_H
Reid Spencerc1d474f2004-11-14 22:08:36 +000028#include <utime.h>
Reid Spencerd103e082004-12-27 06:17:15 +000029#endif
30#if HAVE_TIME_H
Reid Spencer20540312004-12-24 06:29:42 +000031#include <time.h>
Reid Spencerd103e082004-12-27 06:17:15 +000032#endif
33#if HAVE_DIRENT_H
34# include <dirent.h>
35# define NAMLEN(dirent) strlen((dirent)->d_name)
36#else
37# define dirent direct
38# define NAMLEN(dirent) (dirent)->d_namlen
39# if HAVE_SYS_NDIR_H
40# include <sys/ndir.h>
41# endif
42# if HAVE_SYS_DIR_H
43# include <sys/dir.h>
44# endif
45# if HAVE_NDIR_H
46# include <ndir.h>
47# endif
48#endif
49
Reid Spencerd1ef1df2005-06-02 05:38:20 +000050// Put in a hack for Cygwin which falsely reports that the mkdtemp function
51// is available when it is not.
52#ifdef __CYGWIN__
53# undef HAVE_MKDTEMP
54#endif
Reid Spencer814ba572004-08-25 06:20:07 +000055
Reid Spencer29f83e02005-07-28 16:25:57 +000056namespace {
57inline bool lastIsSlash(const std::string& path) {
58 return !path.empty() && path[path.length() - 1] == '/';
59}
60
61}
62
Reid Spencer6df221d2004-08-29 05:24:01 +000063namespace llvm {
64using namespace sys;
Reid Spencer814ba572004-08-25 06:20:07 +000065
Misha Brukmanf06cb1d2004-12-20 00:16:38 +000066Path::Path(const std::string& unverified_path) : path(unverified_path) {
Reid Spencer6df221d2004-08-29 05:24:01 +000067 if (unverified_path.empty())
68 return;
Reid Spencer0c6a2832004-11-05 22:15:36 +000069 if (this->isValid())
Reid Spencer6df221d2004-08-29 05:24:01 +000070 return;
71 // oops, not valid.
72 path.clear();
73 ThrowErrno(unverified_path + ": path is not valid");
Reid Spencer814ba572004-08-25 06:20:07 +000074}
75
Reid Spencer20540312004-12-24 06:29:42 +000076bool
77Path::isValid() const {
Reid Spencerd28e432c2005-07-08 06:53:26 +000078 // Check some obvious things
Reid Spencer20540312004-12-24 06:29:42 +000079 if (path.empty())
80 return false;
81 else if (path.length() >= MAXPATHLEN)
82 return false;
Reid Spencerd28e432c2005-07-08 06:53:26 +000083
84 // Check that the characters are ascii chars
85 size_t len = path.length();
86 unsigned i = 0;
87 while (i < len && isascii(path[i]))
88 ++i;
89 return i >= len;
Reid Spencer20540312004-12-24 06:29:42 +000090}
91
Reid Spencer6df221d2004-08-29 05:24:01 +000092Path
93Path::GetRootDirectory() {
94 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +000095 result.set("/");
Reid Spencer6df221d2004-08-29 05:24:01 +000096 return result;
97}
98
Reid Spencer20540312004-12-24 06:29:42 +000099Path
100Path::GetTemporaryDirectory() {
101#if defined(HAVE_MKDTEMP)
102 // The best way is with mkdtemp but that's not available on many systems,
103 // Linux and FreeBSD have it. Others probably won't.
104 char pathname[MAXPATHLEN];
105 strcpy(pathname,"/tmp/llvm_XXXXXX");
106 if (0 == mkdtemp(pathname))
Reid Spencer8424ba32005-04-21 02:50:10 +0000107 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000108 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000109 result.set(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000110 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
111 return result;
112#elif defined(HAVE_MKSTEMP)
113 // If no mkdtemp is available, mkstemp can be used to create a temporary file
114 // which is then removed and created as a directory. We prefer this over
115 // mktemp because of mktemp's inherent security and threading risks. We still
116 // have a slight race condition from the time the temporary file is created to
117 // the time it is re-created as a directoy.
118 char pathname[MAXPATHLEN];
119 strcpy(pathname, "/tmp/llvm_XXXXXX");
120 int fd = 0;
121 if (-1 == (fd = mkstemp(pathname)))
Reid Spencer8424ba32005-04-21 02:50:10 +0000122 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000123 ::close(fd);
124 ::unlink(pathname); // start race condition, ignore errors
125 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
Reid Spencer8424ba32005-04-21 02:50:10 +0000126 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000127 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000128 result.set(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000129 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
130 return result;
131#elif defined(HAVE_MKTEMP)
132 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
133 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
134 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
135 // the XXXXXX with the pid of the process and a letter. That leads to only
136 // twenty six temporary files that can be generated.
137 char pathname[MAXPATHLEN];
138 strcpy(pathname, "/tmp/llvm_XXXXXX");
139 char *TmpName = ::mktemp(pathname);
140 if (TmpName == 0)
Reid Spencer8424ba32005-04-21 02:50:10 +0000141 ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
Reid Spencer20540312004-12-24 06:29:42 +0000142 if (-1 == ::mkdir(TmpName, S_IRWXU))
Reid Spencer8424ba32005-04-21 02:50:10 +0000143 ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000144 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000145 result.set(TmpName);
Reid Spencer20540312004-12-24 06:29:42 +0000146 assert(result.isValid() && "mktemp didn't create a valid pathname!");
147 return result;
148#else
149 // This is the worst case implementation. tempnam(3) leaks memory unless its
150 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
151 // issues. The mktemp(3) function doesn't have enough variability in the
152 // temporary name generated. So, we provide our own implementation that
153 // increments an integer from a random number seeded by the current time. This
154 // should be sufficiently unique that we don't have many collisions between
155 // processes. Generally LLVM processes don't run very long and don't use very
156 // many temporary files so this shouldn't be a big issue for LLVM.
157 static time_t num = ::time(0);
158 char pathname[MAXPATHLEN];
159 do {
160 num++;
161 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
162 } while ( 0 == access(pathname, F_OK ) );
163 if (-1 == ::mkdir(pathname, S_IRWXU))
Reid Spencer8424ba32005-04-21 02:50:10 +0000164 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000165 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000166 result.set(pathname);
Reid Spencer20540312004-12-24 06:29:42 +0000167 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
168 return result;
169#endif
170}
171
Reid Spencer9b155dc2004-12-13 03:00:51 +0000172static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
173 const char* at = path;
174 const char* delim = strchr(at, ':');
175 Path tmpPath;
176 while( delim != 0 ) {
177 std::string tmp(at, size_t(delim-at));
Reid Spencerc9c04732005-07-07 23:21:43 +0000178 if (tmpPath.set(tmp))
Reid Spencer5b891e92005-07-07 18:21:42 +0000179 if (tmpPath.canRead())
Reid Spencer9b155dc2004-12-13 03:00:51 +0000180 Paths.push_back(tmpPath);
181 at = delim + 1;
182 delim = strchr(at, ':');
Reid Spencerdf05ec72004-09-14 00:16:39 +0000183 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000184 if (*at != 0)
Reid Spencerc9c04732005-07-07 23:21:43 +0000185 if (tmpPath.set(std::string(at)))
Reid Spencer5b891e92005-07-07 18:21:42 +0000186 if (tmpPath.canRead())
Reid Spencer9b155dc2004-12-13 03:00:51 +0000187 Paths.push_back(tmpPath);
188
Reid Spencerdf05ec72004-09-14 00:16:39 +0000189}
Misha Brukmanf06cb1d2004-12-20 00:16:38 +0000190
Reid Spencer9b155dc2004-12-13 03:00:51 +0000191void
192Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
193#ifdef LTDL_SHLIBPATH_VAR
194 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
195 if (env_var != 0) {
196 getPathList(env_var,Paths);
Reid Spencerdf05ec72004-09-14 00:16:39 +0000197 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000198#endif
199 // FIXME: Should this look at LD_LIBRARY_PATH too?
200 Paths.push_back(sys::Path("/usr/local/lib/"));
201 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
202 Paths.push_back(sys::Path("/usr/lib/"));
203 Paths.push_back(sys::Path("/lib/"));
Reid Spencerdf05ec72004-09-14 00:16:39 +0000204}
205
Reid Spencer9b155dc2004-12-13 03:00:51 +0000206void
207Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
208 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
209 if (env_var != 0) {
210 getPathList(env_var,Paths);
211 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000212#ifdef LLVM_LIBDIR
213 {
214 Path tmpPath;
Reid Spencerc9c04732005-07-07 23:21:43 +0000215 if (tmpPath.set(LLVM_LIBDIR))
Reid Spencer5b891e92005-07-07 18:21:42 +0000216 if (tmpPath.canRead())
Reid Spencer9b155dc2004-12-13 03:00:51 +0000217 Paths.push_back(tmpPath);
218 }
219#endif
220 GetSystemLibraryPaths(Paths);
Reid Spencer6df221d2004-08-29 05:24:01 +0000221}
222
223Path
224Path::GetLLVMDefaultConfigDir() {
225 return Path("/etc/llvm/");
226}
227
Reid Spencer6df221d2004-08-29 05:24:01 +0000228Path
229Path::GetUserHomeDirectory() {
230 const char* home = getenv("HOME");
231 if (home) {
232 Path result;
Reid Spencerc9c04732005-07-07 23:21:43 +0000233 if (result.set(home))
Reid Spencer6df221d2004-08-29 05:24:01 +0000234 return result;
235 }
236 return GetRootDirectory();
237}
238
239bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000240Path::isFile() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000241 if (!exists())
242 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000243 struct stat buf;
244 if (0 != stat(path.c_str(), &buf)) {
245 ThrowErrno(path + ": can't determine type of path object: ");
246 }
247 return S_ISREG(buf.st_mode);
Reid Spencerae9bbda2004-09-11 04:55:08 +0000248}
249
250bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000251Path::isDirectory() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000252 if (!exists())
253 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000254 struct stat buf;
255 if (0 != stat(path.c_str(), &buf)) {
256 ThrowErrno(path + ": can't determine type of path object: ");
257 }
258 return S_ISDIR(buf.st_mode);
Reid Spencerae9bbda2004-09-11 04:55:08 +0000259}
260
Reid Spenceraf48d862005-07-08 03:08:58 +0000261bool
262Path::isHidden() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000263 if (!exists())
264 return false;
Reid Spenceraf48d862005-07-08 03:08:58 +0000265 size_t slash = path.rfind('/');
266 return (slash != std::string::npos &&
267 slash < path.length()-1 &&
268 path[slash+1] == '.') ||
269 (!path.empty() && slash == std::string::npos && path[0] == '.');
270}
271
Reid Spencerae9bbda2004-09-11 04:55:08 +0000272std::string
Reid Spencer0c6a2832004-11-05 22:15:36 +0000273Path::getBasename() const {
Reid Spencerae9bbda2004-09-11 04:55:08 +0000274 // Find the last slash
275 size_t slash = path.rfind('/');
276 if (slash == std::string::npos)
277 slash = 0;
278 else
279 slash++;
280
Jeff Cohen5b106d02005-07-09 18:42:02 +0000281 size_t dot = path.rfind('.');
282 if (dot == std::string::npos || dot < slash)
283 return path.substr(slash);
284 else
285 return path.substr(slash, dot - slash);
Reid Spencerae9bbda2004-09-11 04:55:08 +0000286}
287
Reid Spencer0c6a2832004-11-05 22:15:36 +0000288bool Path::hasMagicNumber(const std::string &Magic) const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000289 if (!isFile())
290 return false;
Reid Spencerae9bbda2004-09-11 04:55:08 +0000291 size_t len = Magic.size();
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000292 assert(len < 1024 && "Request for magic string too long");
293 char* buf = (char*) alloca(1 + len);
294 int fd = ::open(path.c_str(),O_RDONLY);
295 if (fd < 0)
296 return false;
Reid Spencer9b155dc2004-12-13 03:00:51 +0000297 size_t read_len = ::read(fd, buf, len);
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000298 close(fd);
Reid Spencer9b155dc2004-12-13 03:00:51 +0000299 if (len != read_len)
300 return false;
Reid Spencerae9bbda2004-09-11 04:55:08 +0000301 buf[len] = '\0';
302 return Magic == buf;
303}
304
Reid Spencerc1d474f2004-11-14 22:08:36 +0000305bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
306 if (!isFile())
307 return false;
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000308 assert(len < 1024 && "Request for magic string too long");
309 char* buf = (char*) alloca(1 + len);
310 int fd = ::open(path.c_str(),O_RDONLY);
311 if (fd < 0)
312 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000313 ssize_t bytes_read = ::read(fd, buf, len);
314 ::close(fd);
315 if (ssize_t(len) != bytes_read) {
316 Magic.clear();
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000317 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000318 }
319 Magic.assign(buf,len);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000320 return true;
321}
322
Reid Spencerae9bbda2004-09-11 04:55:08 +0000323bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000324Path::isBytecodeFile() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000325 if (!isFile())
326 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000327 char buffer[ 4];
328 buffer[0] = 0;
Reid Spencer5ccfd5a2004-12-11 00:14:15 +0000329 int fd = ::open(path.c_str(),O_RDONLY);
330 if (fd < 0)
331 return false;
332 ssize_t bytes_read = ::read(fd, buffer, 4);
333 ::close(fd);
334 if (4 != bytes_read)
335 return false;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000336
337 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
338 (buffer[3] == 'c' || buffer[3] == 'm'));
Reid Spencerae9bbda2004-09-11 04:55:08 +0000339}
340
341bool
Reid Spencer6df221d2004-08-29 05:24:01 +0000342Path::exists() const {
343 return 0 == access(path.c_str(), F_OK );
344}
345
346bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000347Path::canRead() const {
Reid Spencer6df221d2004-08-29 05:24:01 +0000348 return 0 == access(path.c_str(), F_OK | R_OK );
349}
350
351bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000352Path::canWrite() const {
Reid Spencer6df221d2004-08-29 05:24:01 +0000353 return 0 == access(path.c_str(), F_OK | W_OK );
354}
355
356bool
Reid Spencer5b891e92005-07-07 18:21:42 +0000357Path::canExecute() const {
Reid Spencer2d85f562005-07-08 17:46:10 +0000358 if (0 != access(path.c_str(), R_OK | X_OK ))
359 return false;
Misha Brukmana9a8c1b2005-04-20 15:33:22 +0000360 struct stat st;
361 int r = stat(path.c_str(), &st);
362 if (r != 0 || !S_ISREG(st.st_mode))
363 return false;
Reid Spencer2d85f562005-07-08 17:46:10 +0000364 return true;
Reid Spencer6df221d2004-08-29 05:24:01 +0000365}
366
367std::string
368Path::getLast() const {
369 // Find the last slash
370 size_t pos = path.rfind('/');
371
372 // Handle the corner cases
373 if (pos == std::string::npos)
374 return path;
375
376 // If the last character is a slash
377 if (pos == path.length()-1) {
378 // Find the second to last slash
379 size_t pos2 = path.rfind('/', pos-1);
380 if (pos2 == std::string::npos)
381 return path.substr(0,pos);
382 else
383 return path.substr(pos2+1,pos-pos2-1);
384 }
385 // Return everything after the last slash
386 return path.substr(pos+1);
387}
388
Chris Lattner48572532006-07-28 22:03:44 +0000389bool
390Path::getFileStatus(FileStatus &info, std::string *ErrStr) const {
Reid Spencerfb1f7352004-11-09 20:26:31 +0000391 struct stat buf;
Chris Lattner48572532006-07-28 22:03:44 +0000392 if (0 != stat(path.c_str(), &buf))
393 return GetErrno(path + ": can't determine type of path object: ", ErrStr);
Reid Spencerfb1f7352004-11-09 20:26:31 +0000394 info.fileSize = buf.st_size;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000395 info.modTime.fromEpochTime(buf.st_mtime);
Reid Spencerfb1f7352004-11-09 20:26:31 +0000396 info.mode = buf.st_mode;
397 info.user = buf.st_uid;
398 info.group = buf.st_gid;
Chris Lattner48572532006-07-28 22:03:44 +0000399 info.isDir = S_ISDIR(buf.st_mode);
400 info.isFile = S_ISREG(buf.st_mode);
401 return false;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000402}
403
Chris Lattner48572532006-07-28 22:03:44 +0000404static bool AddPermissionBits(const Path &File, int bits) {
Reid Spencer94bf2262004-12-13 19:59:50 +0000405 // Get the umask value from the operating system. We want to use it
406 // when changing the file's permissions. Since calling umask() sets
407 // the umask and returns its old value, we must call it a second
408 // time to reset it to the user's preference.
409 int mask = umask(0777); // The arg. to umask is arbitrary.
410 umask(mask); // Restore the umask.
411
412 // Get the file's current mode.
Chris Lattner48572532006-07-28 22:03:44 +0000413 FileStatus Stat;
414 if (File.getFileStatus(Stat)) return false;
Reid Spencer94bf2262004-12-13 19:59:50 +0000415
416 // Change the file to have whichever permissions bits from 'bits'
417 // that the umask would not disable.
Chris Lattner48572532006-07-28 22:03:44 +0000418 if ((chmod(File.c_str(), (Stat.getMode() | (bits & ~mask)))) == -1)
Reid Spencer94bf2262004-12-13 19:59:50 +0000419 return false;
420
421 return true;
422}
423
Reid Spenceraf48d862005-07-08 03:08:58 +0000424void Path::makeReadableOnDisk() {
Chris Lattner48572532006-07-28 22:03:44 +0000425 if (!AddPermissionBits(*this, 0444))
Reid Spencer94bf2262004-12-13 19:59:50 +0000426 ThrowErrno(path + ": can't make file readable");
427}
428
Reid Spenceraf48d862005-07-08 03:08:58 +0000429void Path::makeWriteableOnDisk() {
Chris Lattner48572532006-07-28 22:03:44 +0000430 if (!AddPermissionBits(*this, 0222))
Reid Spencer94bf2262004-12-13 19:59:50 +0000431 ThrowErrno(path + ": can't make file writable");
432}
433
Reid Spenceraf48d862005-07-08 03:08:58 +0000434void Path::makeExecutableOnDisk() {
Chris Lattner48572532006-07-28 22:03:44 +0000435 if (!AddPermissionBits(*this, 0111))
Reid Spencer94bf2262004-12-13 19:59:50 +0000436 ThrowErrno(path + ": can't make file executable");
437}
438
Reid Spencerc1d474f2004-11-14 22:08:36 +0000439bool
Reid Spencer91f505e2004-11-16 06:15:19 +0000440Path::getDirectoryContents(std::set<Path>& result) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000441 if (!isDirectory())
442 return false;
443 DIR* direntries = ::opendir(path.c_str());
444 if (direntries == 0)
445 ThrowErrno(path + ": can't open directory");
446
Reid Spencer29f83e02005-07-28 16:25:57 +0000447 std::string dirPath = path;
448 if (!lastIsSlash(dirPath))
449 dirPath += '/';
450
Reid Spencerc1d474f2004-11-14 22:08:36 +0000451 result.clear();
452 struct dirent* de = ::readdir(direntries);
Misha Brukman1001aea2005-04-20 04:04:07 +0000453 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000454 if (de->d_name[0] != '.') {
Reid Spencer29f83e02005-07-28 16:25:57 +0000455 Path aPath(dirPath + (const char*)de->d_name);
Chris Lattner0b2890e2006-07-07 21:21:06 +0000456 struct stat st;
457 if (0 != lstat(aPath.path.c_str(), &st)) {
458 if (S_ISLNK(st.st_mode))
Misha Brukman1001aea2005-04-20 04:04:07 +0000459 continue; // dangling symlink -- ignore
Chris Lattner0b2890e2006-07-07 21:21:06 +0000460 ThrowErrno(aPath.path + ": can't determine file object type");
Misha Brukman1001aea2005-04-20 04:04:07 +0000461 }
Reid Spencer91f505e2004-11-16 06:15:19 +0000462 result.insert(aPath);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000463 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000464 }
465
466 closedir(direntries);
467 return true;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000468}
469
Reid Spencer6df221d2004-08-29 05:24:01 +0000470bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000471Path::set(const std::string& a_path) {
472 if (a_path.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000473 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000474 std::string save(path);
Reid Spencer6df221d2004-08-29 05:24:01 +0000475 path = a_path;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000476 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000477 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000478 return false;
479 }
480 return true;
481}
482
483bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000484Path::appendComponent(const std::string& name) {
485 if (name.empty())
Reid Spencer6df221d2004-08-29 05:24:01 +0000486 return false;
Reid Spencerc9c04732005-07-07 23:21:43 +0000487 std::string save(path);
Reid Spencer29f83e02005-07-28 16:25:57 +0000488 if (!lastIsSlash(path))
489 path += '/';
Reid Spencerc9c04732005-07-07 23:21:43 +0000490 path += name;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000491 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000492 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000493 return false;
494 }
495 return true;
496}
497
498bool
Reid Spencerc9c04732005-07-07 23:21:43 +0000499Path::eraseComponent() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000500 size_t slashpos = path.rfind('/',path.size());
Reid Spencerc9c04732005-07-07 23:21:43 +0000501 if (slashpos == 0 || slashpos == std::string::npos) {
502 path.erase();
503 return true;
504 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000505 if (slashpos == path.size() - 1)
506 slashpos = path.rfind('/',slashpos-1);
Reid Spencerc9c04732005-07-07 23:21:43 +0000507 if (slashpos == std::string::npos) {
508 path.erase();
509 return true;
510 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000511 path.erase(slashpos);
512 return true;
513}
514
515bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000516Path::appendSuffix(const std::string& suffix) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000517 std::string save(path);
Reid Spencer6df221d2004-08-29 05:24:01 +0000518 path.append(".");
519 path.append(suffix);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000520 if (!isValid()) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000521 path = save;
Reid Spencer6df221d2004-08-29 05:24:01 +0000522 return false;
523 }
524 return true;
525}
526
Reid Spencerc9c04732005-07-07 23:21:43 +0000527bool
528Path::eraseSuffix() {
Reid Spencerd28e432c2005-07-08 06:53:26 +0000529 std::string save = path;
Reid Spencer6df221d2004-08-29 05:24:01 +0000530 size_t dotpos = path.rfind('.',path.size());
531 size_t slashpos = path.rfind('/',path.size());
Jeff Cohen4c241442005-07-08 04:49:16 +0000532 if (dotpos != std::string::npos) {
Jeff Cohen5b106d02005-07-09 18:42:02 +0000533 if (slashpos == std::string::npos || dotpos > slashpos+1) {
Jeff Cohen4c241442005-07-08 04:49:16 +0000534 path.erase(dotpos, path.size()-dotpos);
Jeff Cohenf5067762005-07-08 05:02:13 +0000535 return true;
Jeff Cohen4c241442005-07-08 04:49:16 +0000536 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000537 }
Reid Spencerd28e432c2005-07-08 06:53:26 +0000538 if (!isValid())
539 path = save;
Jeff Cohen4c241442005-07-08 04:49:16 +0000540 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000541}
542
Reid Spencer6df221d2004-08-29 05:24:01 +0000543bool
Reid Spenceraf48d862005-07-08 03:08:58 +0000544Path::createDirectoryOnDisk( bool create_parents) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000545 // Get a writeable copy of the path name
546 char pathname[MAXPATHLEN];
547 path.copy(pathname,MAXPATHLEN);
548
549 // Null-terminate the last component
550 int lastchar = path.length() - 1 ;
551 if (pathname[lastchar] == '/')
552 pathname[lastchar] = 0;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000553 else
554 pathname[lastchar+1] = 0;
Reid Spencer6df221d2004-08-29 05:24:01 +0000555
556 // If we're supposed to create intermediate directories
557 if ( create_parents ) {
558 // Find the end of the initial name component
559 char * next = strchr(pathname,'/');
560 if ( pathname[0] == '/')
561 next = strchr(&pathname[1],'/');
562
563 // Loop through the directory components until we're done
564 while ( next != 0 ) {
565 *next = 0;
566 if (0 != access(pathname, F_OK | R_OK | W_OK))
567 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
Reid Spencer8424ba32005-04-21 02:50:10 +0000568 ThrowErrno(std::string(pathname) + ": can't create directory");
Reid Spencer6df221d2004-08-29 05:24:01 +0000569 char* save = next;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000570 next = strchr(next+1,'/');
Reid Spencer6df221d2004-08-29 05:24:01 +0000571 *save = '/';
572 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000573 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000574
575 if (0 != access(pathname, F_OK | R_OK))
576 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
Reid Spencer8424ba32005-04-21 02:50:10 +0000577 ThrowErrno(std::string(pathname) + ": can't create directory");
Reid Spencer6df221d2004-08-29 05:24:01 +0000578 return true;
579}
580
581bool
Reid Spenceraf48d862005-07-08 03:08:58 +0000582Path::createFileOnDisk() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000583 // Create the file
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000584 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
585 if (fd < 0)
Reid Spencer8424ba32005-04-21 02:50:10 +0000586 ThrowErrno(path + ": can't create file");
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000587 ::close(fd);
Reid Spencer6df221d2004-08-29 05:24:01 +0000588
589 return true;
Reid Spencer814ba572004-08-25 06:20:07 +0000590}
591
Reid Spencer6df221d2004-08-29 05:24:01 +0000592bool
Reid Spenceraf48d862005-07-08 03:08:58 +0000593Path::createTemporaryFileOnDisk(bool reuse_current) {
Reid Spencerf66d9322004-12-15 01:50:13 +0000594 // Make this into a unique file name
Reid Spencer98ce23f2004-12-15 08:32:45 +0000595 makeUnique( reuse_current );
Reid Spencerf66d9322004-12-15 01:50:13 +0000596
597 // create the file
598 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
599 if (outFile != -1) {
600 ::close(outFile);
601 return true;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000602 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000603 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000604}
605
606bool
Chris Lattner3cec1092006-07-28 22:29:50 +0000607Path::eraseFromDisk(bool remove_contents, std::string *ErrStr) const {
608 // Make sure we're dealing with a directory.
Reid Spencerc9c04732005-07-07 23:21:43 +0000609 if (isFile()) {
Chris Lattner3cec1092006-07-28 22:29:50 +0000610 if (unlink(path.c_str()) != 0)
611 return GetErrno(path + ": can't destroy file", ErrStr);
Reid Spencerc9c04732005-07-07 23:21:43 +0000612 return false;
Chris Lattner3cec1092006-07-28 22:29:50 +0000613 }
614
615 if (!isDirectory()) {
616 if (ErrStr) *ErrStr = "not a file or directory";
617 return true;
618 }
619 if (remove_contents) {
620 // Recursively descend the directory to remove its contents.
621 std::string cmd = "/bin/rm -rf " + path;
622 system(cmd.c_str());
623 return false;
624 }
625
626 // Otherwise, try to just remove the one directory.
627 char pathname[MAXPATHLEN];
628 path.copy(pathname, MAXPATHLEN);
629 int lastchar = path.length() - 1 ;
630 if (pathname[lastchar] == '/')
631 pathname[lastchar] = 0;
632 else
633 pathname[lastchar+1] = 0;
634
635 if (rmdir(pathname) != 0)
636 return GetErrno(std::string(pathname) + ": can't destroy directory",
637 ErrStr);
638 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000639}
640
641bool
Reid Spenceraf48d862005-07-08 03:08:58 +0000642Path::renamePathOnDisk(const Path& newName) {
Reid Spencerc9c04732005-07-07 23:21:43 +0000643 if (0 != ::rename(path.c_str(), newName.c_str()))
Reid Spencer8424ba32005-04-21 02:50:10 +0000644 ThrowErrno(std::string("can't rename '") + path + "' as '" +
645 newName.toString() + "' ");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000646 return true;
647}
648
649bool
Chris Lattner60c50642006-07-28 22:36:17 +0000650Path::setStatusInfoOnDisk(const FileStatus &si, std::string *ErrStr) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000651 struct utimbuf utb;
652 utb.actime = si.modTime.toPosixTime();
653 utb.modtime = utb.actime;
654 if (0 != ::utime(path.c_str(),&utb))
Chris Lattner60c50642006-07-28 22:36:17 +0000655 return GetErrno(path + ": can't set file modification time", ErrStr);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000656 if (0 != ::chmod(path.c_str(),si.mode))
Chris Lattner60c50642006-07-28 22:36:17 +0000657 return GetErrno(path + ": can't set mode", ErrStr);
658 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000659}
660
Reid Spencerf66d9322004-12-15 01:50:13 +0000661void
Reid Spencer10741062004-12-21 03:27:08 +0000662sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
Reid Spencerf66d9322004-12-15 01:50:13 +0000663 int inFile = -1;
664 int outFile = -1;
665 try {
666 inFile = ::open(Src.c_str(), O_RDONLY);
667 if (inFile == -1)
Reid Spencer8424ba32005-04-21 02:50:10 +0000668 ThrowErrno(Src.toString() + ": can't open source file to copy: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000669
670 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
671 if (outFile == -1)
Reid Spencer8424ba32005-04-21 02:50:10 +0000672 ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000673
674 char Buffer[16*1024];
675 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
676 if (Amt == -1) {
677 if (errno != EINTR && errno != EAGAIN)
Reid Spencer8424ba32005-04-21 02:50:10 +0000678 ThrowErrno(Src.toString()+": can't read source file: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000679 } else {
680 char *BufPtr = Buffer;
681 while (Amt) {
682 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
683 if (AmtWritten == -1) {
684 if (errno != EINTR && errno != EAGAIN)
Reid Spencer8424ba32005-04-21 02:50:10 +0000685 ThrowErrno(Dest.toString() + ": can't write destination file: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000686 } else {
687 Amt -= AmtWritten;
688 BufPtr += AmtWritten;
689 }
690 }
691 }
692 }
693 ::close(inFile);
694 ::close(outFile);
695 } catch (...) {
696 if (inFile != -1)
697 ::close(inFile);
698 if (outFile != -1)
699 ::close(outFile);
700 throw;
701 }
702}
703
704void
Reid Spencer98ce23f2004-12-15 08:32:45 +0000705Path::makeUnique(bool reuse_current) {
706 if (reuse_current && !exists())
Reid Spencerf66d9322004-12-15 01:50:13 +0000707 return; // File doesn't exist already, just use it!
708
709 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
710 // mktemp or our own implementation.
711 char *FNBuffer = (char*) alloca(path.size()+8);
712 path.copy(FNBuffer,path.size());
713 strcpy(FNBuffer+path.size(), "-XXXXXX");
714
715#if defined(HAVE_MKSTEMP)
716 int TempFD;
717 if ((TempFD = mkstemp(FNBuffer)) == -1) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000718 ThrowErrno(path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000719 }
720
721 // We don't need to hold the temp file descriptor... we will trust that no one
722 // will overwrite/delete the file before we can open it again.
723 close(TempFD);
724
725 // Save the name
726 path = FNBuffer;
727#elif defined(HAVE_MKTEMP)
728 // If we don't have mkstemp, use the old and obsolete mktemp function.
729 if (mktemp(FNBuffer) == 0) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000730 ThrowErrno(path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000731 }
732
733 // Save the name
734 path = FNBuffer;
735#else
736 // Okay, looks like we have to do it all by our lonesome.
737 static unsigned FCounter = 0;
738 unsigned offset = path.size() + 1;
739 while ( FCounter < 999999 && exists()) {
740 sprintf(FNBuffer+offset,"%06u",++FCounter);
741 path = FNBuffer;
742 }
743 if (FCounter > 999999)
Reid Spencer8424ba32005-04-21 02:50:10 +0000744 throw std::string(path + ": can't make unique filename: too many files");
Reid Spencerf66d9322004-12-15 01:50:13 +0000745#endif
746
747}
Reid Spencer814ba572004-08-25 06:20:07 +0000748}
749