|
32 | 32 |
|
33 | 33 | #include "lapacke_utils.h" |
34 | 34 |
|
| 35 | +#include <stdlib.h> |
| 36 | +#include <string.h> |
| 37 | + |
35 | 38 | static int nancheck_flag = -1; |
36 | 39 |
|
37 | 40 | void LAPACKE_set_nancheck( int flag ) |
38 | 41 | { |
39 | 42 | nancheck_flag = ( flag ) ? 1 : 0; |
40 | 43 | } |
41 | 44 |
|
| 45 | +typedef struct { |
| 46 | + int found; |
| 47 | + char *value; |
| 48 | +} lapacke_env_var; |
| 49 | + |
| 50 | +static inline lapacke_env_var LAPACKE_getenv(const char *var_name) |
| 51 | +{ |
| 52 | + size_t var_length = 0; |
| 53 | + |
| 54 | + /* Get the length of the environment variable value */ |
| 55 | +#if defined(_WIN32) |
| 56 | + errno_t result = getenv_s( &var_length, NULL, 0, var_name ); |
| 57 | + if ( result != 0 || var_length == 0 ) { |
| 58 | + return (lapacke_env_var){ 0, NULL }; |
| 59 | + } |
| 60 | +#else |
| 61 | + const char *env = getenv( var_name ); |
| 62 | + if ( env == NULL ) { |
| 63 | + return (lapacke_env_var){ 0, NULL }; |
| 64 | + } |
| 65 | + var_length = strlen( env ) + 1; |
| 66 | +#endif |
| 67 | + |
| 68 | + /* Allocate memory for the environment variable value */ |
| 69 | + char *value = (char *)LAPACKE_malloc( var_length ); |
| 70 | + if ( value == NULL ) { |
| 71 | + return (lapacke_env_var){ 0, NULL }; |
| 72 | + } |
| 73 | + |
| 74 | + /* Get the value of the environment variable */ |
| 75 | +#if defined(_WIN32) |
| 76 | + result = getenv_s( &var_length, value, var_length, var_name ); |
| 77 | + if ( result != 0 ) { |
| 78 | + LAPACKE_free( value ); |
| 79 | + return (lapacke_env_var){ 0, NULL }; |
| 80 | + } |
| 81 | +#else |
| 82 | + memcpy( value, env, var_length ); |
| 83 | +#endif |
| 84 | + |
| 85 | + return (lapacke_env_var){ 1, value }; |
| 86 | +} |
| 87 | + |
| 88 | +static inline void LAPACKE_freenv(lapacke_env_var *var) |
| 89 | +{ |
| 90 | + if ( var->found && var->value != NULL ) { |
| 91 | + LAPACKE_free( var->value ); |
| 92 | + } |
| 93 | + var->found = 0; |
| 94 | + var->value = NULL; |
| 95 | +} |
| 96 | + |
42 | 97 | int LAPACKE_get_nancheck( ) |
43 | 98 | { |
44 | | - char* env; |
45 | 99 | if ( nancheck_flag != -1 ) { |
46 | 100 | return nancheck_flag; |
47 | 101 | } |
48 | 102 |
|
49 | 103 | /* Check environment variable, once and only once */ |
50 | | - env = getenv( "LAPACKE_NANCHECK" ); |
51 | | - if ( !env ) { |
| 104 | + lapacke_env_var lapacke_nancheck = LAPACKE_getenv( "LAPACKE_NANCHECK" ); |
| 105 | + if ( !lapacke_nancheck.found ) { |
52 | 106 | /* By default, NaN checking is enabled */ |
53 | 107 | nancheck_flag = 1; |
54 | 108 | } else { |
55 | | - nancheck_flag = atoi( env ) ? 1 : 0; |
| 109 | + nancheck_flag = atoi( lapacke_nancheck.value ) ? 1 : 0; |
56 | 110 | } |
57 | 111 |
|
| 112 | + LAPACKE_freenv( &lapacke_nancheck ); |
58 | 113 | return nancheck_flag; |
59 | 114 | } |
0 commit comments