github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/util/save_util.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include "test/util/save_util.h"
    16  
    17  #include <stddef.h>
    18  #include <stdlib.h>
    19  #include <unistd.h>
    20  
    21  #include <atomic>
    22  #include <cerrno>
    23  
    24  #include "absl/types/optional.h"
    25  
    26  namespace gvisor {
    27  namespace testing {
    28  namespace {
    29  
    30  std::atomic<absl::optional<bool>> save_present;
    31  
    32  bool SavePresent() {
    33    auto present = save_present.load();
    34    if (!present.has_value()) {
    35      present = getenv("GVISOR_SAVE_TEST") != nullptr;
    36      save_present.store(present);
    37    }
    38    return present.value();
    39  }
    40  
    41  std::atomic<int> save_disable;
    42  
    43  }  // namespace
    44  
    45  bool IsRunningWithSaveRestore() { return SavePresent(); }
    46  
    47  void MaybeSave() {
    48    if (SavePresent() && save_disable.load() == 0) {
    49      internal::DoCooperativeSave();
    50    }
    51  }
    52  
    53  DisableSave::DisableSave() { save_disable++; }
    54  
    55  DisableSave::~DisableSave() { reset(); }
    56  
    57  void DisableSave::reset() {
    58    if (!reset_) {
    59      reset_ = true;
    60      save_disable--;
    61    }
    62  }
    63  
    64  }  // namespace testing
    65  }  // namespace gvisor