xref: /freebsd/lib/msun/tests/fenv_test.c (revision 89e3d5671ba13dceca272d5b159c9bd805f3f504)
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 #include "test-utils.h"
47 
48 #define	NEXCEPTS	(sizeof(std_excepts) / sizeof(std_excepts[0]))
49 
50 static const int std_excepts[] = {
51 	FE_INVALID,
52 	FE_DIVBYZERO,
53 	FE_OVERFLOW,
54 	FE_UNDERFLOW,
55 	FE_INEXACT,
56 };
57 
58 /* init_exceptsets() initializes this to the power set of std_excepts[] */
59 static int std_except_sets[1 << NEXCEPTS];
60 
61 #pragma STDC FENV_ACCESS ON
62 
63 /*
64  * Initialize std_except_sets[] to the power set of std_excepts[]
65  */
66 static void
67 init_exceptsets(void)
68 {
69 	unsigned i, j, sr;
70 
71 	for (i = 0; i < 1 << NEXCEPTS; i++) {
72 		for (sr = i, j = 0; sr != 0; sr >>= 1, j++)
73 			std_except_sets[i] |= std_excepts[j] & ((~sr & 1) - 1);
74 	}
75 }
76 
77 /*
78  * Raise a floating-point exception without relying on the standard
79  * library routines, which we are trying to test.
80  *
81  * XXX We can't raise an {over,under}flow without also raising an
82  * inexact exception.
83  */
84 static void
85 raiseexcept(int excepts)
86 {
87 	volatile double d;
88 
89 	/*
90 	 * With a compiler that supports the FENV_ACCESS pragma
91 	 * properly, simple expressions like '0.0 / 0.0' should
92 	 * be sufficient to generate traps.  Unfortunately, we
93 	 * need to bring a volatile variable into the equation
94 	 * to prevent incorrect optimizations.
95 	 */
96 	if (excepts & FE_INVALID) {
97 		d = 0.0;
98 		d = 0.0 / d;
99 	}
100 	if (excepts & FE_DIVBYZERO) {
101 		d = 0.0;
102 		d = 1.0 / d;
103 	}
104 	if (excepts & FE_OVERFLOW) {
105 		d = DBL_MAX;
106 		d *= 2.0;
107 	}
108 	if (excepts & FE_UNDERFLOW) {
109 		d = DBL_MIN;
110 		d /= DBL_MAX;
111 	}
112 	if (excepts & FE_INEXACT) {
113 		d = DBL_MIN;
114 		d += 1.0;
115 	}
116 
117 	/*
118 	 * On the x86 (and some other architectures?) the FPU and
119 	 * integer units are decoupled.  We need to execute an FWAIT
120 	 * or a floating-point instruction to get synchronous exceptions.
121 	 */
122 	d = 1.0;
123 	d += 1.0;
124 }
125 
126 /*
127  * Determine the current rounding mode without relying on the fenv
128  * routines.  This function may raise an inexact exception.
129  */
130 static int
131 getround(void)
132 {
133 	volatile double d;
134 
135 	/*
136 	 * This test works just as well with 0.0 - 0.0, except on ia64
137 	 * where 0.0 - 0.0 gives the wrong sign when rounding downwards.
138 	 */
139 	d = 1.0;
140 	d -= 1.0;
141 	if (copysign(1.0, d) < 0.0)
142 		return (FE_DOWNWARD);
143 
144 	d = 1.0;
145 	if (d + (DBL_EPSILON * 3.0 / 4.0) == 1.0)
146 		return (FE_TOWARDZERO);
147 	if (d + (DBL_EPSILON * 1.0 / 4.0) > 1.0)
148 		return (FE_UPWARD);
149 
150 	return (FE_TONEAREST);
151 }
152 
153 static void
154 trap_handler(int sig)
155 {
156 
157 	assert(sig == SIGFPE);
158 	_exit(0);
159 }
160 
161 /*
162  * This tests checks the default FP environment, so it must be first.
163  * The memcmp() test below may be too much to ask for, since there
164  * could be multiple machine-specific default environments.
165  */
166 static void
167 test_dfl_env(void)
168 {
169 #ifndef NO_STRICT_DFL_ENV
170 	fenv_t env;
171 
172 	fegetenv(&env);
173 
174 #ifdef __amd64__
175 	/*
176 	 * Compare the fields that the AMD [1] and Intel [2] specs say will be
177 	 * set once fnstenv returns.
178 	 *
179 	 * Not all amd64 capable processors implement the fnstenv instruction
180 	 * by zero'ing out the env.__x87.__other field (example: AMD Opteron
181 	 * 6308). The AMD64/x64 specs aren't explicit on what the
182 	 * env.__x87.__other field will contain after fnstenv is executed, so
183 	 * the values in env.__x87.__other could be filled with arbitrary
184 	 * data depending on how the CPU implements fnstenv.
185 	 *
186 	 * 1. http://support.amd.com/TechDocs/26569_APM_v5.pdf
187 	 * 2. http://www.intel.com/Assets/en_US/PDF/manual/253666.pdf
188 	 */
189 	assert(memcmp(&env.__mxcsr, &FE_DFL_ENV->__mxcsr,
190 	    sizeof(env.__mxcsr)) == 0);
191 	assert(memcmp(&env.__x87.__control, &FE_DFL_ENV->__x87.__control,
192 	    sizeof(env.__x87.__control)) == 0);
193 	assert(memcmp(&env.__x87.__status, &FE_DFL_ENV->__x87.__status,
194 	    sizeof(env.__x87.__status)) == 0);
195 	assert(memcmp(&env.__x87.__tag, &FE_DFL_ENV->__x87.__tag,
196 	    sizeof(env.__x87.__tag)) == 0);
197 #else
198 	assert(memcmp(&env, FE_DFL_ENV, sizeof(env)) == 0);
199 #endif
200 
201 #endif
202 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
203 }
204 
205 /*
206  * Test fetestexcept() and feclearexcept().
207  */
208 static void
209 test_fetestclearexcept(void)
210 {
211 	int excepts, i;
212 
213 	for (i = 0; i < 1 << NEXCEPTS; i++)
214 		assert(fetestexcept(std_except_sets[i]) == 0);
215 	for (i = 0; i < 1 << NEXCEPTS; i++) {
216 		excepts = std_except_sets[i];
217 
218 		/* FE_ALL_EXCEPT might be special-cased, as on i386. */
219 		raiseexcept(excepts);
220 		assert(fetestexcept(excepts) == excepts);
221 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
222 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
223 
224 		raiseexcept(excepts);
225 		assert(fetestexcept(excepts) == excepts);
226 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0) {
227 			excepts |= FE_INEXACT;
228 			assert((fetestexcept(ALL_STD_EXCEPT) | FE_INEXACT) ==
229 			    excepts);
230 		} else {
231 			assert(fetestexcept(ALL_STD_EXCEPT) == excepts);
232 		}
233 		assert(feclearexcept(excepts) == 0);
234 		assert(fetestexcept(ALL_STD_EXCEPT) == 0);
235 	}
236 }
237 
238 /*
239  * Test fegetexceptflag() and fesetexceptflag().
240  *
241  * Prerequisites: fetestexcept(), feclearexcept()
242  */
243 static void
244 test_fegsetexceptflag(void)
245 {
246 	fexcept_t flag;
247 	int excepts, i;
248 
249 	assert(fetestexcept(FE_ALL_EXCEPT) == 0);
250 	for (i = 0; i < 1 << NEXCEPTS; i++) {
251 		excepts = std_except_sets[i];
252 
253 		assert(fegetexceptflag(&flag, excepts) == 0);
254 		raiseexcept(ALL_STD_EXCEPT);
255 		assert(fesetexceptflag(&flag, excepts) == 0);
256 		assert(fetestexcept(ALL_STD_EXCEPT) ==
257 		    (ALL_STD_EXCEPT ^ excepts));
258 
259 		assert(fegetexceptflag(&flag, FE_ALL_EXCEPT) == 0);
260 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
261 		assert(fesetexceptflag(&flag, excepts) == 0);
262 		assert(fetestexcept(ALL_STD_EXCEPT) == 0);
263 		assert(fesetexceptflag(&flag, ALL_STD_EXCEPT ^ excepts) == 0);
264 		assert(fetestexcept(ALL_STD_EXCEPT) ==
265 		    (ALL_STD_EXCEPT ^ excepts));
266 
267 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
268 	}
269 }
270 
271 /*
272  * Test feraiseexcept().
273  *
274  * Prerequisites: fetestexcept(), feclearexcept()
275  */
276 static void
277 test_feraiseexcept(void)
278 {
279 	int excepts, i;
280 
281 	for (i = 0; i < 1 << NEXCEPTS; i++) {
282 		excepts = std_except_sets[i];
283 
284 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
285 		assert(feraiseexcept(excepts) == 0);
286 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0) {
287 			excepts |= FE_INEXACT;
288 			assert((fetestexcept(ALL_STD_EXCEPT) | FE_INEXACT) ==
289 			    excepts);
290 		} else {
291 			assert(fetestexcept(ALL_STD_EXCEPT) == excepts);
292 		}
293 		assert(feclearexcept(FE_ALL_EXCEPT) == 0);
294 	}
295 	assert(feraiseexcept(FE_INVALID | FE_DIVBYZERO) == 0);
296 	assert(fetestexcept(ALL_STD_EXCEPT) == (FE_INVALID | FE_DIVBYZERO));
297 	assert(feraiseexcept(FE_OVERFLOW | FE_UNDERFLOW | FE_INEXACT) == 0);
298 	assert(fetestexcept(ALL_STD_EXCEPT) == ALL_STD_EXCEPT);
299 	assert(feclearexcept(FE_ALL_EXCEPT) == 0);
300 }
301 
302 /*
303  * Test fegetround() and fesetround().
304  */
305 static void
306 test_fegsetround(void)
307 {
308 
309 	assert(fegetround() == FE_TONEAREST);
310 	assert(getround() == FE_TONEAREST);
311 	assert(FLT_ROUNDS == 1);
312 
313 	assert(fesetround(FE_DOWNWARD) == 0);
314 	assert(fegetround() == FE_DOWNWARD);
315 	assert(getround() == FE_DOWNWARD);
316 	assert(FLT_ROUNDS == 3);
317 
318 	assert(fesetround(FE_UPWARD) == 0);
319 	assert(getround() == FE_UPWARD);
320 	assert(fegetround() == FE_UPWARD);
321 	assert(FLT_ROUNDS == 2);
322 
323 	assert(fesetround(FE_TOWARDZERO) == 0);
324 	assert(getround() == FE_TOWARDZERO);
325 	assert(fegetround() == FE_TOWARDZERO);
326 	assert(FLT_ROUNDS == 0);
327 
328 	assert(fesetround(FE_TONEAREST) == 0);
329 	assert(getround() == FE_TONEAREST);
330 	assert(FLT_ROUNDS == 1);
331 
332 	assert(feclearexcept(FE_ALL_EXCEPT) == 0);
333 }
334 
335 /*
336  * Test fegetenv() and fesetenv().
337  *
338  * Prerequisites: fetestexcept(), feclearexcept(), fegetround(), fesetround()
339  */
340 static void
341 test_fegsetenv(void)
342 {
343 	fenv_t env1, env2;
344 	int excepts, i;
345 
346 	for (i = 0; i < 1 << NEXCEPTS; i++) {
347 		excepts = std_except_sets[i];
348 
349 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
350 		assert(fegetround() == FE_TONEAREST);
351 		assert(fegetenv(&env1) == 0);
352 
353 		/*
354 		 * fe[gs]etenv() should be able to save and restore
355 		 * exception flags without the spurious inexact
356 		 * exceptions that afflict raiseexcept().
357 		 */
358 		raiseexcept(excepts);
359 		if ((excepts & (FE_UNDERFLOW | FE_OVERFLOW)) != 0 &&
360 		    (excepts & FE_INEXACT) == 0)
361 			assert(feclearexcept(FE_INEXACT) == 0);
362 
363 		fesetround(FE_DOWNWARD);
364 		assert(fegetenv(&env2) == 0);
365 		assert(fesetenv(&env1) == 0);
366 		assert(fetestexcept(FE_ALL_EXCEPT) == 0);
367 		assert(fegetround() == FE_TONEAREST);
368 
369 		assert(fesetenv(&env2) == 0);
370 
371 		/*
372 		 * Some platforms like powerpc may set extra exception bits. Since
373 		 * only standard exceptions are tested, mask against ALL_STD_EXCEPT
374 		 */
375 		assert((fetestexcept(FE_ALL_EXCEPT) & ALL_STD_EXCEPT) == excepts);
376 
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