Support/PathV2: Move current_path from path to fs and fix the Unix implementation.
[oota-llvm.git] / lib / Support / Unix / PathV2.inc
1 //===- llvm/Support/Unix/PathV2.cpp - Unix Path Implementation --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific implementation of the PathV2 API.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Unix.h"
20 #if HAVE_SYS_STAT_H
21 #include <sys/stat.h>
22 #endif
23 #if HAVE_FCNTL_H
24 #include <fcntl.h>
25 #endif
26 #if HAVE_STDIO_H
27 #include <stdio.h>
28 #endif
29
30 using namespace llvm;
31
32 namespace {
33   struct AutoFD {
34     int FileDescriptor;
35
36     AutoFD(int fd) : FileDescriptor(fd) {}
37     ~AutoFD() {
38       if (FileDescriptor >= 0)
39         ::close(FileDescriptor);
40     }
41
42     int take() {
43       int ret = FileDescriptor;
44       FileDescriptor = -1;
45       return ret;
46     }
47
48     operator int() const {return FileDescriptor;}
49   };
50
51   error_code TempDir(SmallVectorImpl<char> &result) {
52     // FIXME: Don't use TMPDIR if program is SUID or SGID enabled.
53     const char *dir = 0;
54     (dir = std::getenv("TMPDIR" )) ||
55     (dir = std::getenv("TMP"    )) ||
56     (dir = std::getenv("TEMP"   )) ||
57     (dir = std::getenv("TEMPDIR")) ||
58 #ifdef P_tmpdir
59     (dir = P_tmpdir) ||
60 #endif
61     (dir = "/tmp");
62
63     result.set_size(0);
64     StringRef d(dir);
65     result.append(d.begin(), d.end());
66     return success;
67   }
68 }
69
70 namespace llvm {
71 namespace sys  {
72 namespace fs {
73
74 error_code current_path(SmallVectorImpl<char> &result) {
75   result.reserve(MAXPATHLEN);
76
77   while (true) {
78     if (::getcwd(result.data(), result.capacity()) == 0) {
79       // See if there was a real error.
80       if (errno != errc::not_enough_memory)
81         return error_code(errno, system_category());
82       // Otherwise there just wasn't enough space.
83       result.reserve(result.capacity() * 2);
84     } else
85       break;
86   }
87
88   result.set_size(strlen(result.data()));
89   return success;
90 }
91
92 error_code copy_file(const Twine &from, const Twine &to, copy_option copt) {
93  // Get arguments.
94   SmallString<128> from_storage;
95   SmallString<128> to_storage;
96   StringRef f = from.toNullTerminatedStringRef(from_storage);
97   StringRef t = to.toNullTerminatedStringRef(to_storage);
98
99   const size_t buf_sz = 32768;
100   char buffer[buf_sz];
101   int from_file = -1, to_file = -1;
102
103   // Open from.
104   if ((from_file = ::open(f.begin(), O_RDONLY)) < 0)
105     return error_code(errno, system_category());
106   AutoFD from_fd(from_file);
107
108   // Stat from.
109   struct stat from_stat;
110   if (::stat(f.begin(), &from_stat) != 0)
111     return error_code(errno, system_category());
112
113   // Setup to flags.
114   int to_flags = O_CREAT | O_WRONLY;
115   if (copt == copy_option::fail_if_exists)
116     to_flags |= O_EXCL;
117
118   // Open to.
119   if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0)
120     return error_code(errno, system_category());
121   AutoFD to_fd(to_file);
122
123   // Copy!
124   ssize_t sz, sz_read = 1, sz_write;
125   while (sz_read > 0 &&
126          (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) {
127     // Allow for partial writes - see Advanced Unix Programming (2nd Ed.),
128     // Marc Rochkind, Addison-Wesley, 2004, page 94
129     sz_write = 0;
130     do {
131       if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) {
132         sz_read = sz;  // cause read loop termination.
133         break;         // error.
134       }
135       sz_write += sz;
136     } while (sz_write < sz_read);
137   }
138
139   // After all the file operations above the return value of close actually
140   // matters.
141   if (::close(from_fd.take()) < 0) sz_read = -1;
142   if (::close(to_fd.take()) < 0) sz_read = -1;
143
144   // Check for errors.
145   if (sz_read < 0)
146     return error_code(errno, system_category());
147
148   return success;
149 }
150
151 error_code create_directory(const Twine &path, bool &existed) {
152   SmallString<128> path_storage;
153   StringRef p = path.toNullTerminatedStringRef(path_storage);
154
155   if (::mkdir(p.begin(), 0700) == -1) {
156     if (errno != errc::file_exists)
157       return error_code(errno, system_category());
158     existed = true;
159   } else
160     existed = false;
161
162   return success;
163 }
164
165 error_code create_hard_link(const Twine &to, const Twine &from) {
166   // Get arguments.
167   SmallString<128> from_storage;
168   SmallString<128> to_storage;
169   StringRef f = from.toNullTerminatedStringRef(from_storage);
170   StringRef t = to.toNullTerminatedStringRef(to_storage);
171
172   if (::link(t.begin(), f.begin()) == -1)
173     return error_code(errno, system_category());
174
175   return success;
176 }
177
178 error_code create_symlink(const Twine &to, const Twine &from) {
179   // Get arguments.
180   SmallString<128> from_storage;
181   SmallString<128> to_storage;
182   StringRef f = from.toNullTerminatedStringRef(from_storage);
183   StringRef t = to.toNullTerminatedStringRef(to_storage);
184
185   if (::symlink(t.begin(), f.begin()) == -1)
186     return error_code(errno, system_category());
187
188   return success;
189 }
190
191 error_code remove(const Twine &path, bool &existed) {
192   SmallString<128> path_storage;
193   StringRef p = path.toNullTerminatedStringRef(path_storage);
194
195   if (::remove(p.begin()) == -1) {
196     if (errno != errc::no_such_file_or_directory)
197       return error_code(errno, system_category());
198     existed = false;
199   } else
200     existed = true;
201
202   return success;
203 }
204
205 error_code rename(const Twine &from, const Twine &to) {
206   // Get arguments.
207   SmallString<128> from_storage;
208   SmallString<128> to_storage;
209   StringRef f = from.toNullTerminatedStringRef(from_storage);
210   StringRef t = to.toNullTerminatedStringRef(to_storage);
211
212   if (::rename(f.begin(), t.begin()) == -1)
213     return error_code(errno, system_category());
214
215   return success;
216 }
217
218 error_code resize_file(const Twine &path, uint64_t size) {
219   SmallString<128> path_storage;
220   StringRef p = path.toNullTerminatedStringRef(path_storage);
221
222   if (::truncate(p.begin(), size) == -1)
223     return error_code(errno, system_category());
224
225   return success;
226 }
227
228 error_code exists(const Twine &path, bool &result) {
229   SmallString<128> path_storage;
230   StringRef p = path.toNullTerminatedStringRef(path_storage);
231
232   struct stat status;
233   if (::stat(p.begin(), &status) == -1) {
234     if (errno != errc::no_such_file_or_directory)
235       return error_code(errno, system_category());
236     result = false;
237   } else
238     result = true;
239
240   return success;
241 }
242
243 error_code equivalent(const Twine &A, const Twine &B, bool &result) {
244   // Get arguments.
245   SmallString<128> a_storage;
246   SmallString<128> b_storage;
247   StringRef a = A.toNullTerminatedStringRef(a_storage);
248   StringRef b = B.toNullTerminatedStringRef(b_storage);
249
250   struct stat stat_a, stat_b;
251   int error_b = ::stat(b.begin(), &stat_b);
252   int error_a = ::stat(a.begin(), &stat_a);
253
254   // If both are invalid, it's an error. If only one is, the result is false.
255   if (error_a != 0 || error_b != 0) {
256     if (error_a == error_b)
257       return error_code(errno, system_category());
258     result = false;
259   } else {
260     result =
261       stat_a.st_dev == stat_b.st_dev &&
262       stat_a.st_ino == stat_b.st_ino;
263   }
264
265   return success;
266 }
267
268 error_code file_size(const Twine &path, uint64_t &result) {
269   SmallString<128> path_storage;
270   StringRef p = path.toNullTerminatedStringRef(path_storage);
271
272   struct stat status;
273   if (::stat(p.begin(), &status) == -1)
274     return error_code(errno, system_category());
275   if (!S_ISREG(status.st_mode))
276     return make_error_code(errc::operation_not_permitted);
277
278   result = status.st_size;
279   return success;
280 }
281
282 error_code status(const Twine &path, file_status &result) {
283   SmallString<128> path_storage;
284   StringRef p = path.toNullTerminatedStringRef(path_storage);
285
286   struct stat status;
287   if (::stat(p.begin(), &status) != 0) {
288     error_code ec(errno, system_category());
289     if (ec == errc::no_such_file_or_directory)
290       result = file_status(file_type::file_not_found);
291     else
292       result = file_status(file_type::status_error);
293     return ec;
294   }
295
296   if (S_ISDIR(status.st_mode))
297     result = file_status(file_type::directory_file);
298   else if (S_ISREG(status.st_mode))
299     result = file_status(file_type::regular_file);
300   else if (S_ISBLK(status.st_mode))
301     result = file_status(file_type::block_file);
302   else if (S_ISCHR(status.st_mode))
303     result = file_status(file_type::character_file);
304   else if (S_ISFIFO(status.st_mode))
305     result = file_status(file_type::fifo_file);
306   else if (S_ISSOCK(status.st_mode))
307     result = file_status(file_type::socket_file);
308   else
309     result = file_status(file_type::type_unknown);
310
311   return success;
312 }
313
314 error_code unique_file(const Twine &model, int &result_fd,
315                              SmallVectorImpl<char> &result_path) {
316   SmallString<128> Model;
317   model.toVector(Model);
318   // Null terminate.
319   Model.c_str();
320
321   // Make model absolute by prepending a temp directory if it's not already.
322   bool absolute;
323   if (error_code ec = path::is_absolute(Twine(Model), absolute)) return ec;
324   if (!absolute) {
325     SmallString<128> TDir;
326     if (error_code ec = TempDir(TDir)) return ec;
327     if (error_code ec = path::append(TDir, Twine(Model))) return ec;
328     Model.swap(TDir);
329   }
330
331   // Replace '%' with random chars. From here on, DO NOT modify model. It may be
332   // needed if the randomly chosen path already exists.
333   SmallString<128> RandomPath;
334   RandomPath.reserve(Model.size() + 1);
335   ::srand(::time(NULL));
336
337 retry_random_path:
338   // This is opened here instead of above to make it easier to track when to
339   // close it. Collisions should be rare enough for the possible extra syscalls
340   // not to matter.
341   FILE *RandomSource = ::fopen("/dev/urandom", "r");
342   RandomPath.set_size(0);
343   for (SmallVectorImpl<char>::const_iterator i = Model.begin(),
344                                              e = Model.end(); i != e; ++i) {
345     if (*i == '%') {
346       char val = 0;
347       if (RandomSource)
348         val = fgetc(RandomSource);
349       else
350         val = ::rand();
351       RandomPath.push_back("0123456789abcdef"[val & 15]);
352     } else
353       RandomPath.push_back(*i);
354   }
355
356   if (RandomSource)
357     ::fclose(RandomSource);
358
359   // Try to open + create the file.
360 rety_open_create:
361   int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600);
362   if (RandomFD == -1) {
363     // If the file existed, try again, otherwise, error.
364     if (errno == errc::file_exists)
365       goto retry_random_path;
366     // The path prefix doesn't exist.
367     if (errno == errc::no_such_file_or_directory) {
368       StringRef p(RandomPath.begin(), RandomPath.size());
369       SmallString<64> dir_to_create;
370       for (path::const_iterator i = path::begin(p),
371                                 e = --path::end(p); i != e; ++i) {
372         if (error_code ec = path::append(dir_to_create, *i)) return ec;
373         bool Exists;
374         if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec;
375         if (!Exists) {
376           // Don't try to create network paths.
377           if (i->size() > 2 && (*i)[0] == '/' &&
378                                (*i)[1] == '/' &&
379                                (*i)[2] != '/')
380             return make_error_code(errc::no_such_file_or_directory);
381           if (::mkdir(dir_to_create.c_str(), 0700) == -1)
382             return error_code(errno, system_category());
383         }
384       }
385       goto rety_open_create;
386     }
387     return error_code(errno, system_category());
388   }
389
390    // Make the path absolute.
391   char real_path_buff[PATH_MAX + 1];
392   if (realpath(RandomPath.c_str(), real_path_buff) == NULL) {
393     ::close(RandomFD);
394     ::unlink(RandomPath.c_str());
395     return error_code(errno, system_category());
396   }
397
398   result_path.set_size(0);
399   StringRef d(real_path_buff);
400   result_path.append(d.begin(), d.end());
401
402   result_fd = RandomFD;
403   return success;
404 }
405
406 } // end namespace fs
407 } // end namespace sys
408 } // end namespace llvm