libc.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #include "libc.h"
  2. #if _WIN32
  3. #include <windows.h>
  4. #include <bbstring.h>
  5. #if _MSC_VER
  6. #include <stdint.h>
  7. #endif
  8. #elif __APPLE__
  9. #include <TargetConditionals.h>
  10. #endif
  11. void setenv_( const char *name,const char *value,int overwrite ){
  12. #if _WIN32
  13. if( !overwrite && getenv( name ) ) return;
  14. bbString tmp=bbString( name )+BB_T( "=" )+bbString( value );
  15. putenv( tmp.c_str() );
  16. #else
  17. setenv( name,value,overwrite );
  18. #endif
  19. }
  20. int system_( const char *cmd ){
  21. #if _WIN32
  22. bool inherit=false;
  23. DWORD flags=CREATE_NO_WINDOW;
  24. STARTUPINFOA si={sizeof(si)};
  25. PROCESS_INFORMATION pi={0};
  26. bbString tmp=BB_T( "cmd /S /C\"" )+BB_T( cmd )+BB_T( "\"" );
  27. if( GetStdHandle( STD_OUTPUT_HANDLE ) ){
  28. inherit=true;
  29. si.dwFlags=STARTF_USESTDHANDLES;
  30. si.hStdInput=GetStdHandle( STD_INPUT_HANDLE );
  31. si.hStdOutput=GetStdHandle( STD_OUTPUT_HANDLE );
  32. si.hStdError=GetStdHandle( STD_ERROR_HANDLE );
  33. }
  34. if( GetConsoleWindow() ){
  35. flags=0;
  36. }
  37. if( !CreateProcessA( 0,(LPSTR)tmp.c_str(),0,0,inherit,flags,0,0,&si,&pi ) ) return -1;
  38. WaitForSingleObject( pi.hProcess,INFINITE );
  39. int res=GetExitCodeProcess( pi.hProcess,(DWORD*)&res ) ? res : -1;
  40. CloseHandle( pi.hProcess );
  41. CloseHandle( pi.hThread );
  42. return res;
  43. #elif __APPLE__
  44. #if !TARGET_OS_IPHONE
  45. return system( cmd );
  46. #endif
  47. #else
  48. return system( cmd );
  49. #endif
  50. return -1;
  51. }
  52. int mkdir_( const char *path,int mode ){
  53. #if _WIN32
  54. return mkdir( path );
  55. #else
  56. return mkdir( path,0777 );
  57. #endif
  58. }
  59. int gettimeofday_( timeval *tv ){
  60. #if _MSC_VER
  61. // https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows
  62. // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
  63. // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
  64. // until 00:00:00 January 1, 1970
  65. static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
  66. SYSTEMTIME system_time;
  67. FILETIME file_time;
  68. uint64_t time;
  69. GetSystemTime( &system_time );
  70. SystemTimeToFileTime( &system_time, &file_time );
  71. time = ((uint64_t)file_time.dwLowDateTime ) ;
  72. time += ((uint64_t)file_time.dwHighDateTime) << 32;
  73. tv->tv_sec = (long) ((time - EPOCH) / 10000000L);
  74. tv->tv_usec = (long) (system_time.wMilliseconds * 1000);
  75. return 0;
  76. #else
  77. return gettimeofday( tv,0 );
  78. #endif
  79. }