File: segv_errors.c

package info (click to toggle)
linux 6.1.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,488,076 kB
  • sloc: ansic: 23,401,844; asm: 266,744; sh: 108,976; makefile: 49,705; python: 36,927; perl: 36,810; cpp: 6,044; yacc: 4,904; lex: 2,722; awk: 1,440; ruby: 25; sed: 5
file content (78 lines) | stat: -rw-r--r-- 1,384 bytes parent folder | download | duplicates (25)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// SPDX-License-Identifier: GPL-2.0

/*
 * Copyright 2017 John Sperbeck
 *
 * Test that an access to a mapped but inaccessible area causes a SEGV and
 * reports si_code == SEGV_ACCERR.
 */

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/mman.h>
#include <assert.h>
#include <ucontext.h>

#include "utils.h"

static bool faulted;
static int si_code;

static void segv_handler(int n, siginfo_t *info, void *ctxt_v)
{
	ucontext_t *ctxt = (ucontext_t *)ctxt_v;
	struct pt_regs *regs = ctxt->uc_mcontext.regs;

	faulted = true;
	si_code = info->si_code;
	regs->nip += 4;
}

int test_segv_errors(void)
{
	struct sigaction act = {
		.sa_sigaction = segv_handler,
		.sa_flags = SA_SIGINFO,
	};
	char c, *p = NULL;

	p = mmap(NULL, getpagesize(), 0, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
	FAIL_IF(p == MAP_FAILED);

	FAIL_IF(sigaction(SIGSEGV, &act, NULL) != 0);

	faulted = false;
	si_code = 0;

	/*
	 * We just need a compiler barrier, but mb() works and has the nice
	 * property of being easy to spot in the disassembly.
	 */
	mb();
	c = *p;
	mb();

	FAIL_IF(!faulted);
	FAIL_IF(si_code != SEGV_ACCERR);

	faulted = false;
	si_code = 0;

	mb();
	*p = c;
	mb();

	FAIL_IF(!faulted);
	FAIL_IF(si_code != SEGV_ACCERR);

	return 0;
}

int main(void)
{
	return test_harness(test_segv_errors, "segv_errors");
}