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) { 55 CHECK(name != nullptr); 56 std::unique_ptr<File> file(new File); 57 if (!file->Open(name, flags, 0666)) { 58 return nullptr; 59 } 60 return file.release(); 61 } 62 63 bool OS::FileExists(const char* name) { 64 struct stat st; 65 if (stat(name, &st) == 0) { 66 return S_ISREG(st.st_mode); // TODO: Deal with symlinks? 67 } else { 68 return false; 69 } 70 } 71 72 bool OS::DirectoryExists(const char* name) { 73 struct stat st; 74 if (stat(name, &st) == 0) { 75 return S_ISDIR(st.st_mode); // TODO: Deal with symlinks? 76 } else { 77 return false; 78 } 79 } 80 81 } // namespace art 82