blob: f1d6938e31f37f8e492bdd729ef8fb5056091aae [file] [log] [blame]
Reid Spencerb89a2232004-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 Spencer8e665952004-08-29 05:24:01 +000016//=== is guaranteed to work on *all* UNIX variants.
Reid Spencerb89a2232004-08-25 06:20:07 +000017//===----------------------------------------------------------------------===//
18
Misha Brukman210b32b2004-12-20 00:16:38 +000019#include "llvm/Config/alloca.h"
Reid Spencerb89a2232004-08-25 06:20:07 +000020#include "Unix.h"
21#include <sys/stat.h>
22#include <fcntl.h>
Reid Spencereaf18152004-11-14 22:08:36 +000023#include <utime.h>
24#include <dirent.h>
Reid Spencer69a16162004-12-24 06:29:42 +000025#include <time.h>
Reid Spencerb89a2232004-08-25 06:20:07 +000026
Reid Spencer8e665952004-08-29 05:24:01 +000027namespace llvm {
28using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000029
Misha Brukman210b32b2004-12-20 00:16:38 +000030Path::Path(const std::string& unverified_path) : path(unverified_path) {
Reid Spencer8e665952004-08-29 05:24:01 +000031 if (unverified_path.empty())
32 return;
Reid Spencer07adb282004-11-05 22:15:36 +000033 if (this->isValid())
Reid Spencer8e665952004-08-29 05:24:01 +000034 return;
35 // oops, not valid.
36 path.clear();
37 ThrowErrno(unverified_path + ": path is not valid");
Reid Spencerb89a2232004-08-25 06:20:07 +000038}
39
Reid Spencer69a16162004-12-24 06:29:42 +000040bool
41Path::isValid() const {
42 if (path.empty())
43 return false;
44 else if (path.length() >= MAXPATHLEN)
45 return false;
46#if defined(HAVE_REALPATH)
47 char pathname[MAXPATHLEN];
48 if (0 == realpath(path.c_str(), pathname))
49 if (errno != EACCES && errno != EIO && errno != ENOENT && errno != ENOTDIR)
50 return false;
51#endif
52 return true;
53}
54
Reid Spencer8e665952004-08-29 05:24:01 +000055Path
56Path::GetRootDirectory() {
57 Path result;
Reid Spencer07adb282004-11-05 22:15:36 +000058 result.setDirectory("/");
Reid Spencer8e665952004-08-29 05:24:01 +000059 return result;
60}
61
Reid Spencer69a16162004-12-24 06:29:42 +000062Path
63Path::GetTemporaryDirectory() {
64#if defined(HAVE_MKDTEMP)
65 // The best way is with mkdtemp but that's not available on many systems,
66 // Linux and FreeBSD have it. Others probably won't.
67 char pathname[MAXPATHLEN];
68 strcpy(pathname,"/tmp/llvm_XXXXXX");
69 if (0 == mkdtemp(pathname))
70 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
71 Path result;
72 result.setDirectory(pathname);
73 assert(result.isValid() && "mkdtemp didn't create a valid pathname!");
74 return result;
75#elif defined(HAVE_MKSTEMP)
76 // If no mkdtemp is available, mkstemp can be used to create a temporary file
77 // which is then removed and created as a directory. We prefer this over
78 // mktemp because of mktemp's inherent security and threading risks. We still
79 // have a slight race condition from the time the temporary file is created to
80 // the time it is re-created as a directoy.
81 char pathname[MAXPATHLEN];
82 strcpy(pathname, "/tmp/llvm_XXXXXX");
83 int fd = 0;
84 if (-1 == (fd = mkstemp(pathname)))
85 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
86 ::close(fd);
87 ::unlink(pathname); // start race condition, ignore errors
88 if (-1 == ::mkdir(pathname, S_IRWXU)) // end race condition
89 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
90 Path result;
91 result.setDirectory(pathname);
92 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
93 return result;
94#elif defined(HAVE_MKTEMP)
95 // If a system doesn't have mkdtemp(3) or mkstemp(3) but it does have
96 // mktemp(3) then we'll assume that system (e.g. AIX) has a reasonable
97 // implementation of mktemp(3) and doesn't follow BSD 4.3's lead of replacing
98 // the XXXXXX with the pid of the process and a letter. That leads to only
99 // twenty six temporary files that can be generated.
100 char pathname[MAXPATHLEN];
101 strcpy(pathname, "/tmp/llvm_XXXXXX");
102 char *TmpName = ::mktemp(pathname);
103 if (TmpName == 0)
104 throw std::string(TmpName) + ": Can't create unique directory name";
105 if (-1 == ::mkdir(TmpName, S_IRWXU))
106 ThrowErrno(std::string(TmpName) + ": Can't create temporary directory");
107 Path result;
108 result.setDirectory(TmpName);
109 assert(result.isValid() && "mktemp didn't create a valid pathname!");
110 return result;
111#else
112 // This is the worst case implementation. tempnam(3) leaks memory unless its
113 // on an SVID2 (or later) system. On BSD 4.3 it leaks. tmpnam(3) has thread
114 // issues. The mktemp(3) function doesn't have enough variability in the
115 // temporary name generated. So, we provide our own implementation that
116 // increments an integer from a random number seeded by the current time. This
117 // should be sufficiently unique that we don't have many collisions between
118 // processes. Generally LLVM processes don't run very long and don't use very
119 // many temporary files so this shouldn't be a big issue for LLVM.
120 static time_t num = ::time(0);
121 char pathname[MAXPATHLEN];
122 do {
123 num++;
124 sprintf(pathname, "/tmp/llvm_%010u", unsigned(num));
125 } while ( 0 == access(pathname, F_OK ) );
126 if (-1 == ::mkdir(pathname, S_IRWXU))
127 ThrowErrno(std::string(pathname) + ": Can't create temporary directory");
128 Path result;
129 result.setDirectory(pathname);
130 assert(result.isValid() && "mkstemp didn't create a valid pathname!");
131 return result;
132#endif
133}
134
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000135static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
136 const char* at = path;
137 const char* delim = strchr(at, ':');
138 Path tmpPath;
139 while( delim != 0 ) {
140 std::string tmp(at, size_t(delim-at));
141 if (tmpPath.setDirectory(tmp))
142 if (tmpPath.readable())
143 Paths.push_back(tmpPath);
144 at = delim + 1;
145 delim = strchr(at, ':');
Reid Spencer74e72612004-09-14 00:16:39 +0000146 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000147 if (*at != 0)
148 if (tmpPath.setDirectory(std::string(at)))
149 if (tmpPath.readable())
150 Paths.push_back(tmpPath);
151
Reid Spencer74e72612004-09-14 00:16:39 +0000152}
Misha Brukman210b32b2004-12-20 00:16:38 +0000153
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000154void
155Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
156#ifdef LTDL_SHLIBPATH_VAR
157 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
158 if (env_var != 0) {
159 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +0000160 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000161#endif
162 // FIXME: Should this look at LD_LIBRARY_PATH too?
163 Paths.push_back(sys::Path("/usr/local/lib/"));
164 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
165 Paths.push_back(sys::Path("/usr/lib/"));
166 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +0000167}
168
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000169void
170Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
171 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
172 if (env_var != 0) {
173 getPathList(env_var,Paths);
174 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000175#ifdef LLVM_LIBDIR
176 {
177 Path tmpPath;
178 if (tmpPath.setDirectory(LLVM_LIBDIR))
179 if (tmpPath.readable())
180 Paths.push_back(tmpPath);
181 }
182#endif
183 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +0000184}
185
186Path
187Path::GetLLVMDefaultConfigDir() {
188 return Path("/etc/llvm/");
189}
190
Reid Spencer8e665952004-08-29 05:24:01 +0000191Path
192Path::GetUserHomeDirectory() {
193 const char* home = getenv("HOME");
194 if (home) {
195 Path result;
Reid Spencer07adb282004-11-05 22:15:36 +0000196 if (result.setDirectory(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000197 return result;
198 }
199 return GetRootDirectory();
200}
201
202bool
Reid Spencer07adb282004-11-05 22:15:36 +0000203Path::isFile() const {
204 return (isValid() && path[path.length()-1] != '/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000205}
206
207bool
Reid Spencer07adb282004-11-05 22:15:36 +0000208Path::isDirectory() const {
209 return (isValid() && path[path.length()-1] == '/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000210}
211
212std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000213Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000214 // Find the last slash
215 size_t slash = path.rfind('/');
216 if (slash == std::string::npos)
217 slash = 0;
218 else
219 slash++;
220
221 return path.substr(slash, path.rfind('.'));
222}
223
Reid Spencer07adb282004-11-05 22:15:36 +0000224bool Path::hasMagicNumber(const std::string &Magic) const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000225 size_t len = Magic.size();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000226 assert(len < 1024 && "Request for magic string too long");
227 char* buf = (char*) alloca(1 + len);
228 int fd = ::open(path.c_str(),O_RDONLY);
229 if (fd < 0)
230 return false;
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000231 size_t read_len = ::read(fd, buf, len);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000232 close(fd);
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000233 if (len != read_len)
234 return false;
Reid Spencer1b554b42004-09-11 04:55:08 +0000235 buf[len] = '\0';
236 return Magic == buf;
237}
238
Reid Spencereaf18152004-11-14 22:08:36 +0000239bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
240 if (!isFile())
241 return false;
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000242 assert(len < 1024 && "Request for magic string too long");
243 char* buf = (char*) alloca(1 + len);
244 int fd = ::open(path.c_str(),O_RDONLY);
245 if (fd < 0)
246 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000247 ssize_t bytes_read = ::read(fd, buf, len);
248 ::close(fd);
249 if (ssize_t(len) != bytes_read) {
250 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000251 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000252 }
253 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000254 return true;
255}
256
Reid Spencer1b554b42004-09-11 04:55:08 +0000257bool
Reid Spencer07adb282004-11-05 22:15:36 +0000258Path::isBytecodeFile() const {
Reid Spencer9195f372004-11-09 20:26:31 +0000259 char buffer[ 4];
260 buffer[0] = 0;
Reid Spencer1fce0912004-12-11 00:14:15 +0000261 int fd = ::open(path.c_str(),O_RDONLY);
262 if (fd < 0)
263 return false;
264 ssize_t bytes_read = ::read(fd, buffer, 4);
265 ::close(fd);
266 if (4 != bytes_read)
267 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000268
269 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
270 (buffer[3] == 'c' || buffer[3] == 'm'));
Reid Spencer1b554b42004-09-11 04:55:08 +0000271}
272
273bool
Reid Spencer8e665952004-08-29 05:24:01 +0000274Path::exists() const {
275 return 0 == access(path.c_str(), F_OK );
276}
277
278bool
279Path::readable() const {
280 return 0 == access(path.c_str(), F_OK | R_OK );
281}
282
283bool
284Path::writable() const {
285 return 0 == access(path.c_str(), F_OK | W_OK );
286}
287
288bool
289Path::executable() const {
290 return 0 == access(path.c_str(), R_OK | X_OK );
291}
292
293std::string
294Path::getLast() const {
295 // Find the last slash
296 size_t pos = path.rfind('/');
297
298 // Handle the corner cases
299 if (pos == std::string::npos)
300 return path;
301
302 // If the last character is a slash
303 if (pos == path.length()-1) {
304 // Find the second to last slash
305 size_t pos2 = path.rfind('/', pos-1);
306 if (pos2 == std::string::npos)
307 return path.substr(0,pos);
308 else
309 return path.substr(pos2+1,pos-pos2-1);
310 }
311 // Return everything after the last slash
312 return path.substr(pos+1);
313}
314
Reid Spencerb608a812004-11-16 06:15:19 +0000315void
316Path::getStatusInfo(StatusInfo& info) const {
Reid Spencer9195f372004-11-09 20:26:31 +0000317 struct stat buf;
318 if (0 != stat(path.c_str(), &buf)) {
319 ThrowErrno(std::string("Can't get status: ")+path);
320 }
321 info.fileSize = buf.st_size;
Reid Spencereaf18152004-11-14 22:08:36 +0000322 info.modTime.fromEpochTime(buf.st_mtime);
Reid Spencer9195f372004-11-09 20:26:31 +0000323 info.mode = buf.st_mode;
324 info.user = buf.st_uid;
325 info.group = buf.st_gid;
Reid Spencereaf18152004-11-14 22:08:36 +0000326 info.isDir = S_ISDIR(buf.st_mode);
327 if (info.isDir && path[path.length()-1] != '/')
328 path += '/';
329}
330
Reid Spencer77cc91d2004-12-13 19:59:50 +0000331static bool AddPermissionBits(const std::string& Filename, int bits) {
332 // Get the umask value from the operating system. We want to use it
333 // when changing the file's permissions. Since calling umask() sets
334 // the umask and returns its old value, we must call it a second
335 // time to reset it to the user's preference.
336 int mask = umask(0777); // The arg. to umask is arbitrary.
337 umask(mask); // Restore the umask.
338
339 // Get the file's current mode.
340 struct stat st;
341 if ((stat(Filename.c_str(), &st)) == -1)
342 return false;
343
344 // Change the file to have whichever permissions bits from 'bits'
345 // that the umask would not disable.
346 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
347 return false;
348
349 return true;
350}
351
352void Path::makeReadable() {
353 if (!AddPermissionBits(path,0444))
354 ThrowErrno(path + ": can't make file readable");
355}
356
357void Path::makeWriteable() {
358 if (!AddPermissionBits(path,0222))
359 ThrowErrno(path + ": can't make file writable");
360}
361
362void Path::makeExecutable() {
363 if (!AddPermissionBits(path,0111))
364 ThrowErrno(path + ": can't make file executable");
365}
366
Reid Spencereaf18152004-11-14 22:08:36 +0000367bool
Reid Spencerb608a812004-11-16 06:15:19 +0000368Path::getDirectoryContents(std::set<Path>& result) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000369 if (!isDirectory())
370 return false;
371 DIR* direntries = ::opendir(path.c_str());
372 if (direntries == 0)
373 ThrowErrno(path + ": can't open directory");
374
375 result.clear();
376 struct dirent* de = ::readdir(direntries);
377 while (de != 0) {
378 if (de->d_name[0] != '.') {
379 Path aPath(path + (const char*)de->d_name);
380 struct stat buf;
381 if (0 != stat(aPath.path.c_str(), &buf))
382 ThrowErrno(aPath.path + ": can't get status");
383 if (S_ISDIR(buf.st_mode))
384 aPath.path += "/";
Reid Spencerb608a812004-11-16 06:15:19 +0000385 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000386 }
387 de = ::readdir(direntries);
388 }
389
390 closedir(direntries);
391 return true;
Reid Spencer9195f372004-11-09 20:26:31 +0000392}
393
Reid Spencer8e665952004-08-29 05:24:01 +0000394bool
Reid Spencer07adb282004-11-05 22:15:36 +0000395Path::setDirectory(const std::string& a_path) {
Reid Spencer8e665952004-08-29 05:24:01 +0000396 if (a_path.size() == 0)
397 return false;
398 Path save(*this);
399 path = a_path;
400 size_t last = a_path.size() -1;
Reid Spencer3d595cb2004-12-13 07:51:07 +0000401 if (a_path[last] != '/')
Reid Spencer8e665952004-08-29 05:24:01 +0000402 path += '/';
Reid Spencer07adb282004-11-05 22:15:36 +0000403 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000404 path = save.path;
405 return false;
406 }
407 return true;
408}
409
410bool
Reid Spencer07adb282004-11-05 22:15:36 +0000411Path::setFile(const std::string& a_path) {
Reid Spencer8e665952004-08-29 05:24:01 +0000412 if (a_path.size() == 0)
413 return false;
414 Path save(*this);
415 path = a_path;
416 size_t last = a_path.size() - 1;
417 while (last > 0 && a_path[last] == '/')
418 last--;
419 path.erase(last+1);
Reid Spencer07adb282004-11-05 22:15:36 +0000420 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000421 path = save.path;
422 return false;
423 }
424 return true;
425}
426
427bool
Reid Spencer07adb282004-11-05 22:15:36 +0000428Path::appendDirectory(const std::string& dir) {
429 if (isFile())
Reid Spencer8e665952004-08-29 05:24:01 +0000430 return false;
431 Path save(*this);
432 path += dir;
433 path += "/";
Reid Spencer07adb282004-11-05 22:15:36 +0000434 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000435 path = save.path;
436 return false;
437 }
438 return true;
439}
440
441bool
Reid Spencer07adb282004-11-05 22:15:36 +0000442Path::elideDirectory() {
443 if (isFile())
Reid Spencer8e665952004-08-29 05:24:01 +0000444 return false;
445 size_t slashpos = path.rfind('/',path.size());
446 if (slashpos == 0 || slashpos == std::string::npos)
447 return false;
448 if (slashpos == path.size() - 1)
449 slashpos = path.rfind('/',slashpos-1);
450 if (slashpos == std::string::npos)
451 return false;
452 path.erase(slashpos);
453 return true;
454}
455
456bool
Reid Spencer07adb282004-11-05 22:15:36 +0000457Path::appendFile(const std::string& file) {
458 if (!isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000459 return false;
460 Path save(*this);
461 path += file;
Reid Spencer07adb282004-11-05 22:15:36 +0000462 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000463 path = save.path;
464 return false;
465 }
466 return true;
467}
468
469bool
Reid Spencer07adb282004-11-05 22:15:36 +0000470Path::elideFile() {
471 if (isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000472 return false;
473 size_t slashpos = path.rfind('/',path.size());
474 if (slashpos == std::string::npos)
475 return false;
476 path.erase(slashpos+1);
477 return true;
478}
479
480bool
Reid Spencer07adb282004-11-05 22:15:36 +0000481Path::appendSuffix(const std::string& suffix) {
482 if (isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000483 return false;
484 Path save(*this);
485 path.append(".");
486 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000487 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000488 path = save.path;
489 return false;
490 }
491 return true;
492}
493
494bool
Reid Spencer07adb282004-11-05 22:15:36 +0000495Path::elideSuffix() {
496 if (isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000497 size_t dotpos = path.rfind('.',path.size());
498 size_t slashpos = path.rfind('/',path.size());
499 if (slashpos != std::string::npos && dotpos != std::string::npos &&
500 dotpos > slashpos) {
501 path.erase(dotpos, path.size()-dotpos);
502 return true;
503 }
504 return false;
505}
506
507
508bool
Reid Spencer07adb282004-11-05 22:15:36 +0000509Path::createDirectory( bool create_parents) {
Reid Spencer8e665952004-08-29 05:24:01 +0000510 // Make sure we're dealing with a directory
Reid Spencer07adb282004-11-05 22:15:36 +0000511 if (!isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000512
513 // Get a writeable copy of the path name
514 char pathname[MAXPATHLEN];
515 path.copy(pathname,MAXPATHLEN);
516
517 // Null-terminate the last component
518 int lastchar = path.length() - 1 ;
519 if (pathname[lastchar] == '/')
520 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000521 else
522 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000523
524 // If we're supposed to create intermediate directories
525 if ( create_parents ) {
526 // Find the end of the initial name component
527 char * next = strchr(pathname,'/');
528 if ( pathname[0] == '/')
529 next = strchr(&pathname[1],'/');
530
531 // Loop through the directory components until we're done
532 while ( next != 0 ) {
533 *next = 0;
534 if (0 != access(pathname, F_OK | R_OK | W_OK))
535 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
536 ThrowErrno(std::string(pathname) + ": Can't create directory");
537 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000538 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000539 *save = '/';
540 }
Reid Spencer8e665952004-08-29 05:24:01 +0000541 }
Reid Spencereaf18152004-11-14 22:08:36 +0000542
543 if (0 != access(pathname, F_OK | R_OK))
544 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
545 ThrowErrno(std::string(pathname) + ": Can't create directory");
Reid Spencer8e665952004-08-29 05:24:01 +0000546 return true;
547}
548
549bool
Reid Spencer07adb282004-11-05 22:15:36 +0000550Path::createFile() {
Reid Spencer8e665952004-08-29 05:24:01 +0000551 // Make sure we're dealing with a file
Reid Spencer07adb282004-11-05 22:15:36 +0000552 if (!isFile()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000553
554 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000555 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
556 if (fd < 0)
Reid Spencer9195f372004-11-09 20:26:31 +0000557 ThrowErrno(path + ": Can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000558 ::close(fd);
Reid Spencer8e665952004-08-29 05:24:01 +0000559
560 return true;
Reid Spencerb89a2232004-08-25 06:20:07 +0000561}
562
Reid Spencer8e665952004-08-29 05:24:01 +0000563bool
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000564Path::createTemporaryFile(bool reuse_current) {
Reid Spencer9195f372004-11-09 20:26:31 +0000565 // Make sure we're dealing with a file
Reid Spencerc29befb2004-12-15 01:50:13 +0000566 if (!isFile())
567 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000568
Reid Spencerc29befb2004-12-15 01:50:13 +0000569 // Make this into a unique file name
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000570 makeUnique( reuse_current );
Reid Spencerc29befb2004-12-15 01:50:13 +0000571
572 // create the file
573 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
574 if (outFile != -1) {
575 ::close(outFile);
576 return true;
Reid Spencer9195f372004-11-09 20:26:31 +0000577 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000578 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000579}
580
581bool
Reid Spencer00e89302004-12-15 23:02:10 +0000582Path::destroyDirectory(bool remove_contents) const {
Reid Spencer8e665952004-08-29 05:24:01 +0000583 // Make sure we're dealing with a directory
Reid Spencer07adb282004-11-05 22:15:36 +0000584 if (!isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000585
586 // If it doesn't exist, we're done.
587 if (!exists()) return true;
588
589 if (remove_contents) {
590 // Recursively descend the directory to remove its content
591 std::string cmd("/bin/rm -rf ");
592 cmd += path;
593 system(cmd.c_str());
594 } else {
595 // Otherwise, try to just remove the one directory
596 char pathname[MAXPATHLEN];
597 path.copy(pathname,MAXPATHLEN);
598 int lastchar = path.length() - 1 ;
599 if (pathname[lastchar] == '/')
600 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000601 else
602 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000603 if ( 0 != rmdir(pathname))
604 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
605 }
606 return true;
607}
608
609bool
Reid Spencer00e89302004-12-15 23:02:10 +0000610Path::destroyFile() const {
Reid Spencer07adb282004-11-05 22:15:36 +0000611 if (!isFile()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000612 if (0 != unlink(path.c_str()))
Reid Spencereaf18152004-11-14 22:08:36 +0000613 ThrowErrno(path + ": Can't destroy file");
614 return true;
615}
616
617bool
618Path::renameFile(const Path& newName) {
619 if (!isFile()) return false;
620 if (0 != rename(path.c_str(), newName.c_str()))
Reid Spencer1fce0912004-12-11 00:14:15 +0000621 ThrowErrno(std::string("can't rename ") + path + " as " +
622 newName.toString());
Reid Spencereaf18152004-11-14 22:08:36 +0000623 return true;
624}
625
626bool
627Path::setStatusInfo(const StatusInfo& si) const {
628 if (!isFile()) return false;
629 struct utimbuf utb;
630 utb.actime = si.modTime.toPosixTime();
631 utb.modtime = utb.actime;
632 if (0 != ::utime(path.c_str(),&utb))
633 ThrowErrno(path + ": can't set file modification time");
634 if (0 != ::chmod(path.c_str(),si.mode))
635 ThrowErrno(path + ": can't set mode");
Reid Spencer8e665952004-08-29 05:24:01 +0000636 return true;
637}
638
Reid Spencerc29befb2004-12-15 01:50:13 +0000639void
Reid Spencer78076f62004-12-21 03:27:08 +0000640sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000641 int inFile = -1;
642 int outFile = -1;
643 try {
644 inFile = ::open(Src.c_str(), O_RDONLY);
645 if (inFile == -1)
646 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
647
648 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
649 if (outFile == -1)
650 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
651
652 char Buffer[16*1024];
653 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
654 if (Amt == -1) {
655 if (errno != EINTR && errno != EAGAIN)
656 ThrowErrno("Can't read source file: " + Src.toString());
657 } else {
658 char *BufPtr = Buffer;
659 while (Amt) {
660 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
661 if (AmtWritten == -1) {
662 if (errno != EINTR && errno != EAGAIN)
663 ThrowErrno("Can't write destination file: " + Dest.toString());
664 } else {
665 Amt -= AmtWritten;
666 BufPtr += AmtWritten;
667 }
668 }
669 }
670 }
671 ::close(inFile);
672 ::close(outFile);
673 } catch (...) {
674 if (inFile != -1)
675 ::close(inFile);
676 if (outFile != -1)
677 ::close(outFile);
678 throw;
679 }
680}
681
682void
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000683Path::makeUnique(bool reuse_current) {
684 if (reuse_current && !exists())
Reid Spencerc29befb2004-12-15 01:50:13 +0000685 return; // File doesn't exist already, just use it!
686
687 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
688 // mktemp or our own implementation.
689 char *FNBuffer = (char*) alloca(path.size()+8);
690 path.copy(FNBuffer,path.size());
691 strcpy(FNBuffer+path.size(), "-XXXXXX");
692
693#if defined(HAVE_MKSTEMP)
694 int TempFD;
695 if ((TempFD = mkstemp(FNBuffer)) == -1) {
696 ThrowErrno("Cannot make unique filename for '" + path + "'");
697 }
698
699 // We don't need to hold the temp file descriptor... we will trust that no one
700 // will overwrite/delete the file before we can open it again.
701 close(TempFD);
702
703 // Save the name
704 path = FNBuffer;
705#elif defined(HAVE_MKTEMP)
706 // If we don't have mkstemp, use the old and obsolete mktemp function.
707 if (mktemp(FNBuffer) == 0) {
708 ThrowErrno("Cannot make unique filename for '" + path + "'");
709 }
710
711 // Save the name
712 path = FNBuffer;
713#else
714 // Okay, looks like we have to do it all by our lonesome.
715 static unsigned FCounter = 0;
716 unsigned offset = path.size() + 1;
717 while ( FCounter < 999999 && exists()) {
718 sprintf(FNBuffer+offset,"%06u",++FCounter);
719 path = FNBuffer;
720 }
721 if (FCounter > 999999)
722 throw std::string("Cannot make unique filename for '" + path + "'");
723#endif
724
725}
Reid Spencerb89a2232004-08-25 06:20:07 +0000726}
727
728// vim: sw=2