1 /*
2 * Copyright (C) 2011 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 "scoped_flock.h"
18
19 #include <sys/file.h>
20 #include <sys/stat.h>
21
22 #include <android-base/logging.h>
23 #include <android-base/stringprintf.h>
24
25 #include "base/unix_file/fd_file.h"
26
27 namespace art {
28
29 using android::base::StringPrintf;
30
Open(const char * filename,std::string * error_msg)31 /* static */ ScopedFlock LockedFile::Open(const char* filename, std::string* error_msg) {
32 return Open(filename, O_CREAT | O_RDWR, true, error_msg);
33 }
34
Open(const char * filename,int flags,bool block,std::string * error_msg)35 /* static */ ScopedFlock LockedFile::Open(const char* filename, int flags, bool block,
36 std::string* error_msg) {
37 while (true) {
38 // NOTE: We don't check usage here because the ScopedFlock should *never* be
39 // responsible for flushing its underlying FD. Its only purpose should be
40 // to acquire a lock, and the unlock / close in the corresponding
41 // destructor. Callers should explicitly flush files they're writing to if
42 // that is the desired behaviour.
43 std::unique_ptr<File> file(OS::OpenFileWithFlags(filename, flags, false /* check_usage */));
44 if (file.get() == nullptr) {
45 *error_msg = StringPrintf("Failed to open file '%s': %s", filename, strerror(errno));
46 return nullptr;
47 }
48
49 int operation = block ? LOCK_EX : (LOCK_EX | LOCK_NB);
50 int flock_result = TEMP_FAILURE_RETRY(flock(file->Fd(), operation));
51 if (flock_result == EWOULDBLOCK) {
52 // File is locked by someone else and we are required not to block;
53 return nullptr;
54 }
55 if (flock_result != 0) {
56 *error_msg = StringPrintf("Failed to lock file '%s': %s", filename, strerror(errno));
57 return nullptr;
58 }
59 struct stat fstat_stat;
60 int fstat_result = TEMP_FAILURE_RETRY(fstat(file->Fd(), &fstat_stat));
61 if (fstat_result != 0) {
62 *error_msg = StringPrintf("Failed to fstat file '%s': %s", filename, strerror(errno));
63 return nullptr;
64 }
65 struct stat stat_stat;
66 int stat_result = TEMP_FAILURE_RETRY(stat(filename, &stat_stat));
67 if (stat_result != 0) {
68 PLOG(WARNING) << "Failed to stat, will retry: " << filename;
69 // ENOENT can happen if someone racing with us unlinks the file we created so just retry.
70 if (block) {
71 continue;
72 } else {
73 // Note that in theory we could race with someone here for a long time and end up retrying
74 // over and over again. This potential behavior does not fit well in the non-blocking
75 // semantics. Thus, if we are not require to block return failure when racing.
76 return nullptr;
77 }
78 }
79 if (fstat_stat.st_dev != stat_stat.st_dev || fstat_stat.st_ino != stat_stat.st_ino) {
80 LOG(WARNING) << "File changed while locking, will retry: " << filename;
81 if (block) {
82 continue;
83 } else {
84 // See comment above.
85 return nullptr;
86 }
87 }
88
89 return ScopedFlock(new LockedFile(std::move((*file.get()))));
90 }
91 }
92
DupOf(const int fd,const std::string & path,const bool read_only_mode,std::string * error_msg)93 ScopedFlock LockedFile::DupOf(const int fd, const std::string& path,
94 const bool read_only_mode, std::string* error_msg) {
95 // NOTE: We don't check usage here because the ScopedFlock should *never* be
96 // responsible for flushing its underlying FD. Its only purpose should be
97 // to acquire a lock, and the unlock / close in the corresponding
98 // destructor. Callers should explicitly flush files they're writing to if
99 // that is the desired behaviour.
100 ScopedFlock locked_file(
101 new LockedFile(dup(fd), path, false /* check_usage */, read_only_mode));
102 if (locked_file->Fd() == -1) {
103 *error_msg = StringPrintf("Failed to duplicate open file '%s': %s",
104 locked_file->GetPath().c_str(), strerror(errno));
105 return nullptr;
106 }
107 if (0 != TEMP_FAILURE_RETRY(flock(locked_file->Fd(), LOCK_EX))) {
108 *error_msg = StringPrintf(
109 "Failed to lock file '%s': %s", locked_file->GetPath().c_str(), strerror(errno));
110 return nullptr;
111 }
112
113 return locked_file;
114 }
115
ReleaseLock()116 void LockedFile::ReleaseLock() {
117 if (this->Fd() != -1) {
118 int flock_result = TEMP_FAILURE_RETRY(flock(this->Fd(), LOCK_UN));
119 if (flock_result != 0) {
120 // Only printing a warning is okay since this is only used with either:
121 // 1) a non-blocking Init call, or
122 // 2) as a part of a seperate binary (eg dex2oat) which has it's own timeout logic to prevent
123 // deadlocks.
124 // This means we can be sure that the warning won't cause a deadlock.
125 PLOG(WARNING) << "Unable to unlock file " << this->GetPath();
126 }
127 }
128 }
129
130 } // namespace art
131