xref: /aosp_15_r20/external/libbrillo/brillo/scoped_umask.h (revision 1a96fba65179ea7d3f56207137718607415c5953)
1*1a96fba6SXin Li // Copyright 2019 The Chromium OS Authors. All rights reserved.
2*1a96fba6SXin Li // Use of this source code is governed by a BSD-style license that can be
3*1a96fba6SXin Li // found in the LICENSE file.
4*1a96fba6SXin Li 
5*1a96fba6SXin Li #ifndef LIBBRILLO_BRILLO_SCOPED_UMASK_H_
6*1a96fba6SXin Li #define LIBBRILLO_BRILLO_SCOPED_UMASK_H_
7*1a96fba6SXin Li 
8*1a96fba6SXin Li #include <sys/types.h>
9*1a96fba6SXin Li 
10*1a96fba6SXin Li #include <base/macros.h>
11*1a96fba6SXin Li #include <brillo/brillo_export.h>
12*1a96fba6SXin Li 
13*1a96fba6SXin Li namespace brillo {
14*1a96fba6SXin Li 
15*1a96fba6SXin Li // ScopedUmask is a helper class for temporarily setting the umask before a
16*1a96fba6SXin Li // set of operations. umask(2) is never expected to fail.
17*1a96fba6SXin Li class BRILLO_EXPORT ScopedUmask {
18*1a96fba6SXin Li  public:
19*1a96fba6SXin Li   explicit ScopedUmask(mode_t new_umask);
20*1a96fba6SXin Li   ~ScopedUmask();
21*1a96fba6SXin Li 
22*1a96fba6SXin Li  private:
23*1a96fba6SXin Li   mode_t saved_umask_;
24*1a96fba6SXin Li 
25*1a96fba6SXin Li   // Avoid reusing ScopedUmask for multiple masks. DISALLOW_COPY_AND_ASSIGN
26*1a96fba6SXin Li   // deletes the copy constructor and operator=, but there are other situations
27*1a96fba6SXin Li   // where reassigning a new ScopedUmask to an existing ScopedUmask object
28*1a96fba6SXin Li   // is problematic:
29*1a96fba6SXin Li   //
30*1a96fba6SXin Li   // /* starting umask: default_value
31*1a96fba6SXin Li   // auto a = std::make_unique<ScopedUmask>(first_value);
32*1a96fba6SXin Li   // ... code here ...
33*1a96fba6SXin Li   // a.reset(ScopedUmask(new_value));
34*1a96fba6SXin Li   //
35*1a96fba6SXin Li   // Here, the order of destruction of the old object and the construction of
36*1a96fba6SXin Li   // the new object is inverted. The recommended usage would be:
37*1a96fba6SXin Li   //
38*1a96fba6SXin Li   // {
39*1a96fba6SXin Li   //    ScopedUmask a(old_value);
40*1a96fba6SXin Li   //    ... code here ...
41*1a96fba6SXin Li   // }
42*1a96fba6SXin Li   //
43*1a96fba6SXin Li   // {
44*1a96fba6SXin Li   //    ScopedUmask a(new_value);
45*1a96fba6SXin Li   //    ... code here ...
46*1a96fba6SXin Li   // }
47*1a96fba6SXin Li   DISALLOW_COPY_AND_ASSIGN(ScopedUmask);
48*1a96fba6SXin Li };
49*1a96fba6SXin Li 
50*1a96fba6SXin Li }  // namespace brillo
51*1a96fba6SXin Li 
52*1a96fba6SXin Li #endif  // LIBBRILLO_BRILLO_SCOPED_UMASK_H_
53