blob: 58f7cb4c434a75d5c5a1962b05b9b34a4280e2a2 [file] [log] [blame]
Dominik Laskowski298b08e2022-02-15 13:45:02 -08001/*
2 * Copyright 2022 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#pragma once
18
19#include <log/log.h>
20#include <utils/Mutex.h>
21
22namespace android {
23
24struct SCOPED_CAPABILITY ConditionalLock {
25 ConditionalLock(Mutex& mutex, bool lock) ACQUIRE(mutex) : mutex(mutex), lock(lock) {
26 if (lock) mutex.lock();
27 }
28
29 ~ConditionalLock() RELEASE() {
30 if (lock) mutex.unlock();
31 }
32
33 Mutex& mutex;
34 const bool lock;
35};
36
37struct SCOPED_CAPABILITY TimedLock {
38 TimedLock(Mutex& mutex, nsecs_t timeout, const char* whence) ACQUIRE(mutex)
39 : mutex(mutex), status(mutex.timedLock(timeout)) {
40 ALOGE_IF(!locked(), "%s timed out locking: %s (%d)", whence, strerror(-status), status);
41 }
42
43 ~TimedLock() RELEASE() {
44 if (locked()) mutex.unlock();
45 }
46
47 bool locked() const { return status == NO_ERROR; }
48
49 Mutex& mutex;
50 const status_t status;
51};
52
Josh Gao194ff392022-09-08 16:19:29 -070053// Require, under penalty of compilation failure, that the compiler thinks that a mutex is held.
54#define REQUIRE_MUTEX(expr) ([]() REQUIRES(expr) {})()
55
56// Tell the compiler that we know that a mutex is held.
57#define ASSERT_MUTEX(expr) ([]() ASSERT_CAPABILITY(expr) {})()
58
59// Specify that one mutex is an alias for another.
60// (e.g. SurfaceFlinger::mStateLock and Layer::mFlinger->mStateLock)
61#define MUTEX_ALIAS(held, alias) (REQUIRE_MUTEX(held), ASSERT_MUTEX(alias))
62
Dominik Laskowski298b08e2022-02-15 13:45:02 -080063} // namespace android