blob: 21da4ad97f8e39e8f2c6e94d79c6d63bbb346f65 [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 Spencer814ba572004-08-25 06:20:07 +000050
Reid Spencer6df221d2004-08-29 05:24:01 +000051namespace llvm {
52using namespace sys;
Reid Spencer814ba572004-08-25 06:20:07 +000053
Misha Brukmanf06cb1d2004-12-20 00:16:38 +000054Path::Path(const std::string& unverified_path) : path(unverified_path) {
Reid Spencer6df221d2004-08-29 05:24:01 +000055 if (unverified_path.empty())
56 return;
Reid Spencer0c6a2832004-11-05 22:15:36 +000057 if (this->isValid())
Reid Spencer6df221d2004-08-29 05:24:01 +000058 return;
59 // oops, not valid.
60 path.clear();
61 ThrowErrno(unverified_path + ": path is not valid");
Reid Spencer814ba572004-08-25 06:20:07 +000062}
63
Reid Spencer20540312004-12-24 06:29:42 +000064bool
65Path::isValid() const {
66 if (path.empty())
67 return false;
68 else if (path.length() >= MAXPATHLEN)
69 return false;
70#if defined(HAVE_REALPATH)
71 char pathname[MAXPATHLEN];
72 if (0 == realpath(path.c_str(), pathname))
73 if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
74 return false;
75#endif
76 return true;
77}
78
Reid Spencer6df221d2004-08-29 05:24:01 +000079Path
80Path::GetRootDirectory() {
81 Path result;
Reid Spencer0c6a2832004-11-05 22:15:36 +000082 result.setDirectory("/");
Reid Spencer6df221d2004-08-29 05:24:01 +000083 return result;
84}
85
Reid Spencer20540312004-12-24 06:29:42 +000086Path
87Path::GetTemporaryDirectory() {
88#if defined(HAVE_MKDTEMP)
89 // The best way is with mkdtemp but that's not available on many systems,
90 // Linux and FreeBSD have it. Others probably won't.
91 char pathname[MAXPATHLEN];
92 strcpy(pathname,"/tmp/llvm_XXXXXX");
93 if (0 == mkdtemp(pathname))
Reid Spencer8424ba32005-04-21 02:50:10 +000094 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +000095 Path result;
96 result.setDirectory(pathname);
97 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
98 return result;
99#elif defined(HAVE_MKSTEMP)
100 // If no mkdtemp is available, mkstemp can be used to create a temporary file
101 // which is then removed and created as a directory. We prefer this over
102 // mktemp because of mktemp's inherent security and threading risks. We still
103 // have a slight race condition from the time the temporary file is created to
104 // the time it is re-created as a directoy.
105 char pathname[MAXPATHLEN];
106 strcpy(pathname, "/tmp/llvm_XXXXXX");
107 int fd = 0;
108 if (-1 == (fd = mkstemp(pathname)))
Reid Spencer8424ba32005-04-21 02:50:10 +0000109 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000110 ::close(fd);
111 ::unlink(pathname); // start race condition, ignore errors
112 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
Reid Spencer8424ba32005-04-21 02:50:10 +0000113 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000114 Path result;
115 result.setDirectory(pathname);
116 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
117 return result;
118#elif defined(HAVE_MKTEMP)
119 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
120 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
121 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
122 // the XXXXXX with the pid of the process and a letter. That leads to only
123 // twenty six temporary files that can be generated.
124 char pathname[MAXPATHLEN];
125 strcpy(pathname, "/tmp/llvm_XXXXXX");
126 char *TmpName = ::mktemp(pathname);
127 if (TmpName == 0)
Reid Spencer8424ba32005-04-21 02:50:10 +0000128 ThrowErrno(std::string(TmpName) + ": can't create unique directory name");
Reid Spencer20540312004-12-24 06:29:42 +0000129 if (-1 == ::mkdir(TmpName, S_IRWXU))
Reid Spencer8424ba32005-04-21 02:50:10 +0000130 ThrowErrno(std::string(TmpName) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000131 Path result;
132 result.setDirectory(TmpName);
133 assert(result.isValid() && "mktemp didn't create a valid pathname!");
134 return result;
135#else
136 // This is the worst case implementation. tempnam(3) leaks memory unless its
137 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
138 // issues. The mktemp(3) function doesn't have enough variability in the
139 // temporary name generated. So, we provide our own implementation that
140 // increments an integer from a random number seeded by the current time. This
141 // should be sufficiently unique that we don't have many collisions between
142 // processes. Generally LLVM processes don't run very long and don't use very
143 // many temporary files so this shouldn't be a big issue for LLVM.
144 static time_t num = ::time(0);
145 char pathname[MAXPATHLEN];
146 do {
147 num++;
148 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
149 } while ( 0 == access(pathname, F_OK ) );
150 if (-1 == ::mkdir(pathname, S_IRWXU))
Reid Spencer8424ba32005-04-21 02:50:10 +0000151 ThrowErrno(std::string(pathname) + ": can't create temporary directory");
Reid Spencer20540312004-12-24 06:29:42 +0000152 Path result;
153 result.setDirectory(pathname);
154 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
155 return result;
156#endif
157}
158
Reid Spencer9b155dc2004-12-13 03:00:51 +0000159static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
160 const char* at = path;
161 const char* delim = strchr(at, ':');
162 Path tmpPath;
163 while( delim != 0 ) {
164 std::string tmp(at, size_t(delim-at));
165 if (tmpPath.setDirectory(tmp))
166 if (tmpPath.readable())
167 Paths.push_back(tmpPath);
168 at = delim + 1;
169 delim = strchr(at, ':');
Reid Spencerdf05ec72004-09-14 00:16:39 +0000170 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000171 if (*at != 0)
172 if (tmpPath.setDirectory(std::string(at)))
173 if (tmpPath.readable())
174 Paths.push_back(tmpPath);
175
Reid Spencerdf05ec72004-09-14 00:16:39 +0000176}
Misha Brukmanf06cb1d2004-12-20 00:16:38 +0000177
Reid Spencer9b155dc2004-12-13 03:00:51 +0000178void
179Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
180#ifdef LTDL_SHLIBPATH_VAR
181 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
182 if (env_var != 0) {
183 getPathList(env_var,Paths);
Reid Spencerdf05ec72004-09-14 00:16:39 +0000184 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000185#endif
186 // FIXME: Should this look at LD_LIBRARY_PATH too?
187 Paths.push_back(sys::Path("/usr/local/lib/"));
188 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
189 Paths.push_back(sys::Path("/usr/lib/"));
190 Paths.push_back(sys::Path("/lib/"));
Reid Spencerdf05ec72004-09-14 00:16:39 +0000191}
192
Reid Spencer9b155dc2004-12-13 03:00:51 +0000193void
194Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
195 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
196 if (env_var != 0) {
197 getPathList(env_var,Paths);
198 }
Reid Spencer9b155dc2004-12-13 03:00:51 +0000199#ifdef LLVM_LIBDIR
200 {
201 Path tmpPath;
202 if (tmpPath.setDirectory(LLVM_LIBDIR))
203 if (tmpPath.readable())
204 Paths.push_back(tmpPath);
205 }
206#endif
207 GetSystemLibraryPaths(Paths);
Reid Spencer6df221d2004-08-29 05:24:01 +0000208}
209
210Path
211Path::GetLLVMDefaultConfigDir() {
212 return Path("/etc/llvm/");
213}
214
Reid Spencer6df221d2004-08-29 05:24:01 +0000215Path
216Path::GetUserHomeDirectory() {
217 const char* home = getenv("HOME");
218 if (home) {
219 Path result;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000220 if (result.setDirectory(home))
Reid Spencer6df221d2004-08-29 05:24:01 +0000221 return result;
222 }
223 return GetRootDirectory();
224}
225
226bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000227Path::isFile() const {
228 return (isValid() && path[path.length()-1] != '/');
Reid Spencerae9bbda2004-09-11 04:55:08 +0000229}
230
231bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000232Path::isDirectory() const {
233 return (isValid() && path[path.length()-1] == '/');
Reid Spencerae9bbda2004-09-11 04:55:08 +0000234}
235
236std::string
Reid Spencer0c6a2832004-11-05 22:15:36 +0000237Path::getBasename() const {
Reid Spencerae9bbda2004-09-11 04:55:08 +0000238 // Find the last slash
239 size_t slash = path.rfind('/');
240 if (slash == std::string::npos)
241 slash = 0;
242 else
243 slash++;
244
245 return path.substr(slash, path.rfind('.'));
246}
247
Reid Spencer0c6a2832004-11-05 22:15:36 +0000248bool Path::hasMagicNumber(const std::string &Magic) const {
Reid Spencerae9bbda2004-09-11 04:55:08 +0000249 size_t len = Magic.size();
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000250 assert(len < 1024 && "Request for magic string too long");
251 char* buf = (char*) alloca(1 + len);
252 int fd = ::open(path.c_str(),O_RDONLY);
253 if (fd < 0)
254 return false;
Reid Spencer9b155dc2004-12-13 03:00:51 +0000255 size_t read_len = ::read(fd, buf, len);
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000256 close(fd);
Reid Spencer9b155dc2004-12-13 03:00:51 +0000257 if (len != read_len)
258 return false;
Reid Spencerae9bbda2004-09-11 04:55:08 +0000259 buf[len] = '\0';
260 return Magic == buf;
261}
262
Reid Spencerc1d474f2004-11-14 22:08:36 +0000263bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
264 if (!isFile())
265 return false;
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000266 assert(len < 1024 && "Request for magic string too long");
267 char* buf = (char*) alloca(1 + len);
268 int fd = ::open(path.c_str(),O_RDONLY);
269 if (fd < 0)
270 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000271 ssize_t bytes_read = ::read(fd, buf, len);
272 ::close(fd);
273 if (ssize_t(len) != bytes_read) {
274 Magic.clear();
Reid Spencer1b13a7c2004-11-16 17:14:08 +0000275 return false;
Reid Spencerf4731852004-12-02 09:09:48 +0000276 }
277 Magic.assign(buf,len);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000278 return true;
279}
280
Reid Spencerae9bbda2004-09-11 04:55:08 +0000281bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000282Path::isBytecodeFile() const {
Reid Spencerfb1f7352004-11-09 20:26:31 +0000283 char buffer[ 4];
284 buffer[0] = 0;
Reid Spencer5ccfd5a2004-12-11 00:14:15 +0000285 int fd = ::open(path.c_str(),O_RDONLY);
286 if (fd < 0)
287 return false;
288 ssize_t bytes_read = ::read(fd, buffer, 4);
289 ::close(fd);
290 if (4 != bytes_read)
291 return false;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000292
293 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
294 (buffer[3] == 'c' || buffer[3] == 'm'));
Reid Spencerae9bbda2004-09-11 04:55:08 +0000295}
296
297bool
Reid Spencer6df221d2004-08-29 05:24:01 +0000298Path::exists() const {
299 return 0 == access(path.c_str(), F_OK );
300}
301
302bool
303Path::readable() const {
304 return 0 == access(path.c_str(), F_OK | R_OK );
305}
306
307bool
308Path::writable() const {
309 return 0 == access(path.c_str(), F_OK | W_OK );
310}
311
312bool
313Path::executable() const {
Misha Brukmana9a8c1b2005-04-20 15:33:22 +0000314 struct stat st;
315 int r = stat(path.c_str(), &st);
316 if (r != 0 || !S_ISREG(st.st_mode))
317 return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000318 return 0 == access(path.c_str(), R_OK | X_OK );
319}
320
321std::string
322Path::getLast() const {
323 // Find the last slash
324 size_t pos = path.rfind('/');
325
326 // Handle the corner cases
327 if (pos == std::string::npos)
328 return path;
329
330 // If the last character is a slash
331 if (pos == path.length()-1) {
332 // Find the second to last slash
333 size_t pos2 = path.rfind('/', pos-1);
334 if (pos2 == std::string::npos)
335 return path.substr(0,pos);
336 else
337 return path.substr(pos2+1,pos-pos2-1);
338 }
339 // Return everything after the last slash
340 return path.substr(pos+1);
341}
342
Reid Spencer91f505e2004-11-16 06:15:19 +0000343void
344Path::getStatusInfo(StatusInfo& info) const {
Reid Spencerfb1f7352004-11-09 20:26:31 +0000345 struct stat buf;
346 if (0 != stat(path.c_str(), &buf)) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000347 ThrowErrno(path + ": can't determine type of path object: ");
Reid Spencerfb1f7352004-11-09 20:26:31 +0000348 }
349 info.fileSize = buf.st_size;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000350 info.modTime.fromEpochTime(buf.st_mtime);
Reid Spencerfb1f7352004-11-09 20:26:31 +0000351 info.mode = buf.st_mode;
352 info.user = buf.st_uid;
353 info.group = buf.st_gid;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000354 info.isDir = S_ISDIR(buf.st_mode);
355 if (info.isDir && path[path.length()-1] != '/')
356 path += '/';
357}
358
Reid Spencer94bf2262004-12-13 19:59:50 +0000359static bool AddPermissionBits(const std::string& Filename, int bits) {
360 // Get the umask value from the operating system. We want to use it
361 // when changing the file's permissions. Since calling umask() sets
362 // the umask and returns its old value, we must call it a second
363 // time to reset it to the user's preference.
364 int mask = umask(0777); // The arg. to umask is arbitrary.
365 umask(mask); // Restore the umask.
366
367 // Get the file's current mode.
368 struct stat st;
369 if ((stat(Filename.c_str(), &st)) == -1)
370 return false;
371
372 // Change the file to have whichever permissions bits from 'bits'
373 // that the umask would not disable.
374 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
375 return false;
376
377 return true;
378}
379
380void Path::makeReadable() {
381 if (!AddPermissionBits(path,0444))
382 ThrowErrno(path + ": can't make file readable");
383}
384
385void Path::makeWriteable() {
386 if (!AddPermissionBits(path,0222))
387 ThrowErrno(path + ": can't make file writable");
388}
389
390void Path::makeExecutable() {
391 if (!AddPermissionBits(path,0111))
392 ThrowErrno(path + ": can't make file executable");
393}
394
Reid Spencerc1d474f2004-11-14 22:08:36 +0000395bool
Reid Spencer91f505e2004-11-16 06:15:19 +0000396Path::getDirectoryContents(std::set<Path>& result) const {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000397 if (!isDirectory())
398 return false;
399 DIR* direntries = ::opendir(path.c_str());
400 if (direntries == 0)
401 ThrowErrno(path + ": can't open directory");
402
403 result.clear();
404 struct dirent* de = ::readdir(direntries);
Misha Brukman1001aea2005-04-20 04:04:07 +0000405 for ( ; de != 0; de = ::readdir(direntries)) {
Reid Spencerc1d474f2004-11-14 22:08:36 +0000406 if (de->d_name[0] != '.') {
407 Path aPath(path + (const char*)de->d_name);
408 struct stat buf;
Misha Brukman1001aea2005-04-20 04:04:07 +0000409 if (0 != stat(aPath.path.c_str(), &buf)) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000410 int stat_errno = errno;
Misha Brukman1001aea2005-04-20 04:04:07 +0000411 struct stat st;
412 if (0 == lstat(aPath.path.c_str(), &st) && S_ISLNK(st.st_mode))
413 continue; // dangling symlink -- ignore
Reid Spencer8424ba32005-04-21 02:50:10 +0000414 ThrowErrno(aPath.path +
415 ": can't determine file object type", stat_errno);
Misha Brukman1001aea2005-04-20 04:04:07 +0000416 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000417 if (S_ISDIR(buf.st_mode))
418 aPath.path += "/";
Reid Spencer91f505e2004-11-16 06:15:19 +0000419 result.insert(aPath);
Reid Spencerc1d474f2004-11-14 22:08:36 +0000420 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000421 }
422
423 closedir(direntries);
424 return true;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000425}
426
Reid Spencer6df221d2004-08-29 05:24:01 +0000427bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000428Path::setDirectory(const std::string& a_path) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000429 if (a_path.size() == 0)
430 return false;
431 Path save(*this);
432 path = a_path;
433 size_t last = a_path.size() -1;
Reid Spencera85abc22004-12-13 07:51:07 +0000434 if (a_path[last] != '/')
Reid Spencer6df221d2004-08-29 05:24:01 +0000435 path += '/';
Reid Spencer0c6a2832004-11-05 22:15:36 +0000436 if (!isValid()) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000437 path = save.path;
438 return false;
439 }
440 return true;
441}
442
443bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000444Path::setFile(const std::string& a_path) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000445 if (a_path.size() == 0)
446 return false;
447 Path save(*this);
448 path = a_path;
449 size_t last = a_path.size() - 1;
450 while (last > 0 && a_path[last] == '/')
451 last--;
452 path.erase(last+1);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000453 if (!isValid()) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000454 path = save.path;
455 return false;
456 }
457 return true;
458}
459
460bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000461Path::appendDirectory(const std::string& dir) {
462 if (isFile())
Reid Spencer6df221d2004-08-29 05:24:01 +0000463 return false;
464 Path save(*this);
465 path += dir;
466 path += "/";
Reid Spencer0c6a2832004-11-05 22:15:36 +0000467 if (!isValid()) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000468 path = save.path;
469 return false;
470 }
471 return true;
472}
473
474bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000475Path::elideDirectory() {
476 if (isFile())
Reid Spencer6df221d2004-08-29 05:24:01 +0000477 return false;
478 size_t slashpos = path.rfind('/',path.size());
479 if (slashpos == 0 || slashpos == std::string::npos)
480 return false;
481 if (slashpos == path.size() - 1)
482 slashpos = path.rfind('/',slashpos-1);
483 if (slashpos == std::string::npos)
484 return false;
485 path.erase(slashpos);
486 return true;
487}
488
489bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000490Path::appendFile(const std::string& file) {
491 if (!isDirectory())
Reid Spencer6df221d2004-08-29 05:24:01 +0000492 return false;
493 Path save(*this);
494 path += file;
Reid Spencer0c6a2832004-11-05 22:15:36 +0000495 if (!isValid()) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000496 path = save.path;
497 return false;
498 }
499 return true;
500}
501
502bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000503Path::elideFile() {
504 if (isDirectory())
Reid Spencer6df221d2004-08-29 05:24:01 +0000505 return false;
506 size_t slashpos = path.rfind('/',path.size());
507 if (slashpos == std::string::npos)
508 return false;
509 path.erase(slashpos+1);
510 return true;
511}
512
513bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000514Path::appendSuffix(const std::string& suffix) {
515 if (isDirectory())
Reid Spencer6df221d2004-08-29 05:24:01 +0000516 return false;
517 Path save(*this);
518 path.append(".");
519 path.append(suffix);
Reid Spencer0c6a2832004-11-05 22:15:36 +0000520 if (!isValid()) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000521 path = save.path;
522 return false;
523 }
524 return true;
525}
526
527bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000528Path::elideSuffix() {
529 if (isDirectory()) return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000530 size_t dotpos = path.rfind('.',path.size());
531 size_t slashpos = path.rfind('/',path.size());
532 if (slashpos != std::string::npos && dotpos != std::string::npos &&
533 dotpos > slashpos) {
534 path.erase(dotpos, path.size()-dotpos);
535 return true;
536 }
537 return false;
538}
539
540
541bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000542Path::createDirectory( bool create_parents) {
Reid Spencer6df221d2004-08-29 05:24:01 +0000543 // Make sure we're dealing with a directory
Reid Spencer0c6a2832004-11-05 22:15:36 +0000544 if (!isDirectory()) return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000545
546 // Get a writeable copy of the path name
547 char pathname[MAXPATHLEN];
548 path.copy(pathname,MAXPATHLEN);
549
550 // Null-terminate the last component
551 int lastchar = path.length() - 1 ;
552 if (pathname[lastchar] == '/')
553 pathname[lastchar] = 0;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000554 else
555 pathname[lastchar+1] = 0;
Reid Spencer6df221d2004-08-29 05:24:01 +0000556
557 // If we're supposed to create intermediate directories
558 if ( create_parents ) {
559 // Find the end of the initial name component
560 char * next = strchr(pathname,'/');
561 if ( pathname[0] == '/')
562 next = strchr(&pathname[1],'/');
563
564 // Loop through the directory components until we're done
565 while ( next != 0 ) {
566 *next = 0;
567 if (0 != access(pathname, F_OK | R_OK | W_OK))
568 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
Reid Spencer8424ba32005-04-21 02:50:10 +0000569 ThrowErrno(std::string(pathname) + ": can't create directory");
Reid Spencer6df221d2004-08-29 05:24:01 +0000570 char* save = next;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000571 next = strchr(next+1,'/');
Reid Spencer6df221d2004-08-29 05:24:01 +0000572 *save = '/';
573 }
Reid Spencer6df221d2004-08-29 05:24:01 +0000574 }
Reid Spencerc1d474f2004-11-14 22:08:36 +0000575
576 if (0 != access(pathname, F_OK | R_OK))
577 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
Reid Spencer8424ba32005-04-21 02:50:10 +0000578 ThrowErrno(std::string(pathname) + ": can't create directory");
Reid Spencer6df221d2004-08-29 05:24:01 +0000579 return true;
580}
581
582bool
Reid Spencer0c6a2832004-11-05 22:15:36 +0000583Path::createFile() {
Reid Spencer6df221d2004-08-29 05:24:01 +0000584 // Make sure we're dealing with a file
Reid Spencer0c6a2832004-11-05 22:15:36 +0000585 if (!isFile()) return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000586
587 // Create the file
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000588 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
589 if (fd < 0)
Reid Spencer8424ba32005-04-21 02:50:10 +0000590 ThrowErrno(path + ": can't create file");
Reid Spencer36e3cbf2004-09-18 19:25:11 +0000591 ::close(fd);
Reid Spencer6df221d2004-08-29 05:24:01 +0000592
593 return true;
Reid Spencer814ba572004-08-25 06:20:07 +0000594}
595
Reid Spencer6df221d2004-08-29 05:24:01 +0000596bool
Reid Spencer98ce23f2004-12-15 08:32:45 +0000597Path::createTemporaryFile(bool reuse_current) {
Reid Spencerfb1f7352004-11-09 20:26:31 +0000598 // Make sure we're dealing with a file
Reid Spencerf66d9322004-12-15 01:50:13 +0000599 if (!isFile())
600 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000601
Reid Spencerf66d9322004-12-15 01:50:13 +0000602 // Make this into a unique file name
Reid Spencer98ce23f2004-12-15 08:32:45 +0000603 makeUnique( reuse_current );
Reid Spencerf66d9322004-12-15 01:50:13 +0000604
605 // create the file
606 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
607 if (outFile != -1) {
608 ::close(outFile);
609 return true;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000610 }
Reid Spencerf66d9322004-12-15 01:50:13 +0000611 return false;
Reid Spencerfb1f7352004-11-09 20:26:31 +0000612}
613
614bool
Reid Spencere5624272004-12-15 23:02:10 +0000615Path::destroyDirectory(bool remove_contents) const {
Reid Spencer6df221d2004-08-29 05:24:01 +0000616 // Make sure we're dealing with a directory
Reid Spencer0c6a2832004-11-05 22:15:36 +0000617 if (!isDirectory()) return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000618
619 // If it doesn't exist, we're done.
620 if (!exists()) return true;
621
622 if (remove_contents) {
623 // Recursively descend the directory to remove its content
624 std::string cmd("/bin/rm -rf ");
625 cmd += path;
626 system(cmd.c_str());
627 } else {
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;
Reid Spencerc1d474f2004-11-14 22:08:36 +0000634 else
635 pathname[lastchar+1] = 0;
Reid Spencer6df221d2004-08-29 05:24:01 +0000636 if ( 0 != rmdir(pathname))
Reid Spencer8424ba32005-04-21 02:50:10 +0000637 ThrowErrno(std::string(pathname) + ": can't destroy directory");
Reid Spencer6df221d2004-08-29 05:24:01 +0000638 }
639 return true;
640}
641
642bool
Reid Spencere5624272004-12-15 23:02:10 +0000643Path::destroyFile() const {
Reid Spencer0c6a2832004-11-05 22:15:36 +0000644 if (!isFile()) return false;
Reid Spencer6df221d2004-08-29 05:24:01 +0000645 if (0 != unlink(path.c_str()))
Reid Spencer8424ba32005-04-21 02:50:10 +0000646 ThrowErrno(path + ": can't destroy file");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000647 return true;
648}
649
650bool
651Path::renameFile(const Path& newName) {
652 if (!isFile()) return false;
653 if (0 != rename(path.c_str(), newName.c_str()))
Reid Spencer8424ba32005-04-21 02:50:10 +0000654 ThrowErrno(std::string("can't rename '") + path + "' as '" +
655 newName.toString() + "' ");
Reid Spencerc1d474f2004-11-14 22:08:36 +0000656 return true;
657}
658
659bool
660Path::setStatusInfo(const StatusInfo& si) const {
661 if (!isFile()) return false;
662 struct utimbuf utb;
663 utb.actime = si.modTime.toPosixTime();
664 utb.modtime = utb.actime;
665 if (0 != ::utime(path.c_str(),&utb))
666 ThrowErrno(path + ": can't set file modification time");
667 if (0 != ::chmod(path.c_str(),si.mode))
668 ThrowErrno(path + ": can't set mode");
Reid Spencer6df221d2004-08-29 05:24:01 +0000669 return true;
670}
671
Reid Spencerf66d9322004-12-15 01:50:13 +0000672void
Reid Spencer10741062004-12-21 03:27:08 +0000673sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
Reid Spencerf66d9322004-12-15 01:50:13 +0000674 int inFile = -1;
675 int outFile = -1;
676 try {
677 inFile = ::open(Src.c_str(), O_RDONLY);
678 if (inFile == -1)
Reid Spencer8424ba32005-04-21 02:50:10 +0000679 ThrowErrno(Src.toString() + ": can't open source file to copy: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000680
681 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
682 if (outFile == -1)
Reid Spencer8424ba32005-04-21 02:50:10 +0000683 ThrowErrno(Dest.toString() +": can't create destination file for copy: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000684
685 char Buffer[16*1024];
686 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
687 if (Amt == -1) {
688 if (errno != EINTR && errno != EAGAIN)
Reid Spencer8424ba32005-04-21 02:50:10 +0000689 ThrowErrno(Src.toString()+": can't read source file: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000690 } else {
691 char *BufPtr = Buffer;
692 while (Amt) {
693 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
694 if (AmtWritten == -1) {
695 if (errno != EINTR && errno != EAGAIN)
Reid Spencer8424ba32005-04-21 02:50:10 +0000696 ThrowErrno(Dest.toString() + ": can't write destination file: ");
Reid Spencerf66d9322004-12-15 01:50:13 +0000697 } else {
698 Amt -= AmtWritten;
699 BufPtr += AmtWritten;
700 }
701 }
702 }
703 }
704 ::close(inFile);
705 ::close(outFile);
706 } catch (...) {
707 if (inFile != -1)
708 ::close(inFile);
709 if (outFile != -1)
710 ::close(outFile);
711 throw;
712 }
713}
714
715void
Reid Spencer98ce23f2004-12-15 08:32:45 +0000716Path::makeUnique(bool reuse_current) {
717 if (reuse_current && !exists())
Reid Spencerf66d9322004-12-15 01:50:13 +0000718 return; // File doesn't exist already, just use it!
719
720 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
721 // mktemp or our own implementation.
722 char *FNBuffer = (char*) alloca(path.size()+8);
723 path.copy(FNBuffer,path.size());
724 strcpy(FNBuffer+path.size(), "-XXXXXX");
725
726#if defined(HAVE_MKSTEMP)
727 int TempFD;
728 if ((TempFD = mkstemp(FNBuffer)) == -1) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000729 ThrowErrno(path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000730 }
731
732 // We don't need to hold the temp file descriptor... we will trust that no one
733 // will overwrite/delete the file before we can open it again.
734 close(TempFD);
735
736 // Save the name
737 path = FNBuffer;
738#elif defined(HAVE_MKTEMP)
739 // If we don't have mkstemp, use the old and obsolete mktemp function.
740 if (mktemp(FNBuffer) == 0) {
Reid Spencer8424ba32005-04-21 02:50:10 +0000741 ThrowErrno(path + ": can't make unique filename");
Reid Spencerf66d9322004-12-15 01:50:13 +0000742 }
743
744 // Save the name
745 path = FNBuffer;
746#else
747 // Okay, looks like we have to do it all by our lonesome.
748 static unsigned FCounter = 0;
749 unsigned offset = path.size() + 1;
750 while ( FCounter < 999999 && exists()) {
751 sprintf(FNBuffer+offset,"%06u",++FCounter);
752 path = FNBuffer;
753 }
754 if (FCounter > 999999)
Reid Spencer8424ba32005-04-21 02:50:10 +0000755 throw std::string(path + ": can't make unique filename: too many files");
Reid Spencerf66d9322004-12-15 01:50:13 +0000756#endif
757
758}
Reid Spencer814ba572004-08-25 06:20:07 +0000759}
760