1 /*
2  * Copyright (C) 2014 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 "base/common_art_test.h"
20 
21 namespace art {
22 
23 class ScopedFlockTest : public CommonArtTest {};
24 
TEST_F(ScopedFlockTest,TestLocking)25 TEST_F(ScopedFlockTest, TestLocking) {
26   ScratchFile scratch_file;
27   std::string error_msg;
28 
29   // NOTE: Locks applied using flock(2) and fcntl(2) are oblivious
30   // to each other, so attempting to query locks set by flock using
31   // using fcntl(,F_GETLK,) will not work. see kernel doc at
32   // Documentation/filesystems/locks.txt.
33   {
34     ScopedFlock file_lock = LockedFile::Open(scratch_file.GetFilename().c_str(),
35                                              &error_msg);
36     ASSERT_TRUE(file_lock.get() != nullptr);
37 
38     // Attempt to acquire a second lock on the same file. This must fail.
39     ScopedFlock second_lock = LockedFile::Open(scratch_file.GetFilename().c_str(),
40                                                O_RDONLY,
41                                                /* block= */ false,
42                                                &error_msg);
43     ASSERT_TRUE(second_lock.get() == nullptr);
44     ASSERT_TRUE(!error_msg.empty());
45   }
46 
47   {
48     // Attempt to reacquire the lock once the first lock has been released, this
49     // must succeed.
50     ScopedFlock file_lock = LockedFile::Open(scratch_file.GetFilename().c_str(),
51                                              &error_msg);
52     ASSERT_TRUE(file_lock.get() != nullptr);
53   }
54 
55   {
56     ScopedFlock file_lock = LockedFile::Open("/will/not/exist",
57                                              &error_msg);
58     ASSERT_TRUE(file_lock.get() == nullptr);
59   }
60 }
61 
62 }  // namespace art
63