summaryrefslogtreecommitdiff
path: root/md/writeup/fpu_catch_division_by_zero.md
blob: 417abc23972cc1abce7979510b3549b26ed74a6a (plain) (blame)
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
title:FPU catch division by zero
keywords:fpu,zero,c,assembler,cpu

# FPU catch division by zero
There can occure some problems in C onw of them is divison on zero.
For this we setup system exception handler or signal handler. 
When is division on zero it works.Also for return in main function
there is used setjmp and longjmp

```c
void set_exception_handler()
{
    int err;
    fenv.__control_word &= ~FE_ALL_EXCEPT;
    fenv.__cs_selector &= ~FE_ALL_EXCEPT << 7;
    fesetenv( &fenv );  
     
    sa.sa_sigaction = &exception_handler;
    sa.sa_flags = SA_SIGINFO;
    err = sigaction( SIGFPE, &sa, NULL );
    if (err != 0)
        printf("Cannot set FloatingPoint exception handler\n");
    else
        printf("[OK] SIGFPE is set\n");
}
 
void exception_handler(int i, siginfo_t *s, void *v )
{
    if (s->si_signo == SIGFPE)
    {
        printf("[SIGFPE] SIGFPE Occure\n");
        printf("[SIGFPE] Error number: %d\n", s->si_errno);
        printf("[SIGFPE] Signal code: %d\n", s->si_code);
        switch (s->si_code)
        {
            case FPE_INTDIV:
                printf("[SIGFPE] Divison by 0\n");
                longjmp( jmp , 1 );
                break;
        }
    }
    abort();
}
```

Compilation is easy:
```sh
gcc sigfpe.c -o sigfpe -lm
```
Now it will no so big problem when some error occur to properly exit
or make some checks.


## Downloads
exception_in_c.zip - 
2KiB - http://archive.main.lv/files/writeup/fpu_catch_division_by_zero/exception_in_c.zip