1//===-- Unittests for setjmp and longjmp ----------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "src/setjmp/longjmp.h"
10#include "src/setjmp/setjmp_impl.h"
11#include "test/UnitTest/Test.h"
12
13constexpr int MAX_LOOP = 123;
14int longjmp_called = 0;
15
16void jump_back(jmp_buf buf, int n) {
17 longjmp_called++;
18 LIBC_NAMESPACE::longjmp(buf, n); // Will return |n| out of setjmp
19}
20
21TEST(LlvmLibcSetJmpTest, SetAndJumpBack) {
22 jmp_buf buf;
23 longjmp_called = 0;
24
25 // Local variables in setjmp scope should be declared volatile.
26 volatile int n = 0;
27 // The first time setjmp is called, it should return 0.
28 // Subsequent calls will return the value passed to jump_back below.
29 if (LIBC_NAMESPACE::setjmp(buf) <= MAX_LOOP) {
30 ++n;
31 jump_back(buf, n);
32 }
33 ASSERT_EQ(longjmp_called, n);
34 ASSERT_EQ(n, MAX_LOOP + 1);
35}
36
37TEST(LlvmLibcSetJmpTest, SetAndJumpBackValOne) {
38 jmp_buf buf;
39 longjmp_called = 0;
40
41 int val = LIBC_NAMESPACE::setjmp(buf);
42 if (val == 0)
43 jump_back(buf, n: val);
44
45 ASSERT_EQ(longjmp_called, 1);
46 ASSERT_EQ(val, 1);
47}
48

source code of libc/test/src/setjmp/setjmp_test.cpp