PathV2.inc revision e1db1b8d4ee9c7584a2c1b3c79b0c01e468398dc
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_DIRENT_H 27# include <dirent.h> 28# define NAMLEN(dirent) strlen((dirent)->d_name) 29#else 30# define dirent direct 31# define NAMLEN(dirent) (dirent)->d_namlen 32# if HAVE_SYS_NDIR_H 33# include <sys/ndir.h> 34# endif 35# if HAVE_SYS_DIR_H 36# include <sys/dir.h> 37# endif 38# if HAVE_NDIR_H 39# include <ndir.h> 40# endif 41#endif 42#if HAVE_STDIO_H 43#include <stdio.h> 44#endif 45 46using namespace llvm; 47 48namespace { 49 /// This class automatically closes the given file descriptor when it goes out 50 /// of scope. You can take back explicit ownership of the file descriptor by 51 /// calling take(). The destructor does not verify that close was successful. 52 /// Therefore, never allow this class to call close on a file descriptor that 53 /// has been read from or written to. 54 struct AutoFD { 55 int FileDescriptor; 56 57 AutoFD(int fd) : FileDescriptor(fd) {} 58 ~AutoFD() { 59 if (FileDescriptor >= 0) 60 ::close(FileDescriptor); 61 } 62 63 int take() { 64 int ret = FileDescriptor; 65 FileDescriptor = -1; 66 return ret; 67 } 68 69 operator int() const {return FileDescriptor;} 70 }; 71 72 error_code TempDir(SmallVectorImpl<char> &result) { 73 // FIXME: Don't use TMPDIR if program is SUID or SGID enabled. 74 const char *dir = 0; 75 (dir = std::getenv("TMPDIR" )) || 76 (dir = std::getenv("TMP" )) || 77 (dir = std::getenv("TEMP" )) || 78 (dir = std::getenv("TEMPDIR")) || 79#ifdef P_tmpdir 80 (dir = P_tmpdir) || 81#endif 82 (dir = "/tmp"); 83 84 result.clear(); 85 StringRef d(dir); 86 result.append(d.begin(), d.end()); 87 return success; 88 } 89} 90 91namespace llvm { 92namespace sys { 93namespace fs { 94 95error_code current_path(SmallVectorImpl<char> &result) { 96 // Reserve an arbitrary amount of space. 97 result.reserve(128); 98 99 while (true) { 100 if (::getcwd(result.data(), result.capacity()) == 0) { 101 // See if there was a real error. 102 if (errno != errc::not_enough_memory) 103 return error_code(errno, system_category()); 104 // Otherwise there just wasn't enough space. 105 result.reserve(result.capacity() * 2); 106 } else 107 break; 108 } 109 110 result.set_size(strlen(result.data())); 111 return success; 112} 113 114error_code copy_file(const Twine &from, const Twine &to, copy_option copt) { 115 // Get arguments. 116 SmallString<128> from_storage; 117 SmallString<128> to_storage; 118 StringRef f = from.toNullTerminatedStringRef(from_storage); 119 StringRef t = to.toNullTerminatedStringRef(to_storage); 120 121 const size_t buf_sz = 32768; 122 char buffer[buf_sz]; 123 int from_file = -1, to_file = -1; 124 125 // Open from. 126 if ((from_file = ::open(f.begin(), O_RDONLY)) < 0) 127 return error_code(errno, system_category()); 128 AutoFD from_fd(from_file); 129 130 // Stat from. 131 struct stat from_stat; 132 if (::stat(f.begin(), &from_stat) != 0) 133 return error_code(errno, system_category()); 134 135 // Setup to flags. 136 int to_flags = O_CREAT | O_WRONLY; 137 if (copt == copy_option::fail_if_exists) 138 to_flags |= O_EXCL; 139 140 // Open to. 141 if ((to_file = ::open(t.begin(), to_flags, from_stat.st_mode)) < 0) 142 return error_code(errno, system_category()); 143 AutoFD to_fd(to_file); 144 145 // Copy! 146 ssize_t sz, sz_read = 1, sz_write; 147 while (sz_read > 0 && 148 (sz_read = ::read(from_fd, buffer, buf_sz)) > 0) { 149 // Allow for partial writes - see Advanced Unix Programming (2nd Ed.), 150 // Marc Rochkind, Addison-Wesley, 2004, page 94 151 sz_write = 0; 152 do { 153 if ((sz = ::write(to_fd, buffer + sz_write, sz_read - sz_write)) < 0) { 154 sz_read = sz; // cause read loop termination. 155 break; // error. 156 } 157 sz_write += sz; 158 } while (sz_write < sz_read); 159 } 160 161 // After all the file operations above the return value of close actually 162 // matters. 163 if (::close(from_fd.take()) < 0) sz_read = -1; 164 if (::close(to_fd.take()) < 0) sz_read = -1; 165 166 // Check for errors. 167 if (sz_read < 0) 168 return error_code(errno, system_category()); 169 170 return success; 171} 172 173error_code create_directory(const Twine &path, bool &existed) { 174 SmallString<128> path_storage; 175 StringRef p = path.toNullTerminatedStringRef(path_storage); 176 177 if (::mkdir(p.begin(), S_IRWXU | S_IRWXG) == -1) { 178 if (errno != errc::file_exists) 179 return error_code(errno, system_category()); 180 existed = true; 181 } else 182 existed = false; 183 184 return success; 185} 186 187error_code create_hard_link(const Twine &to, const Twine &from) { 188 // Get arguments. 189 SmallString<128> from_storage; 190 SmallString<128> to_storage; 191 StringRef f = from.toNullTerminatedStringRef(from_storage); 192 StringRef t = to.toNullTerminatedStringRef(to_storage); 193 194 if (::link(t.begin(), f.begin()) == -1) 195 return error_code(errno, system_category()); 196 197 return success; 198} 199 200error_code create_symlink(const Twine &to, const Twine &from) { 201 // Get arguments. 202 SmallString<128> from_storage; 203 SmallString<128> to_storage; 204 StringRef f = from.toNullTerminatedStringRef(from_storage); 205 StringRef t = to.toNullTerminatedStringRef(to_storage); 206 207 if (::symlink(t.begin(), f.begin()) == -1) 208 return error_code(errno, system_category()); 209 210 return success; 211} 212 213error_code remove(const Twine &path, bool &existed) { 214 SmallString<128> path_storage; 215 StringRef p = path.toNullTerminatedStringRef(path_storage); 216 217 if (::remove(p.begin()) == -1) { 218 if (errno != errc::no_such_file_or_directory) 219 return error_code(errno, system_category()); 220 existed = false; 221 } else 222 existed = true; 223 224 return success; 225} 226 227error_code rename(const Twine &from, const Twine &to) { 228 // Get arguments. 229 SmallString<128> from_storage; 230 SmallString<128> to_storage; 231 StringRef f = from.toNullTerminatedStringRef(from_storage); 232 StringRef t = to.toNullTerminatedStringRef(to_storage); 233 234 if (::rename(f.begin(), t.begin()) == -1) { 235 // If it's a cross device link, copy then delete, otherwise return the error 236 if (errno == EXDEV) { 237 if (error_code ec = copy_file(from, to, copy_option::overwrite_if_exists)) 238 return ec; 239 bool Existed; 240 if (error_code ec = remove(from, Existed)) 241 return ec; 242 } else 243 return error_code(errno, system_category()); 244 } 245 246 return success; 247} 248 249error_code resize_file(const Twine &path, uint64_t size) { 250 SmallString<128> path_storage; 251 StringRef p = path.toNullTerminatedStringRef(path_storage); 252 253 if (::truncate(p.begin(), size) == -1) 254 return error_code(errno, system_category()); 255 256 return success; 257} 258 259error_code exists(const Twine &path, bool &result) { 260 SmallString<128> path_storage; 261 StringRef p = path.toNullTerminatedStringRef(path_storage); 262 263 struct stat status; 264 if (::stat(p.begin(), &status) == -1) { 265 if (errno != errc::no_such_file_or_directory) 266 return error_code(errno, system_category()); 267 result = false; 268 } else 269 result = true; 270 271 return success; 272} 273 274error_code equivalent(const Twine &A, const Twine &B, bool &result) { 275 // Get arguments. 276 SmallString<128> a_storage; 277 SmallString<128> b_storage; 278 StringRef a = A.toNullTerminatedStringRef(a_storage); 279 StringRef b = B.toNullTerminatedStringRef(b_storage); 280 281 struct stat stat_a, stat_b; 282 int error_b = ::stat(b.begin(), &stat_b); 283 int error_a = ::stat(a.begin(), &stat_a); 284 285 // If both are invalid, it's an error. If only one is, the result is false. 286 if (error_a != 0 || error_b != 0) { 287 if (error_a == error_b) 288 return error_code(errno, system_category()); 289 result = false; 290 } else { 291 result = 292 stat_a.st_dev == stat_b.st_dev && 293 stat_a.st_ino == stat_b.st_ino; 294 } 295 296 return success; 297} 298 299error_code file_size(const Twine &path, uint64_t &result) { 300 SmallString<128> path_storage; 301 StringRef p = path.toNullTerminatedStringRef(path_storage); 302 303 struct stat status; 304 if (::stat(p.begin(), &status) == -1) 305 return error_code(errno, system_category()); 306 if (!S_ISREG(status.st_mode)) 307 return make_error_code(errc::operation_not_permitted); 308 309 result = status.st_size; 310 return success; 311} 312 313error_code status(const Twine &path, file_status &result) { 314 SmallString<128> path_storage; 315 StringRef p = path.toNullTerminatedStringRef(path_storage); 316 317 struct stat status; 318 if (::stat(p.begin(), &status) != 0) { 319 error_code ec(errno, system_category()); 320 if (ec == errc::no_such_file_or_directory) 321 result = file_status(file_type::file_not_found); 322 else 323 result = file_status(file_type::status_error); 324 return ec; 325 } 326 327 if (S_ISDIR(status.st_mode)) 328 result = file_status(file_type::directory_file); 329 else if (S_ISREG(status.st_mode)) 330 result = file_status(file_type::regular_file); 331 else if (S_ISBLK(status.st_mode)) 332 result = file_status(file_type::block_file); 333 else if (S_ISCHR(status.st_mode)) 334 result = file_status(file_type::character_file); 335 else if (S_ISFIFO(status.st_mode)) 336 result = file_status(file_type::fifo_file); 337 else if (S_ISSOCK(status.st_mode)) 338 result = file_status(file_type::socket_file); 339 else 340 result = file_status(file_type::type_unknown); 341 342 return success; 343} 344 345error_code unique_file(const Twine &model, int &result_fd, 346 SmallVectorImpl<char> &result_path) { 347 SmallString<128> Model; 348 model.toVector(Model); 349 // Null terminate. 350 Model.c_str(); 351 352 // Make model absolute by prepending a temp directory if it's not already. 353 bool absolute = path::is_absolute(Twine(Model)); 354 if (!absolute) { 355 SmallString<128> TDir; 356 if (error_code ec = TempDir(TDir)) return ec; 357 path::append(TDir, Twine(Model)); 358 Model.swap(TDir); 359 } 360 361 // Replace '%' with random chars. From here on, DO NOT modify model. It may be 362 // needed if the randomly chosen path already exists. 363 SmallString<128> RandomPath; 364 RandomPath.reserve(Model.size() + 1); 365 ::srand(::time(NULL)); 366 367retry_random_path: 368 // This is opened here instead of above to make it easier to track when to 369 // close it. Collisions should be rare enough for the possible extra syscalls 370 // not to matter. 371 FILE *RandomSource = ::fopen("/dev/urandom", "r"); 372 RandomPath.set_size(0); 373 for (SmallVectorImpl<char>::const_iterator i = Model.begin(), 374 e = Model.end(); i != e; ++i) { 375 if (*i == '%') { 376 char val = 0; 377 if (RandomSource) 378 val = fgetc(RandomSource); 379 else 380 val = ::rand(); 381 RandomPath.push_back("0123456789abcdef"[val & 15]); 382 } else 383 RandomPath.push_back(*i); 384 } 385 386 if (RandomSource) 387 ::fclose(RandomSource); 388 389 // Try to open + create the file. 390rety_open_create: 391 int RandomFD = ::open(RandomPath.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); 392 if (RandomFD == -1) { 393 // If the file existed, try again, otherwise, error. 394 if (errno == errc::file_exists) 395 goto retry_random_path; 396 // The path prefix doesn't exist. 397 if (errno == errc::no_such_file_or_directory) { 398 StringRef p(RandomPath.begin(), RandomPath.size()); 399 SmallString<64> dir_to_create; 400 for (path::const_iterator i = path::begin(p), 401 e = --path::end(p); i != e; ++i) { 402 path::append(dir_to_create, *i); 403 bool Exists; 404 if (error_code ec = exists(Twine(dir_to_create), Exists)) return ec; 405 if (!Exists) { 406 // Don't try to create network paths. 407 if (i->size() > 2 && (*i)[0] == '/' && 408 (*i)[1] == '/' && 409 (*i)[2] != '/') 410 return make_error_code(errc::no_such_file_or_directory); 411 if (::mkdir(dir_to_create.c_str(), 0700) == -1) 412 return error_code(errno, system_category()); 413 } 414 } 415 goto rety_open_create; 416 } 417 return error_code(errno, system_category()); 418 } 419 420 // Make the path absolute. 421 if (error_code ec = make_absolute(RandomPath)) { 422 ::close(RandomFD); 423 ::unlink(RandomPath.c_str()); 424 return ec; 425 } 426 427 result_path = RandomPath; 428 result_fd = RandomFD; 429 return success; 430} 431 432error_code directory_iterator_construct(directory_iterator &it, StringRef path){ 433 SmallString<128> path_null(path); 434 DIR *directory = ::opendir(path_null.c_str()); 435 if (directory == 0) 436 return error_code(errno, system_category()); 437 438 it.IterationHandle = reinterpret_cast<intptr_t>(directory); 439 // Add something for replace_filename to replace. 440 path::append(path_null, "."); 441 it.CurrentEntry = directory_entry(path_null.str()); 442 return directory_iterator_increment(it); 443} 444 445error_code directory_iterator_destruct(directory_iterator& it) { 446 if (it.IterationHandle) 447 ::closedir(reinterpret_cast<DIR *>(it.IterationHandle)); 448 it.IterationHandle = 0; 449 it.CurrentEntry = directory_entry(); 450 return success; 451} 452 453error_code directory_iterator_increment(directory_iterator& it) { 454 errno = 0; 455 dirent *cur_dir = ::readdir(reinterpret_cast<DIR *>(it.IterationHandle)); 456 if (cur_dir == 0 && errno != 0) { 457 return error_code(errno, system_category()); 458 } else if (cur_dir != 0) { 459 StringRef name(cur_dir->d_name, NAMLEN(cur_dir)); 460 if ((name.size() == 1 && name[0] == '.') || 461 (name.size() == 2 && name[0] == '.' && name[1] == '.')) 462 return directory_iterator_increment(it); 463 it.CurrentEntry.replace_filename(name); 464 } else 465 return directory_iterator_destruct(it); 466 467 return success; 468} 469 470error_code get_magic(const Twine &path, uint32_t len, 471 SmallVectorImpl<char> &result) { 472 SmallString<128> PathStorage; 473 StringRef Path = path.toNullTerminatedStringRef(PathStorage); 474 result.set_size(0); 475 476 // Open path. 477 std::FILE *file = std::fopen(Path.data(), "rb"); 478 if (file == 0) 479 return error_code(errno, system_category()); 480 481 // Reserve storage. 482 result.reserve(len); 483 484 // Read magic! 485 size_t size = std::fread(result.data(), 1, len, file); 486 if (std::ferror(file) != 0) { 487 std::fclose(file); 488 return error_code(errno, system_category()); 489 } else if (size != result.size()) { 490 if (std::feof(file) != 0) { 491 std::fclose(file); 492 result.set_size(size); 493 return make_error_code(errc::value_too_large); 494 } 495 } 496 std::fclose(file); 497 result.set_size(len); 498 return success; 499} 500 501} // end namespace fs 502} // end namespace sys 503} // end namespace llvm 504