1 /* 2 Copyright (c) 2018-2022 Intel Corporation 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 #ifndef __TBB_tbb_environment_H 18 #define __TBB_tbb_environment_H 19 20 #include <cstdlib> 21 #include <cstring> 22 #include <cerrno> 23 #include <cctype> 24 25 namespace tbb { 26 namespace detail { 27 namespace r1 { 28 29 #if __TBB_WIN8UI_SUPPORT 30 static inline bool GetBoolEnvironmentVariable( const char * ) { 31 return false; 32 } 33 34 static inline long GetIntegralEnvironmentVariable( const char * ) { 35 return -1; 36 } 37 #else /* __TBB_WIN8UI_SUPPORT */ 38 static inline bool GetBoolEnvironmentVariable( const char * name ) { 39 if ( const char* s = std::getenv(name) ) { 40 // The result is defined as true only if the environment variable contains 41 // no characters except one '1' character and an arbitrary number of spaces 42 // (including the absence of spaces). 43 size_t index = std::strspn(s, " "); 44 if (s[index] != '1') return false; 45 index++; 46 // Memory access after incrementing is safe, since the getenv() returns a 47 // null-terminated string, and even if the character getting by index is '1', 48 // and this character is the end of string, after incrementing we will get 49 // an index of character, that contains '\0' 50 index += std::strspn(&s[index], " "); 51 return !s[index]; 52 } 53 return false; 54 } 55 56 static inline long GetIntegralEnvironmentVariable( const char * name ) { 57 if ( const char* s = std::getenv(name) ) { 58 char* end = nullptr; 59 errno = 0; 60 long value = std::strtol(s, &end, 10); 61 62 // We have exceeded the range, value is negative or string is incovertable 63 if ( errno == ERANGE || value < 0 || end==s ) { 64 return -1; 65 } 66 for ( ; *end != '\0'; end++ ) { 67 if ( !std::isspace(*end) ) { 68 return -1; 69 } 70 } 71 return value; 72 } 73 return -1; 74 } 75 #endif /* __TBB_WIN8UI_SUPPORT */ 76 77 } // namespace r1 78 } // namespace detail 79 } // namespace tbb 80 81 #endif // __TBB_tbb_environment_H 82