• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
OpenFileForReading(const char * name)30 File* OS::OpenFileForReading(const char* name) {
31   return OpenFileWithFlags(name, O_RDONLY);
32 }
33 
OpenFileReadWrite(const char * name)34 File* OS::OpenFileReadWrite(const char* name) {
35   return OpenFileWithFlags(name, O_RDWR);
36 }
37 
CreateEmptyFile(const char * name,int extra_flags)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 
CreateEmptyFile(const char * name)46 File* OS::CreateEmptyFile(const char* name) {
47   return art::CreateEmptyFile(name, O_RDWR | O_TRUNC);
48 }
49 
CreateEmptyFileWriteOnly(const char * name)50 File* OS::CreateEmptyFileWriteOnly(const char* name) {
51   return art::CreateEmptyFile(name, O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC);
52 }
53 
OpenFileWithFlags(const char * name,int flags,bool auto_flush)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(
59       new File(name, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH, check_usage));
60   if (!file->IsOpened()) {
61     return nullptr;
62   }
63   return file.release();
64 }
65 
FileExists(const char * name)66 bool OS::FileExists(const char* name) {
67   struct stat st;
68   if (stat(name, &st) == 0) {
69     return S_ISREG(st.st_mode);  // TODO: Deal with symlinks?
70   } else {
71     return false;
72   }
73 }
74 
DirectoryExists(const char * name)75 bool OS::DirectoryExists(const char* name) {
76   struct stat st;
77   if (stat(name, &st) == 0) {
78     return S_ISDIR(st.st_mode);  // TODO: Deal with symlinks?
79   } else {
80     return false;
81   }
82 }
83 
84 }  // namespace art
85