1 /* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "os.h" 18 19 #include <sys/types.h> 20 #include <sys/stat.h> 21 #include <fcntl.h> 22 #include <cstddef> 23 #include <memory> 24 25 #include "base/logging.h" 26 #include "base/unix_file/fd_file.h" 27 28 namespace art { 29 30 File* OS::OpenFileForReading(const char* name) { 31 return OpenFileWithFlags(name, O_RDONLY); 32 } 33 34 File* OS::OpenFileReadWrite(const char* name) { 35 return OpenFileWithFlags(name, O_RDWR); 36 } 37 38 static File* CreateEmptyFile(const char* name, int extra_flags) { 39 // In case the file exists, unlink it so we get a new file. This is necessary as the previous 40 // file may be in use and must not be changed. 41 unlink(name); 42 43 return OS::OpenFileWithFlags(name, O_CREAT | extra_flags); 44 } 45 46 File* OS::CreateEmptyFile(const char* name) { 47 return art::CreateEmptyFile(name, O_RDWR | O_TRUNC); 48 } 49 50 File* OS::CreateEmptyFileWriteOnly(const char* name) { 51 return art::CreateEmptyFile(name, O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC); 52 } 53 54 File* OS::OpenFileWithFlags(const char* name, int flags, bool auto_flush) { 55 CHECK(name != nullptr); 56 bool read_only = ((flags & O_ACCMODE) == O_RDONLY); 57 bool check_usage = !read_only && auto_flush; 58 std::unique_ptr<File> file(new File(name, flags, 0666, check_usage)); 59 if (!file->IsOpened()) { 60 return nullptr; 61 } 62 return file.release(); 63 } 64 65 bool OS::FileExists(const char* name) { 66 struct stat st; 67 if (stat(name, &st) == 0) { 68 return S_ISREG(st.st_mode); // TODO: Deal with symlinks? 69 } else { 70 return false; 71 } 72 } 73 74 bool OS::DirectoryExists(const char* name) { 75 struct stat st; 76 if (stat(name, &st) == 0) { 77 return S_ISDIR(st.st_mode); // TODO: Deal with symlinks? 78 } else { 79 return false; 80 } 81 } 82 83 } // namespace art 84