xref: /freebsd/lib/msun/tests/fenv_test.c (revision b00ab754)
1 /*-
2  * Copyright (c) 2004 David Schultz <das@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * Test the correctness and C99-compliance of various fenv.h features.
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <assert.h>
37 #include <err.h>
38 #include <fenv.h>
39 #include <float.h>
40 #include <math.h>
41 #include <signal.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 /*
47  * Implementations are permitted to define additional exception flags
48  * not specified in the standard, so it is not necessarily true that
49  * FE_ALL_EXCEPT == ALL_STD_EXCEPT.
50  */
51 #define	ALL_STD_EXCEPT	(FE_DIVBYZERO | FE_INEXACT | FE_INVALID | \
52 			 FE_OVERFLOW | FE_UNDERFLOW)
53 
54 #define	NEXCEPTS	(sizeof(std_excepts) / sizeof(std_excepts[0]))
55 
56 static const int std_excepts[] = {
57 	FE_INVALID,
58 	FE_DIVBYZERO,
59 	FE_OVERFLOW,
60 	FE_UNDERFLOW,
61 	FE_INEXACT,
62 };
63 
64 /* init_exceptsets() initializes this to the power set of std_excepts[] */
65 static int std_except_sets[1 << NEXCEPTS];
66 
67 #pragma STDC FENV_ACCESS ON
68 
69 /*
70  * Initialize std_except_sets[] to the power set of std_excepts[]
71  */
72 static void
73 init_exceptsets(void)
74 {
75 	unsigned i, j, sr;
76 
77 	for (i = 0; i < 1 << NEXCEPTS; i++) {
78 		for (sr = i, j = 0; sr != 0; sr >>= 1, j++)
79 			std_except_sets[i] |= std_excepts[j] & ((~sr & 1) - 1);
80 	}
81 }
82 
83 /*
84  * Raise a floating-point exception without relying on the standard
85  * library routines, which we are trying to test.
86  *
87  * XXX We can't raise an {over,under}flow without also raising an
88  * inexact exception.
89  */
90 static void
91 raiseexcept(int excepts)
92 {
93 	volatile double d;
94 
95 	/*
96 	 * With a compiler that supports the FENV_ACCESS pragma
97 	 * properly, simple expressions like '0.0 / 0.0' should
98 	 * be sufficient to generate traps.  Unfortunately, we
99 	 * need to bring a volatile variable into the equation
100 	 * to prevent incorrect optimizations.
101 	 */
102 	if (excepts & FE_INVALID) {
103 		d = 0.0;
104 		d = 0.0 / d;
105 	}
106 	if (excepts & FE_DIVBYZERO) {
107 		d = 0.0;
108 		d = 1.0 / d;
109 	}
110 	if (excepts & FE_OVERFLOW) {
111 		d = DBL_MAX;
112 		d *= 2.0;
113 	}
114 	if (excepts & FE_UNDERFLOW) {
115 		d = DBL_MIN;
116 		d /= DBL_MAX;
117 	}
118 	if (excepts & FE_INEXACT) {
119 		d = DBL_MIN;
120 		d += 1.0;
121 	}
122 
123 	/*
124 	 * On the x86 (and some other architectures?) the FPU and
125 	 * integer units are decoupled.  We need to execute an FWAIT
126 	 * or a floating-point instruction to get synchronous exceptions.
127 	 */
128 	d = 1.0;
129 	d += 1.0;
130 }
131 
132 /*
133  * Determine the current rounding mode without relying on the fenv
134  * routines.  This function may raise an inexact exception.
135  */
136 static int
137 getround(void)
138 {
139 	volatile double d;
140 
141 	/*
142 	 * This test works just as well with 0.0 - 0.0, except on ia64
143 	 * where 0.0 - 0.0 gives the wrong sign when rounding downwards.
144 	 */
145 	d = 1.0;
146 	d -= 1.0;
147 	if (copysign(1.0, d) < 0.0)
148 		return (FE_DOWNWARD);
149 
150 	d = 1.0;
151 	if (d + (DBL_EPSILON * 3.0 / 4.0) == 1.0)
152 		return (FE_TOWARDZERO);
153 	if (d + (DBL_EPSILON * 1.0 / 4.0) > 1.0)
154 		return (FE_UPWARD);
155 
156 	return (FE_TONEAREST);
157 }
158 
159 static void
160 trap_handler(int sig)
161 {
162 
163 	assert(sig == SIGFPE);
164 	_exit(0);
165 }
166 
167 /*
168  * This tests checks the default FP environment, so it must be first.
169  * The memcmp() test below may be too much to ask for, since there
170  * could be multiple machine-specific default environments.
171  */
172 static void
173 test_dfl_env(void)
174 {
175 #ifndef NO_STRICT_DFL_ENV
176 	fenv_t env;
177 
178 	fegetenv(&env);
179 
180 #ifdef __amd64__
181 	/*
182 	 * Compare the fields that the AMD [1] and Intel [2] specs say will be
183 	 * set once fnstenv returns.
184 	 *
185 	 * Not all amd64 capable processors implement the fnstenv instruction
186 	 * by zero'ing out the env.__x87.__other field (example: AMD Opteron
187 	 * 6308). The AMD64/x64 specs aren't explicit on what the
188 	 * env.__x87.__other field will contain after fnstenv is executed, so
189 	 * the values in env.__x87.__other could be filled with arbitrary
190 	 * data depending on how the CPU implements fnstenv.
191 	 *
192 	 * 1. http://support.amd.com/TechDocs/26569_APM_v5.pdf
193 	 * 2. http://www.intel.com/Assets/en_US/PDF/manual/253666.pdf
194 	 */
195 	assert(memcmp(&env.__mxcsr, &FE_DFL_ENV->__mxcsr,
196 	    sizeof(env.__mxcsr)) == 0);
197 	assert(memcmp(&env.__x87.__control, &FE_DFL_ENV->__x87.__control,
198 	    sizeof(env.__x87.__control)) == 0);
199 	assert(memcmp(&env.__x87.__status, &FE_DFL_ENV->__x87.__status,
200 	    sizeof(env.__x87.__status)) == 0);
201 	assert(memcmp(&env.__x87.__tag, &FE_DFL_ENV->__x87.__tag,
202 	    sizeof(env.__x87.__tag)) == 0);
203 #else
204 	assert(memcmp(&env, FE_DFL_ENV, sizeof(env)) == 0);
205 #endif
206 
207 #endif
208 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
209 }
210 
211 /*
212  * Test fetestexcept() and feclearexcept().
213  */
214 static void
215 test_fetestclearexcept(void)
216 {
217 	int excepts, i;
218 
219 	for (i = 0; i < 1 << NEXCEPTS; i++)
220 		assert(fetestexcept(std_except_sets[i]) == 0);
221 	for (i = 0; i < 1 << NEXCEPTS; i++) {
222 		excepts = std_except_sets[i];
223 
224 		/* FE_ALL_EXCEPT might be special-cased, as on i386. */
225 		raiseexcept(excepts);
226 		assert(fetestexcept(excepts) == excepts);
227 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
228 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
229 
230 		raiseexcept(excepts);
231 		assert(fetestexcept(excepts) == excepts);
232 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0) {
233 			excepts |= FE_INEXACT;
234 			assert((fetestexcept(ALL_STD_EXCEPT) | FE_INEXACT) ==
235 			    excepts);
236 		} else {
237 			assert(fetestexcept(ALL_STD_EXCEPT) == excepts);
238 		}
239 		assert(feclearexcept(excepts) == 0);
240 		assert(fetestexcept(ALL_STD_EXCEPT) == 0);
241 	}
242 }
243 
244 /*
245  * Test fegetexceptflag() and fesetexceptflag().
246  *
247  * Prerequisites: fetestexcept(), feclearexcept()
248  */
249 static void
250 test_fegsetexceptflag(void)
251 {
252 	fexcept_t flag;
253 	int excepts, i;
254 
255 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
256 	for (i = 0; i < 1 << NEXCEPTS; i++) {
257 		excepts = std_except_sets[i];
258 
259 		assert(fegetexceptflag(&flag, excepts) == 0);
260 		raiseexcept(ALL_STD_EXCEPT);
261 		assert(fesetexceptflag(&flag, excepts) == 0);
262 		assert(fetestexcept(ALL_STD_EXCEPT) ==
263 		    (ALL_STD_EXCEPT ^ excepts));
264 
265 		assert(fegetexceptflag(&flag, FE_ALL_EXCEPT) == 0);
266 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
267 		assert(fesetexceptflag(&flag, excepts) == 0);
268 		assert(fetestexcept(ALL_STD_EXCEPT) == 0);
269 		assert(fesetexceptflag(&flag, ALL_STD_EXCEPT ^ excepts) == 0);
270 		assert(fetestexcept(ALL_STD_EXCEPT) ==
271 		    (ALL_STD_EXCEPT ^ excepts));
272 
273 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
274 	}
275 }
276 
277 /*
278  * Test feraiseexcept().
279  *
280  * Prerequisites: fetestexcept(), feclearexcept()
281  */
282 static void
283 test_feraiseexcept(void)
284 {
285 	int excepts, i;
286 
287 	for (i = 0; i < 1 << NEXCEPTS; i++) {
288 		excepts = std_except_sets[i];
289 
290 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
291 		assert(feraiseexcept(excepts) == 0);
292 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0) {
293 			excepts |= FE_INEXACT;
294 			assert((fetestexcept(ALL_STD_EXCEPT) | FE_INEXACT) ==
295 			    excepts);
296 		} else {
297 			assert(fetestexcept(ALL_STD_EXCEPT) == excepts);
298 		}
299 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
300 	}
301 	assert(feraiseexcept(FE_INVALID | FE_DIVBYZERO) == 0);
302 	assert(fetestexcept(ALL_STD_EXCEPT) == (FE_INVALID | FE_DIVBYZERO));
303 	assert(feraiseexcept(FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT) == 0);
304 	assert(fetestexcept(ALL_STD_EXCEPT) == ALL_STD_EXCEPT);
305 	assert(feclearexcept(FE_ALL_EXCEPT) == 0);
306 }
307 
308 /*
309  * Test fegetround() and fesetround().
310  */
311 static void
312 test_fegsetround(void)
313 {
314 
315 	assert(fegetround() == FE_TONEAREST);
316 	assert(getround() == FE_TONEAREST);
317 	assert(FLT_ROUNDS == 1);
318 
319 	assert(fesetround(FE_DOWNWARD) == 0);
320 	assert(fegetround() == FE_DOWNWARD);
321 	assert(getround() == FE_DOWNWARD);
322 	assert(FLT_ROUNDS == 3);
323 
324 	assert(fesetround(FE_UPWARD) == 0);
325 	assert(getround() == FE_UPWARD);
326 	assert(fegetround() == FE_UPWARD);
327 	assert(FLT_ROUNDS == 2);
328 
329 	assert(fesetround(FE_TOWARDZERO) == 0);
330 	assert(getround() == FE_TOWARDZERO);
331 	assert(fegetround() == FE_TOWARDZERO);
332 	assert(FLT_ROUNDS == 0);
333 
334 	assert(fesetround(FE_TONEAREST) == 0);
335 	assert(getround() == FE_TONEAREST);
336 	assert(FLT_ROUNDS == 1);
337 
338 	assert(feclearexcept(FE_ALL_EXCEPT) == 0);
339 }
340 
341 /*
342  * Test fegetenv() and fesetenv().
343  *
344  * Prerequisites: fetestexcept(), feclearexcept(), fegetround(), fesetround()
345  */
346 static void
347 test_fegsetenv(void)
348 {
349 	fenv_t env1, env2;
350 	int excepts, i;
351 
352 	for (i = 0; i < 1 << NEXCEPTS; i++) {
353 		excepts = std_except_sets[i];
354 
355 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
356 		assert(fegetround() == FE_TONEAREST);
357 		assert(fegetenv(&env1) == 0);
358 
359 		/*
360 		 * fe[gs]etenv() should be able to save and restore
361 		 * exception flags without the spurious inexact
362 		 * exceptions that afflict raiseexcept().
363 		 */
364 		raiseexcept(excepts);
365 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0 &&
366 		    (excepts & FE_INEXACT) == 0)
367 			assert(feclearexcept(FE_INEXACT) == 0);
368 
369 		fesetround(FE_DOWNWARD);
370 		assert(fegetenv(&env2) == 0);
371 		assert(fesetenv(&env1) == 0);
372 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
373 		assert(fegetround() == FE_TONEAREST);
374 
375 		assert(fesetenv(&env2) == 0);
376 		assert(fetestexcept(FE_ALL_EXCEPT) == excepts);
377 		assert(fegetround() == FE_DOWNWARD);
378 		assert(fesetenv(&env1) == 0);
379 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
380 		assert(fegetround() == FE_TONEAREST);
381 	}
382 }
383 
384 /*
385  * Test fegetexcept(), fedisableexcept(), and feenableexcept().
386  *
387  * Prerequisites: fetestexcept(), feraiseexcept()
388  */
389 static void
390 test_masking(void)
391 {
392 	struct sigaction act;
393 	int except, pass, raise, status;
394 	unsigned i;
395 
396 	assert((fegetexcept() & ALL_STD_EXCEPT) == 0);
397 	assert((feenableexcept(FE_INVALID|FE_OVERFLOW) & ALL_STD_EXCEPT) == 0);
398 	assert((feenableexcept(FE_UNDERFLOW) & ALL_STD_EXCEPT) ==
399 	    (FE_INVALID | FE_OVERFLOW));
400 	assert((fedisableexcept(FE_OVERFLOW) & ALL_STD_EXCEPT) ==
401 	    (FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW));
402 	assert((fegetexcept() & ALL_STD_EXCEPT) == (FE_INVALID | FE_UNDERFLOW));
403 	assert((fedisableexcept(FE_ALL_EXCEPT) & ALL_STD_EXCEPT) ==
404 	    (FE_INVALID | FE_UNDERFLOW));
405 	assert((fegetexcept() & ALL_STD_EXCEPT) == 0);
406 
407 	sigemptyset(&act.sa_mask);
408 	act.sa_flags = 0;
409 	act.sa_handler = trap_handler;
410 	for (pass = 0; pass < 2; pass++) {
411 		for (i = 0; i < NEXCEPTS; i++) {
412 			except = std_excepts[i];
413 			/* over/underflow may also raise inexact */
414 			if (except == FE_INEXACT)
415 				raise = FE_DIVBYZERO | FE_INVALID;
416 			else
417 				raise = ALL_STD_EXCEPT ^ except;
418 
419 			/*
420 			 * We need to fork a child process because
421 			 * there isn't a portable way to recover from
422 			 * a floating-point exception.
423 			 */
424 			switch(fork()) {
425 			case 0:		/* child */
426 				assert((fegetexcept() & ALL_STD_EXCEPT) == 0);
427 				assert((feenableexcept(except)
428 					   & ALL_STD_EXCEPT) == 0);
429 				assert(fegetexcept() == except);
430 				raiseexcept(raise);
431 				assert(feraiseexcept(raise) == 0);
432 				assert(fetestexcept(ALL_STD_EXCEPT) == raise);
433 
434 				assert(sigaction(SIGFPE, &act, NULL) == 0);
435 				switch (pass) {
436 				case 0:
437 					raiseexcept(except);
438 				case 1:
439 					feraiseexcept(except);
440 				default:
441 					assert(0);
442 				}
443 				assert(0);
444 			default:	/* parent */
445 				assert(wait(&status) > 0);
446 				/*
447 				 * Avoid assert() here so that it's possible
448 				 * to examine a failed child's core dump.
449 				 */
450 				if (!WIFEXITED(status))
451 					errx(1, "child aborted\n");
452 				assert(WEXITSTATUS(status) == 0);
453 				break;
454 			case -1:	/* error */
455 				assert(0);
456 			}
457 		}
458 	}
459 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
460 }
461 
462 /*
463  * Test feholdexcept() and feupdateenv().
464  *
465  * Prerequisites: fetestexcept(), fegetround(), fesetround(),
466  *	fedisableexcept(), feenableexcept()
467  */
468 static void
469 test_feholdupdate(void)
470 {
471 	fenv_t env;
472 
473 	struct sigaction act;
474 	int except, pass, status, raise;
475 	unsigned i;
476 
477 	sigemptyset(&act.sa_mask);
478 	act.sa_flags = 0;
479 	act.sa_handler = trap_handler;
480 	for (pass = 0; pass < 2; pass++) {
481 		for (i = 0; i < NEXCEPTS; i++) {
482 			except = std_excepts[i];
483 			/* over/underflow may also raise inexact */
484 			if (except == FE_INEXACT)
485 				raise = FE_DIVBYZERO | FE_INVALID;
486 			else
487 				raise = ALL_STD_EXCEPT ^ except;
488 
489 			/*
490 			 * We need to fork a child process because
491 			 * there isn't a portable way to recover from
492 			 * a floating-point exception.
493 			 */
494 			switch(fork()) {
495 			case 0:		/* child */
496 				/*
497 				 * We don't want to cause a fatal exception in
498 				 * the child until the second pass, so we can
499 				 * check other properties of feupdateenv().
500 				 */
501 				if (pass == 1)
502 					assert((feenableexcept(except) &
503 						   ALL_STD_EXCEPT) == 0);
504 				raiseexcept(raise);
505 				assert(fesetround(FE_DOWNWARD) == 0);
506 				assert(feholdexcept(&env) == 0);
507 				assert(fetestexcept(FE_ALL_EXCEPT) == 0);
508 				raiseexcept(except);
509 				assert(fesetround(FE_UPWARD) == 0);
510 
511 				if (pass == 1)
512 					assert(sigaction(SIGFPE, &act, NULL) ==
513 					    0);
514 				assert(feupdateenv(&env) == 0);
515 				assert(fegetround() == FE_DOWNWARD);
516 				assert(fetestexcept(ALL_STD_EXCEPT) ==
517 				    (except | raise));
518 
519 				assert(pass == 0);
520 				_exit(0);
521 			default:	/* parent */
522 				assert(wait(&status) > 0);
523 				/*
524 				 * Avoid assert() here so that it's possible
525 				 * to examine a failed child's core dump.
526 				 */
527 				if (!WIFEXITED(status))
528 					errx(1, "child aborted\n");
529 				assert(WEXITSTATUS(status) == 0);
530 				break;
531 			case -1:	/* error */
532 				assert(0);
533 			}
534 		}
535 	}
536 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
537 }
538 
539 int
540 main(void)
541 {
542 
543 	printf("1..8\n");
544 	init_exceptsets();
545 	test_dfl_env();
546 	printf("ok 1 - fenv\n");
547 	test_fetestclearexcept();
548 	printf("ok 2 - fenv\n");
549 	test_fegsetexceptflag();
550 	printf("ok 3 - fenv\n");
551 	test_feraiseexcept();
552 	printf("ok 4 - fenv\n");
553 	test_fegsetround();
554 	printf("ok 5 - fenv\n");
555 	test_fegsetenv();
556 	printf("ok 6 - fenv\n");
557 	test_masking();
558 	printf("ok 7 - fenv\n");
559 	test_feholdupdate();
560 	printf("ok 8 - fenv\n");
561 
562 	return (0);
563 }
564