summaryrefslogtreecommitdiff
path: root/libc/test/src/fenv/feholdexcept_test.cpp
blob: 40e336ef41af3b1a7d00c74977ae10fa06c802d1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//===-- Unittests for feholdexcept with exceptions enabled ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "src/fenv/feholdexcept.h"

#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/macros/properties/architectures.h"
#include "test/UnitTest/FPExceptMatcher.h"
#include "test/UnitTest/Test.h"

#include <fenv.h>

TEST(LlvmLibcFEnvTest, RaiseAndCrash) {
#if defined(LIBC_TARGET_ARCH_IS_ANY_ARM) || defined(LIBC_TARGET_ARCH_IS_RISCV64)
  // Few Arm HW implementations do not trap exceptions. We skip this test
  // completely on such HW.
  //
  // Whether HW supports trapping exceptions or not is deduced by enabling an
  // exception and reading back to see if the exception got enabled. If the
  // exception did not get enabled, then it means that the HW does not support
  // trapping exceptions.
  __llvm_libc::fputil::disable_except(FE_ALL_EXCEPT);
  __llvm_libc::fputil::enable_except(FE_DIVBYZERO);
  if (__llvm_libc::fputil::get_except() == 0)
    return;
#endif // Architectures where exception trapping is not supported

  int excepts[] = {FE_DIVBYZERO, FE_INVALID, FE_INEXACT, FE_OVERFLOW,
                   FE_UNDERFLOW};

  for (int e : excepts) {
    fenv_t env;
    __llvm_libc::fputil::disable_except(FE_ALL_EXCEPT);
    __llvm_libc::fputil::enable_except(e);
    ASSERT_EQ(__llvm_libc::fputil::clear_except(FE_ALL_EXCEPT), 0);
    ASSERT_EQ(__llvm_libc::feholdexcept(&env), 0);
    // feholdexcept should disable all excepts so raising an exception
    // should not crash/invoke the exception handler.
    ASSERT_EQ(__llvm_libc::fputil::raise_except(e), 0);

    ASSERT_RAISES_FP_EXCEPT([=] {
      // When we put back the saved env, which has the exception enabled, it
      // should crash with SIGFPE. Note that we set the old environment
      // back inside this closure because in some test frameworks like Fuchsia's
      // zxtest, this test translates to a death test in which this closure is
      // run in a different thread. So, we set the old environment inside
      // this closure so that the exception gets enabled for the thread running
      // this closure.
      __llvm_libc::fputil::set_env(&env);
      __llvm_libc::fputil::raise_except(e);
    });

    // Cleanup
    __llvm_libc::fputil::disable_except(FE_ALL_EXCEPT);
    ASSERT_EQ(__llvm_libc::fputil::clear_except(FE_ALL_EXCEPT), 0);
  }
}