The Gaudi Framework  v36r7 (7f57a304)
System.cpp
Go to the documentation of this file.
1 /***********************************************************************************\
2 * (c) Copyright 1998-2019 CERN for the benefit of the LHCb and ATLAS collaborations *
3 * *
4 * This software is distributed under the terms of the Apache version 2 licence, *
5 * copied verbatim in the file "LICENSE". *
6 * *
7 * In applying this licence, CERN does not waive the privileges and immunities *
8 * granted to it by virtue of its status as an Intergovernmental Organization *
9 * or submit itself to any jurisdiction. *
10 \***********************************************************************************/
11 //====================================================================
12 // System.cpp
13 //--------------------------------------------------------------------
14 //
15 // Package : System (The LHCb System service)
16 //
17 // Description: Implementation of Systems internals
18 //
19 // Author : M.Frank
20 // Created : 13/1/99
21 // Changes :
22 //====================================================================
23 #define SYSTEM_SYSTEM_CPP
24 #include <algorithm>
25 #include <array>
26 #include <cstdlib>
27 #include <cstring>
28 #include <ctime>
29 #include <iomanip>
30 #include <iostream>
31 #include <memory>
32 #include <regex>
33 #include <sstream>
34 #include <typeinfo>
35 
36 #include "GaudiKernel/System.h"
37 
38 // Platform specific include(s):
39 #ifdef __linux__
40 # include "Platform/SystemLinux.h"
41 #elif defined( __APPLE__ )
42 # include "Platform/SystemMacOS.h"
43 #elif defined( _WIN32 )
44 # include "Platform/SystemWin32.h"
45 #endif
46 
47 #define VCL_NAMESPACE Gaudi
49 #undef VCL_NAMESPACE
50 
51 #ifdef _WIN32
52 # define strcasecmp _stricmp
53 # define strncasecmp _strnicmp
54 # define getpid _getpid
55 # define NOMSG
56 # define NOGDI
57 # include "process.h"
58 # include "windows.h"
59 # undef NOMSG
60 # undef NOGDI
61 static const std::array<const char*, 1> SHLIB_SUFFIXES = { ".dll" };
62 #else // UNIX...: first the EGCS stuff, then the OS dependent includes
63 # include "libgen.h"
64 # include "sys/times.h"
65 # include "unistd.h"
66 # include <cstdio>
67 # include <cxxabi.h>
68 # include <errno.h>
69 # include <string.h>
70 # if defined( __linux ) || defined( __APPLE__ )
71 # include "dlfcn.h"
72 # include <sys/utsname.h>
73 # include <unistd.h>
74 # elif __hpux
75 # include "dl.h"
76 struct HMODULE {
77  shl_descriptor dsc;
78  long numSym;
79  shl_symbol* sym;
80 };
81 # endif // HPUX or not...
82 
83 # ifdef __APPLE__
84 static const std::array<const char*, 2> SHLIB_SUFFIXES = { ".dylib", ".so" };
85 # else
86 static const std::array<const char*, 1> SHLIB_SUFFIXES = { ".so" };
87 # endif // __APPLE__
88 
89 #endif // Windows or Unix...
90 
91 static unsigned long doLoad( const std::string& name, System::ImageHandle* handle ) {
92 #ifdef _WIN32
93  void* mh = ::LoadLibrary( name.length() == 0 ? System::exeName().c_str() : name.c_str() );
94  *handle = mh;
95 #else
96  const char* path = name.c_str();
97 # if defined( __linux ) || defined( __APPLE__ )
98  void* mh = ::dlopen( name.length() == 0 ? nullptr : path, RTLD_LAZY | RTLD_GLOBAL );
99  *handle = mh;
100 # elif __hpux
101  shl_t mh = ::shl_load( name.length() == 0 ? 0 : path, BIND_IMMEDIATE | BIND_VERBOSE, 0 );
102  HMODULE* mod = new HMODULE;
103  if ( 0 != mh ) {
104  if ( 0 != ::shl_gethandle_r( mh, &mod->dsc ) ) {
105  std::cout << "System::loadDynamicLib>" << ::strerror( getLastError() ) << std::endl;
106  } else {
107  typedef void* ( *___all )();
108  ___all _alloc = (___all)malloc;
109  mod->numSym = ::shl_getsymbols( mod->dsc.handle, TYPE_PROCEDURE, EXPORT_SYMBOLS, malloc, &mod->sym );
110  *handle = mod;
111  }
112  }
113 # endif
114 #endif
115  if ( !*handle ) { return System::getLastError(); }
116  return 1;
117 }
118 
119 static unsigned long loadWithoutEnvironment( const std::string& name, System::ImageHandle* handle ) {
120 
121  // If the name is empty, don't do anything complicated.
122  if ( name.length() == 0 ) { return doLoad( name, handle ); }
123 
124  // Check if the specified name has a shared library suffix already. If it
125  // does, don't bother the name any more.
126  std::string dllName = name;
127  bool hasShlibSuffix = false;
128  for ( const char* suffix : SHLIB_SUFFIXES ) {
129  const size_t len = strlen( suffix );
130  if ( dllName.compare( dllName.length() - len, len, suffix ) == 0 ) {
131  hasShlibSuffix = true;
132  break;
133  }
134  }
135 
136  // If it doesn't have a shared library suffix on it, add the "default" shared
137  // library suffix to the name.
138  if ( !hasShlibSuffix ) { dllName += SHLIB_SUFFIXES[0]; }
139 
140  // Load the library.
141  return doLoad( dllName, handle );
142 }
143 
145 unsigned long System::loadDynamicLib( const std::string& name, ImageHandle* handle ) {
146  unsigned long res = 0;
147  // if name is empty, just load it
148  if ( name.length() == 0 ) {
149  res = loadWithoutEnvironment( name, handle );
150  } else {
151  // If the name is a logical name (environment variable), the try
152  // to load the corresponding library from there.
153  std::string imgName;
154  if ( getEnv( name, imgName ) ) {
155  res = loadWithoutEnvironment( imgName, handle );
156  } else {
157  // build the dll name
158  std::string dllName = name;
159 // Add a possible "lib" prefix to the name on unix platforms. But only if
160 // it's not an absolute path name.
161 #if defined( __linux ) || defined( __APPLE__ )
162  if ( ( dllName.find( '/' ) == std::string::npos ) && ( dllName.compare( 0, 3, "lib" ) != 0 ) ) {
163  dllName = "lib" + dllName;
164  }
165 #endif // unix
166  // Now try loading the library with all possible suffixes supported by the
167  // platform.
168  for ( const char* suffix : SHLIB_SUFFIXES ) {
169  // Add the suffix if necessary.
170  std::string libName = dllName;
171  const size_t len = strlen( suffix );
172  if ( dllName.compare( dllName.length() - len, len, suffix ) != 0 ) { libName += suffix; }
173  // Try to load the library.
174  res = loadWithoutEnvironment( libName, handle );
175  // If the load succeeded, stop here.
176  if ( res == 1 ) { break; }
177  }
178  }
179  if ( res != 1 ) {
180 #if defined( __linux ) || defined( __APPLE__ )
181  errno = 0xAFFEDEAD;
182 #endif
183  // std::cout << "System::loadDynamicLib>" << getLastErrorString() << std::endl;
184  }
185  }
186  return res;
187 }
188 
190 unsigned long System::unloadDynamicLib( ImageHandle handle ) {
191 #ifdef _WIN32
192  if ( !::FreeLibrary( (HINSTANCE)handle ) ) {
193 #elif defined( __linux ) || defined( __APPLE__ )
194  ::dlclose( handle );
195  if ( 0 ) {
196 #elif __hpux
197  // On HP we have to run finalization ourselves.....
198  Creator pFinalize = 0;
199  if ( getProcedureByName( handle, "_fini", &pFinalize ) ) { pFinalize(); }
200  HMODULE* mod = (HMODULE*)handle;
201  if ( 0 == ::shl_unload( mod->dsc.handle ) ) {
202  delete mod;
203  } else {
204 #else
205  if ( false ) {
206 #endif
207  return getLastError();
208  }
209  return 1;
210 }
211 
213 unsigned long System::getProcedureByName( ImageHandle handle, const std::string& name, EntryPoint* pFunction ) {
214 #ifdef _WIN32
215  *pFunction = ( EntryPoint )::GetProcAddress( (HINSTANCE)handle, name.data() );
216  if ( 0 == *pFunction ) { return System::getLastError(); }
217  return 1;
218 #elif defined( __linux )
219  *pFunction = reinterpret_cast<EntryPoint>( ::dlsym( handle, name.c_str() ) );
220  if ( !*pFunction ) {
221  errno = 0xAFFEDEAD;
222  // std::cout << "System::getProcedureByName>" << getLastErrorString() << std::endl;
223  return 0;
224  }
225  return 1;
226 #elif defined( __APPLE__ )
227  *pFunction = ( EntryPoint )::dlsym( handle, name.c_str() );
228  if ( !( *pFunction ) ) {
229  // Try with an underscore :
230  std::string sname = "_" + name;
231  *pFunction = ( EntryPoint )::dlsym( handle, sname.c_str() );
232  }
233  if ( 0 == *pFunction ) {
234  errno = 0xAFFEDEAD;
235  std::cout << "System::getProcedureByName>" << getLastErrorString() << std::endl;
236  // std::cout << "System::getProcedureByName> failure" << std::endl;
237  return 0;
238  }
239  return 1;
240 #elif __hpux
241  HMODULE* mod = (HMODULE*)handle;
242  if ( 0 != mod ) {
243  long ll1 = name.length();
244  for ( int i = 0; i < mod->numSym; i++ ) {
245  long ll2 = strlen( mod->sym[i].name );
246  if ( 0 != ::strncmp( mod->sym[i].name, name.c_str(), ( ll1 > ll2 ) ? ll1 : ll2 ) == 0 ) {
247  *pFunction = (EntryPoint)mod->sym[i].value;
248  return 1;
249  }
250  }
251  }
252  return 0;
253 #endif
254 }
255 
257 unsigned long System::getProcedureByName( ImageHandle handle, const std::string& name, Creator* pFunction ) {
258  return getProcedureByName( handle, name, (EntryPoint*)pFunction );
259 }
260 
262 unsigned long System::getLastError() {
263 #ifdef _WIN32
264  return ::GetLastError();
265 #else
266  // convert errno (int) to unsigned long
267  return static_cast<unsigned long>( static_cast<unsigned int>( errno ) );
268 #endif
269 }
270 
273  const std::string errString = getErrorString( getLastError() );
274  return errString;
275 }
276 
278 const std::string System::getErrorString( unsigned long error ) {
279  std::string errString = "";
280 #ifdef _WIN32
281  LPVOID lpMessageBuffer;
282  ::FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error,
283  MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ), // The user default language
284  (LPTSTR)&lpMessageBuffer, 0, NULL );
285  errString = (const char*)lpMessageBuffer;
286  // Free the buffer allocated by the system
287  ::LocalFree( lpMessageBuffer );
288 #else
289  char* cerrString( nullptr );
290  // Remember: for linux dl* routines must be handled differently!
291  if ( error == 0xAFFEDEAD ) {
292  cerrString = ::dlerror();
293  if ( !cerrString ) cerrString = ::strerror( error );
294  if ( !cerrString ) {
295  cerrString = (char*)"Unknown error. No information found in strerror()!";
296  } else {
297  errString = std::string( cerrString );
298  }
299  errno = 0;
300  } else {
301  cerrString = ::strerror( error );
302  errString = std::string( cerrString );
303  }
304 #endif
305  return errString;
306 }
307 
308 const std::string System::typeinfoName( const std::type_info& tinfo ) { return typeinfoName( tinfo.name() ); }
309 
310 const std::string System::typeinfoName( const char* class_name ) { return Platform::typeinfoName( class_name ); }
311 
314  static const std::string host = Platform::hostName();
315  return host;
316 }
317 
320  static const std::string osname = Platform::osName();
321  return osname;
322 }
323 
326  static const std::string osver = Platform::osVersion();
327  return osver;
328 }
329 
332  static const std::string mach = Platform::machineType();
333  return mach;
334 }
335 
337  using namespace Gaudi;
338  return instrset_detect();
339 }
340 
343  static const std::string account = Platform::accountName();
344  return account;
345 }
346 
349 
351 long System::argc() { return cmdLineArgs().size(); }
352 
356  return args;
357 }
358 
360 char** System::argv() {
361  auto helperFunc = []( const std::vector<std::string>& args ) -> std::vector<const char*> {
363  std::transform( args.begin(), args.end(), std::back_inserter( result ),
364  []( const std::string& s ) { return s.c_str(); } );
365  return result;
366  };
367  static const std::vector<const char*> args = helperFunc( cmdLineArgs() );
368  // We rely here on the fact that a vector's allocation table is contiguous
369  return (char**)&( args[0] );
370 }
371 
372 #ifdef WIN32
373 // disable warning
374 // C4996: 'getenv': This function or variable may be unsafe.
375 # pragma warning( disable : 4996 )
376 #endif
377 
379 std::string System::getEnv( const char* var ) {
380  char* env;
381  if ( ( env = getenv( var ) ) != nullptr ) {
382  return env;
383  } else {
384  return "UNKNOWN";
385  }
386 }
387 
389 bool System::getEnv( const char* var, std::string& value ) {
390  char* env;
391  if ( ( env = getenv( var ) ) != nullptr ) {
392  value = env;
393  return true;
394  } else {
395  return false;
396  }
397 }
398 
399 bool System::isEnvSet( const char* var ) { return getenv( var ) != nullptr; }
400 
402 #if defined( __APPLE__ )
403 // Needed for _NSGetEnviron(void)
404 # include "crt_externs.h"
405 #endif
407 #if defined( _WIN32 )
408 # define environ _environ
409 #elif defined( __APPLE__ )
410  static char** environ = *_NSGetEnviron();
411 #endif
413  for ( int i = 0; environ[i] != nullptr; ++i ) { vars.push_back( environ[i] ); }
414  return vars;
415 }
416 
417 // -----------------------------------------------------------------------------
418 // backtrace utilities
419 // -----------------------------------------------------------------------------
420 #ifdef __linux
421 # include <execinfo.h>
422 #endif
423 
424 int System::backTrace( [[maybe_unused]] void** addresses, [[maybe_unused]] const int depth ) {
425 
426 #ifdef __linux
427 
428  int count = backtrace( addresses, depth );
429  return count > 0 ? count : 0;
430 
431 #else // windows and osx parts not implemented
432  return 0;
433 #endif
434 }
435 
436 bool System::backTrace( std::string& btrace, const int depth, const int offset ) {
437  try {
438  // Always hide the first two levels of the stack trace (that's us)
439  const int totalOffset = offset + 2;
440  const int totalDepth = depth + totalOffset;
441 
442  std::string fnc, lib;
443 
444  std::vector<void*> addresses( totalDepth, nullptr );
445  int count = System::backTrace( addresses.data(), totalDepth );
446  for ( int i = totalOffset; i < count; ++i ) {
447  void* addr = nullptr;
448 
449  if ( System::getStackLevel( addresses[i], addr, fnc, lib ) ) {
450  std::ostringstream ost;
451  ost << "#" << std::setw( 3 ) << std::setiosflags( std::ios::left ) << i - totalOffset + 1;
452  ost << std::hex << addr << std::dec << " " << fnc << " [" << lib << "]" << std::endl;
453  btrace += ost.str();
454  }
455  }
456  return true;
457  } catch ( const std::bad_alloc& e ) { return false; }
458 }
459 
460 bool System::getStackLevel( [[maybe_unused]] void* addresses, [[maybe_unused]] void*& addr,
461  [[maybe_unused]] std::string& fnc, [[maybe_unused]] std::string& lib ) {
462 
463 #ifdef __linux
464 
465  Dl_info info;
466 
467  if ( dladdr( addresses, &info ) && info.dli_fname && info.dli_fname[0] != '\0' ) {
468  const char* symbol = info.dli_sname && info.dli_sname[0] != '\0' ? info.dli_sname : nullptr;
469 
470  lib = info.dli_fname;
471  addr = info.dli_saddr;
472 
473  if ( symbol ) {
474  int stat = -1;
475  auto dmg =
476  std::unique_ptr<char, decltype( free )*>( abi::__cxa_demangle( symbol, nullptr, nullptr, &stat ), std::free );
477  fnc = ( stat == 0 ) ? dmg.get() : symbol;
478  } else {
479  fnc = "local";
480  }
481  return true;
482  } else {
483  return false;
484  }
485 
486 #else // not implemented for windows and osx
487  return false;
488 #endif
489 }
490 
492 int System::setEnv( const std::string& name, const std::string& value, int overwrite ) {
493 #ifndef WIN32
494  // UNIX version
495  return value.empty() ?
496  // remove if set to nothing (and return success)
497  ::unsetenv( name.c_str() ),
498  0 :
499  // set the value
500  ::setenv( name.c_str(), value.c_str(), overwrite );
501 #else
502  // Windows version
503  if ( value.empty() ) {
504  // equivalent to unsetenv
505  return ::_putenv( ( name + "=" ).c_str() );
506  } else {
507  if ( !getenv( name.c_str() ) || overwrite ) {
508  // set if not yet present or overwrite is set (force)
509  return ::_putenv( ( name + "=" + value ).c_str() );
510  }
511  }
512  return 0; // if we get here, we are trying to set a variable already set, but
513  // not to overwrite.
514  // It is considered a success on Linux (man P setenv)
515 #endif
516 }
System::getErrorString
GAUDI_API const std::string getErrorString(unsigned long error)
Retrieve error code as string for a given error.
Definition: System.cpp:278
instrset_detect.cpp
System::loadDynamicLib
GAUDI_API unsigned long loadDynamicLib(const std::string &name, ImageHandle *handle)
Load dynamic link library.
Definition: System.cpp:145
std::strlen
T strlen(T... args)
std::string
STL class.
System::argc
GAUDI_API long argc()
Number of arguments passed to the commandline (==numCmdLineArgs()); just to match argv call....
Definition: System.cpp:351
std::bad_alloc
STL class.
System::getLastError
GAUDI_API unsigned long getLastError()
Get last system known error.
Definition: System.cpp:262
System::EntryPoint
unsigned long(* EntryPoint)(const unsigned long iid, void **ppvObject)
Definition of the "generic" DLL entry point function.
Definition: System.h:45
System.h
gaudirun.s
string s
Definition: gaudirun.py:346
System::getEnv
GAUDI_API std::string getEnv(const char *var)
get a particular environment variable (returning "UNKNOWN" if not set)
Definition: System.cpp:379
std::vector< std::string >
std::string::find
T find(T... args)
std::string::length
T length(T... args)
std::type_info
std::back_inserter
T back_inserter(T... args)
std::type_info::name
T name(T... args)
System::setEnv
GAUDI_API int setEnv(const std::string &name, const std::string &value, int overwrite=1)
Set an environment variables.
Definition: System.cpp:492
System::instructionsetLevel
GAUDI_API int instructionsetLevel()
Instruction Set "Level".
Definition: System.cpp:336
System::ImageHandle
void * ImageHandle
Definition of an image handle.
Definition: ModuleInfo.h:40
System::getProcedureByName
GAUDI_API unsigned long getProcedureByName(ImageHandle handle, const std::string &name, EntryPoint *pFunction)
Get a specific function defined in the DLL.
Definition: System.cpp:213
System::typeinfoName
GAUDI_API const std::string typeinfoName(const std::type_info &)
Get platform independent information about the class type.
Definition: System.cpp:308
System::getStackLevel
GAUDI_API bool getStackLevel(void *addresses, void *&addr, std::string &fnc, std::string &lib)
System::backTrace
GAUDI_API int backTrace(void **addresses, const int depth)
System::osName
GAUDI_API const std::string & osName()
OS name.
Definition: System.cpp:319
SystemWin32.h
System::exeName
GAUDI_API const std::string & exeName()
Name of the executable file running.
Definition: ModuleInfo.cpp:203
std::hex
T hex(T... args)
std::vector::push_back
T push_back(T... args)
System::accountName
GAUDI_API const std::string & accountName()
User login name.
Definition: System.cpp:342
Gaudi.CommonGaudiConfigurables.mod
mod
Definition: CommonGaudiConfigurables.py:40
SystemLinux.h
TimingHistograms.name
name
Definition: TimingHistograms.py:25
SystemMacOS.h
std::cout
std::string::c_str
T c_str(T... args)
std::string::compare
T compare(T... args)
std::array
STL class.
GaudiPython.HistoUtils.path
path
Definition: HistoUtils.py:961
System::numCmdLineArgs
GAUDI_API long numCmdLineArgs()
Number of arguments passed to the commandline.
Definition: System.cpp:348
compareOutputFiles.sname
string sname
Definition: compareOutputFiles.py:489
instrset_detect
int instrset_detect(void)
Definition: instrset_detect.cpp:63
System::isEnvSet
GAUDI_API bool isEnvSet(const char *var)
Check if an environment variable is set or not.
Definition: System.cpp:399
std::transform
T transform(T... args)
Gaudi
Header file for std:chrono::duration-based Counters.
Definition: __init__.py:1
System::Creator
void *(* Creator)()
Definition of the "generic" DLL entry point function.
Definition: System.h:47
std::ostringstream
STL class.
System::unloadDynamicLib
GAUDI_API unsigned long unloadDynamicLib(ImageHandle handle)
unload dynamic link library
Definition: System.cpp:190
std::endl
T endl(T... args)
gaudirun.args
args
Definition: gaudirun.py:336
System::cmdLineArgs
GAUDI_API const std::vector< std::string > cmdLineArgs()
Command line arguments including executable name as arg[0] as vector of strings.
Definition: System.cpp:354
std::setiosflags
T setiosflags(T... args)
System::machineType
GAUDI_API const std::string & machineType()
Machine type.
Definition: System.cpp:331
std::free
T free(T... args)
std::string::empty
T empty(T... args)
std::ostringstream::str
T str(T... args)
System::hostName
GAUDI_API const std::string & hostName()
Host name.
Definition: System.cpp:313
std::setw
T setw(T... args)
System::getLastErrorString
GAUDI_API const std::string getLastErrorString()
Get last system error as string.
Definition: System.cpp:272
std::unique_ptr
STL class.
std::vector::data
T data(T... args)
System::osVersion
GAUDI_API const std::string & osVersion()
OS version.
Definition: System.cpp:325
System::argv
GAUDI_API char ** argv()
char** command line arguments including executable name as arg[0]; You may not modify them!
Definition: System.cpp:360