1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "rlz/lib/recursive_cross_process_lock_posix.h"
6
7#include <errno.h>
8#include <fcntl.h>
9#include <sys/file.h>
10#include <sys/stat.h>
11#include <sys/types.h>
12#include <unistd.h>
13
14#include "base/files/file_path.h"
15#include "base/logging.h"
16#include "base/posix/eintr_wrapper.h"
17
18namespace rlz_lib {
19
20bool RecursiveCrossProcessLock::TryGetCrossProcessLock(
21    const base::FilePath& lock_filename) {
22  bool just_got_lock = false;
23
24  // Emulate a recursive mutex with a non-recursive one.
25  if (pthread_mutex_trylock(&recursive_lock_) == EBUSY) {
26    if (pthread_equal(pthread_self(), locking_thread_) == 0) {
27      // Some other thread has the lock, wait for it.
28      pthread_mutex_lock(&recursive_lock_);
29      CHECK(locking_thread_ == 0);
30      just_got_lock = true;
31    }
32  } else {
33    just_got_lock = true;
34  }
35
36  locking_thread_ = pthread_self();
37
38  // Try to acquire file lock.
39  if (just_got_lock) {
40    const int kMaxTimeoutMS = 5000;  // Matches Windows.
41    const int kSleepPerTryMS = 200;
42
43    CHECK(file_lock_ == -1);
44    file_lock_ = open(lock_filename.value().c_str(), O_RDWR | O_CREAT, 0666);
45    if (file_lock_ == -1) {
46      perror("open");
47      return false;
48    }
49
50    int flock_result = -1;
51    int elapsed_ms = 0;
52    while ((flock_result =
53               HANDLE_EINTR(flock(file_lock_, LOCK_EX | LOCK_NB))) == -1 &&
54           errno == EWOULDBLOCK &&
55           elapsed_ms < kMaxTimeoutMS) {
56      usleep(kSleepPerTryMS * 1000);
57      elapsed_ms += kSleepPerTryMS;
58    }
59
60    if (flock_result == -1) {
61      perror("flock");
62      close(file_lock_);
63      file_lock_ = -1;
64      return false;
65    }
66    return true;
67  } else {
68    return file_lock_ != -1;
69  }
70}
71
72void RecursiveCrossProcessLock::ReleaseLock() {
73  if (file_lock_ != -1) {
74    ignore_result(HANDLE_EINTR(flock(file_lock_, LOCK_UN)));
75    close(file_lock_);
76    file_lock_ = -1;
77  }
78
79  locking_thread_ = 0;
80  pthread_mutex_unlock(&recursive_lock_);
81}
82
83}  // namespace rlz_lib
84