• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 #ifndef ART_LIBARTBASE_BASE_SCOPED_CAP_H_
18 #define ART_LIBARTBASE_BASE_SCOPED_CAP_H_
19 
20 #include <sys/capability.h>
21 
22 #include <utility>
23 
24 #include "android-base/logging.h"
25 
26 namespace art {
27 
28 // A wrapper of `cap_t` that automatically calls `cap_free`.
29 class ScopedCap {
30  public:
ScopedCap(cap_t cap)31   explicit ScopedCap(cap_t cap) : cap_(cap) {}
32 
33   ScopedCap(const ScopedCap&) = delete;
34   ScopedCap& operator=(const ScopedCap&) = delete;
ScopedCap(ScopedCap && other)35   ScopedCap(ScopedCap&& other) noexcept : cap_(std::exchange(other.cap_, nullptr)) {}
36 
~ScopedCap()37   ~ScopedCap() {
38     if (cap_ != nullptr) {
39       if (cap_free(cap_) != 0) {
40         PLOG(ERROR) << "Failed to call cap_free";
41       }
42     }
43   }
44 
Get()45   cap_t Get() const { return cap_; }
46 
47  private:
48   cap_t cap_;
49 };
50 
51 }  // namespace art
52 
53 #endif  // ART_LIBARTBASE_BASE_SCOPED_CAP_H_
54