blob: e0ca7df6f21add40b000da72a061a0d51359665c [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 Spencerb89a2232004-08-25 06:20:07 +000025
Reid Spencer8e665952004-08-29 05:24:01 +000026namespace llvm {
27using namespace sys;
Reid Spencerb89a2232004-08-25 06:20:07 +000028
Misha Brukman210b32b2004-12-20 00:16:38 +000029Path::Path(const std::string& unverified_path) : path(unverified_path) {
Reid Spencer8e665952004-08-29 05:24:01 +000030 if (unverified_path.empty())
31 return;
Reid Spencer07adb282004-11-05 22:15:36 +000032 if (this->isValid())
Reid Spencer8e665952004-08-29 05:24:01 +000033 return;
34 // oops, not valid.
35 path.clear();
36 ThrowErrno(unverified_path + ": path is not valid");
Reid Spencerb89a2232004-08-25 06:20:07 +000037}
38
Reid Spencer8e665952004-08-29 05:24:01 +000039Path
40Path::GetRootDirectory() {
41 Path result;
Reid Spencer07adb282004-11-05 22:15:36 +000042 result.setDirectory("/");
Reid Spencer8e665952004-08-29 05:24:01 +000043 return result;
44}
45
Reid Spencer1b6b99b2004-12-13 03:00:51 +000046static void getPathList(const char*path, std::vector<sys::Path>& Paths) {
47 const char* at = path;
48 const char* delim = strchr(at, ':');
49 Path tmpPath;
50 while( delim != 0 ) {
51 std::string tmp(at, size_t(delim-at));
52 if (tmpPath.setDirectory(tmp))
53 if (tmpPath.readable())
54 Paths.push_back(tmpPath);
55 at = delim + 1;
56 delim = strchr(at, ':');
Reid Spencer74e72612004-09-14 00:16:39 +000057 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +000058 if (*at != 0)
59 if (tmpPath.setDirectory(std::string(at)))
60 if (tmpPath.readable())
61 Paths.push_back(tmpPath);
62
Reid Spencer74e72612004-09-14 00:16:39 +000063}
Misha Brukman210b32b2004-12-20 00:16:38 +000064
Reid Spencer1b6b99b2004-12-13 03:00:51 +000065void
66Path::GetSystemLibraryPaths(std::vector<sys::Path>& Paths) {
67#ifdef LTDL_SHLIBPATH_VAR
68 char* env_var = getenv(LTDL_SHLIBPATH_VAR);
69 if (env_var != 0) {
70 getPathList(env_var,Paths);
Reid Spencer74e72612004-09-14 00:16:39 +000071 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +000072#endif
73 // FIXME: Should this look at LD_LIBRARY_PATH too?
74 Paths.push_back(sys::Path("/usr/local/lib/"));
75 Paths.push_back(sys::Path("/usr/X11R6/lib/"));
76 Paths.push_back(sys::Path("/usr/lib/"));
77 Paths.push_back(sys::Path("/lib/"));
Reid Spencer74e72612004-09-14 00:16:39 +000078}
79
Reid Spencer1b6b99b2004-12-13 03:00:51 +000080void
81Path::GetBytecodeLibraryPaths(std::vector<sys::Path>& Paths) {
82 char * env_var = getenv("LLVM_LIB_SEARCH_PATH");
83 if (env_var != 0) {
84 getPathList(env_var,Paths);
85 }
Reid Spencer1b6b99b2004-12-13 03:00:51 +000086#ifdef LLVM_LIBDIR
87 {
88 Path tmpPath;
89 if (tmpPath.setDirectory(LLVM_LIBDIR))
90 if (tmpPath.readable())
91 Paths.push_back(tmpPath);
92 }
93#endif
94 GetSystemLibraryPaths(Paths);
Reid Spencer8e665952004-08-29 05:24:01 +000095}
96
97Path
98Path::GetLLVMDefaultConfigDir() {
99 return Path("/etc/llvm/");
100}
101
Reid Spencer8e665952004-08-29 05:24:01 +0000102Path
103Path::GetUserHomeDirectory() {
104 const char* home = getenv("HOME");
105 if (home) {
106 Path result;
Reid Spencer07adb282004-11-05 22:15:36 +0000107 if (result.setDirectory(home))
Reid Spencer8e665952004-08-29 05:24:01 +0000108 return result;
109 }
110 return GetRootDirectory();
111}
112
113bool
Reid Spencer07adb282004-11-05 22:15:36 +0000114Path::isFile() const {
115 return (isValid() && path[path.length()-1] != '/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000116}
117
118bool
Reid Spencer07adb282004-11-05 22:15:36 +0000119Path::isDirectory() const {
120 return (isValid() && path[path.length()-1] == '/');
Reid Spencer1b554b42004-09-11 04:55:08 +0000121}
122
123std::string
Reid Spencer07adb282004-11-05 22:15:36 +0000124Path::getBasename() const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000125 // Find the last slash
126 size_t slash = path.rfind('/');
127 if (slash == std::string::npos)
128 slash = 0;
129 else
130 slash++;
131
132 return path.substr(slash, path.rfind('.'));
133}
134
Reid Spencer07adb282004-11-05 22:15:36 +0000135bool Path::hasMagicNumber(const std::string &Magic) const {
Reid Spencer1b554b42004-09-11 04:55:08 +0000136 size_t len = Magic.size();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000137 assert(len < 1024 && "Request for magic string too long");
138 char* buf = (char*) alloca(1 + len);
139 int fd = ::open(path.c_str(),O_RDONLY);
140 if (fd < 0)
141 return false;
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000142 size_t read_len = ::read(fd, buf, len);
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000143 close(fd);
Reid Spencer1b6b99b2004-12-13 03:00:51 +0000144 if (len != read_len)
145 return false;
Reid Spencer1b554b42004-09-11 04:55:08 +0000146 buf[len] = '\0';
147 return Magic == buf;
148}
149
Reid Spencereaf18152004-11-14 22:08:36 +0000150bool Path::getMagicNumber(std::string& Magic, unsigned len) const {
151 if (!isFile())
152 return false;
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000153 assert(len < 1024 && "Request for magic string too long");
154 char* buf = (char*) alloca(1 + len);
155 int fd = ::open(path.c_str(),O_RDONLY);
156 if (fd < 0)
157 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000158 ssize_t bytes_read = ::read(fd, buf, len);
159 ::close(fd);
160 if (ssize_t(len) != bytes_read) {
161 Magic.clear();
Reid Spencerbe31d2a2004-11-16 17:14:08 +0000162 return false;
Reid Spencer86ac2dc2004-12-02 09:09:48 +0000163 }
164 Magic.assign(buf,len);
Reid Spencereaf18152004-11-14 22:08:36 +0000165 return true;
166}
167
Reid Spencer1b554b42004-09-11 04:55:08 +0000168bool
Reid Spencer07adb282004-11-05 22:15:36 +0000169Path::isBytecodeFile() const {
Reid Spencer9195f372004-11-09 20:26:31 +0000170 char buffer[ 4];
171 buffer[0] = 0;
Reid Spencer1fce0912004-12-11 00:14:15 +0000172 int fd = ::open(path.c_str(),O_RDONLY);
173 if (fd < 0)
174 return false;
175 ssize_t bytes_read = ::read(fd, buffer, 4);
176 ::close(fd);
177 if (4 != bytes_read)
178 return false;
Reid Spencereaf18152004-11-14 22:08:36 +0000179
180 return (buffer[0] == 'l' && buffer[1] == 'l' && buffer[2] == 'v' &&
181 (buffer[3] == 'c' || buffer[3] == 'm'));
Reid Spencer1b554b42004-09-11 04:55:08 +0000182}
183
184bool
Reid Spencer8e665952004-08-29 05:24:01 +0000185Path::exists() const {
186 return 0 == access(path.c_str(), F_OK );
187}
188
189bool
190Path::readable() const {
191 return 0 == access(path.c_str(), F_OK | R_OK );
192}
193
194bool
195Path::writable() const {
196 return 0 == access(path.c_str(), F_OK | W_OK );
197}
198
199bool
200Path::executable() const {
201 return 0 == access(path.c_str(), R_OK | X_OK );
202}
203
204std::string
205Path::getLast() const {
206 // Find the last slash
207 size_t pos = path.rfind('/');
208
209 // Handle the corner cases
210 if (pos == std::string::npos)
211 return path;
212
213 // If the last character is a slash
214 if (pos == path.length()-1) {
215 // Find the second to last slash
216 size_t pos2 = path.rfind('/', pos-1);
217 if (pos2 == std::string::npos)
218 return path.substr(0,pos);
219 else
220 return path.substr(pos2+1,pos-pos2-1);
221 }
222 // Return everything after the last slash
223 return path.substr(pos+1);
224}
225
Reid Spencerb608a812004-11-16 06:15:19 +0000226void
227Path::getStatusInfo(StatusInfo& info) const {
Reid Spencer9195f372004-11-09 20:26:31 +0000228 struct stat buf;
229 if (0 != stat(path.c_str(), &buf)) {
230 ThrowErrno(std::string("Can't get status: ")+path);
231 }
232 info.fileSize = buf.st_size;
Reid Spencereaf18152004-11-14 22:08:36 +0000233 info.modTime.fromEpochTime(buf.st_mtime);
Reid Spencer9195f372004-11-09 20:26:31 +0000234 info.mode = buf.st_mode;
235 info.user = buf.st_uid;
236 info.group = buf.st_gid;
Reid Spencereaf18152004-11-14 22:08:36 +0000237 info.isDir = S_ISDIR(buf.st_mode);
238 if (info.isDir && path[path.length()-1] != '/')
239 path += '/';
240}
241
Reid Spencer77cc91d2004-12-13 19:59:50 +0000242static bool AddPermissionBits(const std::string& Filename, int bits) {
243 // Get the umask value from the operating system. We want to use it
244 // when changing the file's permissions. Since calling umask() sets
245 // the umask and returns its old value, we must call it a second
246 // time to reset it to the user's preference.
247 int mask = umask(0777); // The arg. to umask is arbitrary.
248 umask(mask); // Restore the umask.
249
250 // Get the file's current mode.
251 struct stat st;
252 if ((stat(Filename.c_str(), &st)) == -1)
253 return false;
254
255 // Change the file to have whichever permissions bits from 'bits'
256 // that the umask would not disable.
257 if ((chmod(Filename.c_str(), (st.st_mode | (bits & ~mask)))) == -1)
258 return false;
259
260 return true;
261}
262
263void Path::makeReadable() {
264 if (!AddPermissionBits(path,0444))
265 ThrowErrno(path + ": can't make file readable");
266}
267
268void Path::makeWriteable() {
269 if (!AddPermissionBits(path,0222))
270 ThrowErrno(path + ": can't make file writable");
271}
272
273void Path::makeExecutable() {
274 if (!AddPermissionBits(path,0111))
275 ThrowErrno(path + ": can't make file executable");
276}
277
Reid Spencereaf18152004-11-14 22:08:36 +0000278bool
Reid Spencerb608a812004-11-16 06:15:19 +0000279Path::getDirectoryContents(std::set<Path>& result) const {
Reid Spencereaf18152004-11-14 22:08:36 +0000280 if (!isDirectory())
281 return false;
282 DIR* direntries = ::opendir(path.c_str());
283 if (direntries == 0)
284 ThrowErrno(path + ": can't open directory");
285
286 result.clear();
287 struct dirent* de = ::readdir(direntries);
288 while (de != 0) {
289 if (de->d_name[0] != '.') {
290 Path aPath(path + (const char*)de->d_name);
291 struct stat buf;
292 if (0 != stat(aPath.path.c_str(), &buf))
293 ThrowErrno(aPath.path + ": can't get status");
294 if (S_ISDIR(buf.st_mode))
295 aPath.path += "/";
Reid Spencerb608a812004-11-16 06:15:19 +0000296 result.insert(aPath);
Reid Spencereaf18152004-11-14 22:08:36 +0000297 }
298 de = ::readdir(direntries);
299 }
300
301 closedir(direntries);
302 return true;
Reid Spencer9195f372004-11-09 20:26:31 +0000303}
304
Reid Spencer8e665952004-08-29 05:24:01 +0000305bool
Reid Spencer07adb282004-11-05 22:15:36 +0000306Path::setDirectory(const std::string& a_path) {
Reid Spencer8e665952004-08-29 05:24:01 +0000307 if (a_path.size() == 0)
308 return false;
309 Path save(*this);
310 path = a_path;
311 size_t last = a_path.size() -1;
Reid Spencer3d595cb2004-12-13 07:51:07 +0000312 if (a_path[last] != '/')
Reid Spencer8e665952004-08-29 05:24:01 +0000313 path += '/';
Reid Spencer07adb282004-11-05 22:15:36 +0000314 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000315 path = save.path;
316 return false;
317 }
318 return true;
319}
320
321bool
Reid Spencer07adb282004-11-05 22:15:36 +0000322Path::setFile(const std::string& a_path) {
Reid Spencer8e665952004-08-29 05:24:01 +0000323 if (a_path.size() == 0)
324 return false;
325 Path save(*this);
326 path = a_path;
327 size_t last = a_path.size() - 1;
328 while (last > 0 && a_path[last] == '/')
329 last--;
330 path.erase(last+1);
Reid Spencer07adb282004-11-05 22:15:36 +0000331 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000332 path = save.path;
333 return false;
334 }
335 return true;
336}
337
338bool
Reid Spencer07adb282004-11-05 22:15:36 +0000339Path::appendDirectory(const std::string& dir) {
340 if (isFile())
Reid Spencer8e665952004-08-29 05:24:01 +0000341 return false;
342 Path save(*this);
343 path += dir;
344 path += "/";
Reid Spencer07adb282004-11-05 22:15:36 +0000345 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000346 path = save.path;
347 return false;
348 }
349 return true;
350}
351
352bool
Reid Spencer07adb282004-11-05 22:15:36 +0000353Path::elideDirectory() {
354 if (isFile())
Reid Spencer8e665952004-08-29 05:24:01 +0000355 return false;
356 size_t slashpos = path.rfind('/',path.size());
357 if (slashpos == 0 || slashpos == std::string::npos)
358 return false;
359 if (slashpos == path.size() - 1)
360 slashpos = path.rfind('/',slashpos-1);
361 if (slashpos == std::string::npos)
362 return false;
363 path.erase(slashpos);
364 return true;
365}
366
367bool
Reid Spencer07adb282004-11-05 22:15:36 +0000368Path::appendFile(const std::string& file) {
369 if (!isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000370 return false;
371 Path save(*this);
372 path += file;
Reid Spencer07adb282004-11-05 22:15:36 +0000373 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000374 path = save.path;
375 return false;
376 }
377 return true;
378}
379
380bool
Reid Spencer07adb282004-11-05 22:15:36 +0000381Path::elideFile() {
382 if (isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000383 return false;
384 size_t slashpos = path.rfind('/',path.size());
385 if (slashpos == std::string::npos)
386 return false;
387 path.erase(slashpos+1);
388 return true;
389}
390
391bool
Reid Spencer07adb282004-11-05 22:15:36 +0000392Path::appendSuffix(const std::string& suffix) {
393 if (isDirectory())
Reid Spencer8e665952004-08-29 05:24:01 +0000394 return false;
395 Path save(*this);
396 path.append(".");
397 path.append(suffix);
Reid Spencer07adb282004-11-05 22:15:36 +0000398 if (!isValid()) {
Reid Spencer8e665952004-08-29 05:24:01 +0000399 path = save.path;
400 return false;
401 }
402 return true;
403}
404
405bool
Reid Spencer07adb282004-11-05 22:15:36 +0000406Path::elideSuffix() {
407 if (isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000408 size_t dotpos = path.rfind('.',path.size());
409 size_t slashpos = path.rfind('/',path.size());
410 if (slashpos != std::string::npos && dotpos != std::string::npos &&
411 dotpos > slashpos) {
412 path.erase(dotpos, path.size()-dotpos);
413 return true;
414 }
415 return false;
416}
417
418
419bool
Reid Spencer07adb282004-11-05 22:15:36 +0000420Path::createDirectory( bool create_parents) {
Reid Spencer8e665952004-08-29 05:24:01 +0000421 // Make sure we're dealing with a directory
Reid Spencer07adb282004-11-05 22:15:36 +0000422 if (!isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000423
424 // Get a writeable copy of the path name
425 char pathname[MAXPATHLEN];
426 path.copy(pathname,MAXPATHLEN);
427
428 // Null-terminate the last component
429 int lastchar = path.length() - 1 ;
430 if (pathname[lastchar] == '/')
431 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000432 else
433 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000434
435 // If we're supposed to create intermediate directories
436 if ( create_parents ) {
437 // Find the end of the initial name component
438 char * next = strchr(pathname,'/');
439 if ( pathname[0] == '/')
440 next = strchr(&pathname[1],'/');
441
442 // Loop through the directory components until we're done
443 while ( next != 0 ) {
444 *next = 0;
445 if (0 != access(pathname, F_OK | R_OK | W_OK))
446 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
447 ThrowErrno(std::string(pathname) + ": Can't create directory");
448 char* save = next;
Reid Spencereaf18152004-11-14 22:08:36 +0000449 next = strchr(next+1,'/');
Reid Spencer8e665952004-08-29 05:24:01 +0000450 *save = '/';
451 }
Reid Spencer8e665952004-08-29 05:24:01 +0000452 }
Reid Spencereaf18152004-11-14 22:08:36 +0000453
454 if (0 != access(pathname, F_OK | R_OK))
455 if (0 != mkdir(pathname, S_IRWXU | S_IRWXG))
456 ThrowErrno(std::string(pathname) + ": Can't create directory");
Reid Spencer8e665952004-08-29 05:24:01 +0000457 return true;
458}
459
460bool
Reid Spencer07adb282004-11-05 22:15:36 +0000461Path::createFile() {
Reid Spencer8e665952004-08-29 05:24:01 +0000462 // Make sure we're dealing with a file
Reid Spencer07adb282004-11-05 22:15:36 +0000463 if (!isFile()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000464
465 // Create the file
Reid Spencer622e2202004-09-18 19:25:11 +0000466 int fd = ::creat(path.c_str(), S_IRUSR | S_IWUSR);
467 if (fd < 0)
Reid Spencer9195f372004-11-09 20:26:31 +0000468 ThrowErrno(path + ": Can't create file");
Reid Spencer622e2202004-09-18 19:25:11 +0000469 ::close(fd);
Reid Spencer8e665952004-08-29 05:24:01 +0000470
471 return true;
Reid Spencerb89a2232004-08-25 06:20:07 +0000472}
473
Reid Spencer8e665952004-08-29 05:24:01 +0000474bool
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000475Path::createTemporaryFile(bool reuse_current) {
Reid Spencer9195f372004-11-09 20:26:31 +0000476 // Make sure we're dealing with a file
Reid Spencerc29befb2004-12-15 01:50:13 +0000477 if (!isFile())
478 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000479
Reid Spencerc29befb2004-12-15 01:50:13 +0000480 // Make this into a unique file name
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000481 makeUnique( reuse_current );
Reid Spencerc29befb2004-12-15 01:50:13 +0000482
483 // create the file
484 int outFile = ::open(path.c_str(), O_WRONLY|O_CREAT|O_TRUNC, 0666);
485 if (outFile != -1) {
486 ::close(outFile);
487 return true;
Reid Spencer9195f372004-11-09 20:26:31 +0000488 }
Reid Spencerc29befb2004-12-15 01:50:13 +0000489 return false;
Reid Spencer9195f372004-11-09 20:26:31 +0000490}
491
492bool
Reid Spencer00e89302004-12-15 23:02:10 +0000493Path::destroyDirectory(bool remove_contents) const {
Reid Spencer8e665952004-08-29 05:24:01 +0000494 // Make sure we're dealing with a directory
Reid Spencer07adb282004-11-05 22:15:36 +0000495 if (!isDirectory()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000496
497 // If it doesn't exist, we're done.
498 if (!exists()) return true;
499
500 if (remove_contents) {
501 // Recursively descend the directory to remove its content
502 std::string cmd("/bin/rm -rf ");
503 cmd += path;
504 system(cmd.c_str());
505 } else {
506 // Otherwise, try to just remove the one directory
507 char pathname[MAXPATHLEN];
508 path.copy(pathname,MAXPATHLEN);
509 int lastchar = path.length() - 1 ;
510 if (pathname[lastchar] == '/')
511 pathname[lastchar] = 0;
Reid Spencereaf18152004-11-14 22:08:36 +0000512 else
513 pathname[lastchar+1] = 0;
Reid Spencer8e665952004-08-29 05:24:01 +0000514 if ( 0 != rmdir(pathname))
515 ThrowErrno(std::string(pathname) + ": Can't destroy directory");
516 }
517 return true;
518}
519
520bool
Reid Spencer00e89302004-12-15 23:02:10 +0000521Path::destroyFile() const {
Reid Spencer07adb282004-11-05 22:15:36 +0000522 if (!isFile()) return false;
Reid Spencer8e665952004-08-29 05:24:01 +0000523 if (0 != unlink(path.c_str()))
Reid Spencereaf18152004-11-14 22:08:36 +0000524 ThrowErrno(path + ": Can't destroy file");
525 return true;
526}
527
528bool
529Path::renameFile(const Path& newName) {
530 if (!isFile()) return false;
531 if (0 != rename(path.c_str(), newName.c_str()))
Reid Spencer1fce0912004-12-11 00:14:15 +0000532 ThrowErrno(std::string("can't rename ") + path + " as " +
533 newName.toString());
Reid Spencereaf18152004-11-14 22:08:36 +0000534 return true;
535}
536
537bool
538Path::setStatusInfo(const StatusInfo& si) const {
539 if (!isFile()) return false;
540 struct utimbuf utb;
541 utb.actime = si.modTime.toPosixTime();
542 utb.modtime = utb.actime;
543 if (0 != ::utime(path.c_str(),&utb))
544 ThrowErrno(path + ": can't set file modification time");
545 if (0 != ::chmod(path.c_str(),si.mode))
546 ThrowErrno(path + ": can't set mode");
Reid Spencer8e665952004-08-29 05:24:01 +0000547 return true;
548}
549
Reid Spencerc29befb2004-12-15 01:50:13 +0000550void
Reid Spencer78076f62004-12-21 03:27:08 +0000551sys::CopyFile(const sys::Path &Dest, const sys::Path &Src) {
Reid Spencerc29befb2004-12-15 01:50:13 +0000552 int inFile = -1;
553 int outFile = -1;
554 try {
555 inFile = ::open(Src.c_str(), O_RDONLY);
556 if (inFile == -1)
557 ThrowErrno("Cannnot open source file to copy: " + Src.toString());
558
559 outFile = ::open(Dest.c_str(), O_WRONLY|O_CREAT, 0666);
560 if (outFile == -1)
561 ThrowErrno("Cannnot create destination file for copy: " +Dest.toString());
562
563 char Buffer[16*1024];
564 while (ssize_t Amt = ::read(inFile, Buffer, 16*1024)) {
565 if (Amt == -1) {
566 if (errno != EINTR && errno != EAGAIN)
567 ThrowErrno("Can't read source file: " + Src.toString());
568 } else {
569 char *BufPtr = Buffer;
570 while (Amt) {
571 ssize_t AmtWritten = ::write(outFile, BufPtr, Amt);
572 if (AmtWritten == -1) {
573 if (errno != EINTR && errno != EAGAIN)
574 ThrowErrno("Can't write destination file: " + Dest.toString());
575 } else {
576 Amt -= AmtWritten;
577 BufPtr += AmtWritten;
578 }
579 }
580 }
581 }
582 ::close(inFile);
583 ::close(outFile);
584 } catch (...) {
585 if (inFile != -1)
586 ::close(inFile);
587 if (outFile != -1)
588 ::close(outFile);
589 throw;
590 }
591}
592
593void
Reid Spencer07f9f4e2004-12-15 08:32:45 +0000594Path::makeUnique(bool reuse_current) {
595 if (reuse_current && !exists())
Reid Spencerc29befb2004-12-15 01:50:13 +0000596 return; // File doesn't exist already, just use it!
597
598 // Append an XXXXXX pattern to the end of the file for use with mkstemp,
599 // mktemp or our own implementation.
600 char *FNBuffer = (char*) alloca(path.size()+8);
601 path.copy(FNBuffer,path.size());
602 strcpy(FNBuffer+path.size(), "-XXXXXX");
603
604#if defined(HAVE_MKSTEMP)
605 int TempFD;
606 if ((TempFD = mkstemp(FNBuffer)) == -1) {
607 ThrowErrno("Cannot make unique filename for '" + path + "'");
608 }
609
610 // We don't need to hold the temp file descriptor... we will trust that no one
611 // will overwrite/delete the file before we can open it again.
612 close(TempFD);
613
614 // Save the name
615 path = FNBuffer;
616#elif defined(HAVE_MKTEMP)
617 // If we don't have mkstemp, use the old and obsolete mktemp function.
618 if (mktemp(FNBuffer) == 0) {
619 ThrowErrno("Cannot make unique filename for '" + path + "'");
620 }
621
622 // Save the name
623 path = FNBuffer;
624#else
625 // Okay, looks like we have to do it all by our lonesome.
626 static unsigned FCounter = 0;
627 unsigned offset = path.size() + 1;
628 while ( FCounter < 999999 && exists()) {
629 sprintf(FNBuffer+offset,"%06u",++FCounter);
630 path = FNBuffer;
631 }
632 if (FCounter > 999999)
633 throw std::string("Cannot make unique filename for '" + path + "'");
634#endif
635
636}
Reid Spencerb89a2232004-08-25 06:20:07 +0000637}
638
639// vim: sw=2