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