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