github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/perf/linux/signal_benchmark.cc (about)

     1  // Copyright 2020 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 <signal.h>
    16  #include <string.h>
    17  
    18  #include "gtest/gtest.h"
    19  #include "benchmark/benchmark.h"
    20  #include "test/util/logging.h"
    21  #include "test/util/test_util.h"
    22  
    23  namespace gvisor {
    24  namespace testing {
    25  
    26  namespace {
    27  
    28  void FixupHandler(int sig, siginfo_t* si, void* void_ctx) {
    29    static unsigned int dataval = 0;
    30  
    31    // Skip the offending instruction.
    32    ucontext_t* ctx = reinterpret_cast<ucontext_t*>(void_ctx);
    33    ctx->uc_mcontext.gregs[REG_RAX] = reinterpret_cast<greg_t>(&dataval);
    34  }
    35  
    36  void BM_FaultSignalFixup(benchmark::State& state) {
    37    // Set up the signal handler.
    38    struct sigaction sa = {};
    39    sigemptyset(&sa.sa_mask);
    40    sa.sa_sigaction = FixupHandler;
    41    sa.sa_flags = SA_SIGINFO;
    42    TEST_CHECK(sigaction(SIGSEGV, &sa, nullptr) == 0);
    43  
    44    // Fault, fault, fault.
    45    for (auto _ : state) {
    46      // Trigger the segfault.
    47      asm volatile(
    48          "movq $0, %%rax\n"
    49          "movq $0x77777777, (%%rax)\n"
    50          :
    51          :
    52          : "rax");
    53    }
    54  }
    55  
    56  BENCHMARK(BM_FaultSignalFixup)->UseRealTime();
    57  
    58  }  // namespace
    59  
    60  }  // namespace testing
    61  }  // namespace gvisor