Пример #1
1
char *gpr_getenv(const char *name) {
  size_t size;
  char *result = NULL;
  errno_t err;

  err = getenv_s(&size, NULL, 0, name);
  if (err || (size == 0)) return NULL;
  result = gpr_malloc(size);
  err = getenv_s(&size, result, size, name);
  if (err) {
    gpr_free(result);
    return NULL;
  }
  return result;
}
Пример #2
0
ExportScene::ExportScene()
: ExportFrame(),
  m_pDCCTransformer( nullptr )
{
    m_Information.ExportTime = _time64( nullptr );
    CHAR strDomain[50];
    size_t BufferSize = ARRAYSIZE(strDomain);
    getenv_s( &BufferSize, strDomain, ARRAYSIZE(strDomain), "USERDOMAIN" );
    CHAR strUsername[50];
    getenv_s( &BufferSize, strUsername, ARRAYSIZE(strUsername), "USERNAME" );
    CHAR strTemp[256];
    sprintf_s( strTemp, "%s\\%s", strDomain, strUsername );
    m_Information.UserName = strTemp;
    CHAR strComputerName[100];
    BufferSize = ARRAYSIZE(strComputerName);
    getenv_s( &BufferSize, strComputerName, ARRAYSIZE(strComputerName), "COMPUTERNAME" );
    m_Information.MachineName = strComputerName;
    OSVERSIONINFO OSVersion = { 0 };
    OSVersion.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
#pragma prefast (disable : 28159)
#pragma warning (suppress : 4996)
    GetVersionEx( &OSVersion );
    sprintf_s( strTemp, "Windows NT %u.%u build %u", OSVersion.dwMajorVersion, OSVersion.dwMinorVersion, OSVersion.dwBuildNumber );
    m_Information.PlatformName = strTemp;
}
Пример #3
0
std::string SysEnv::GetVariable(std::string const& name){
	size_t size;
	getenv_s(&size, nullptr, 0, name.c_str());
	if(size > 0){
		char* tmpvar = new char[size];
		errno_t result = getenv_s(&size, tmpvar, size, name.c_str());
		std::string var = (result == 0 ? std::string(tmpvar) : "");
		delete[] tmpvar;
		return var;
	}
	
	return "";
}
Пример #4
0
std::string EnvironmentVariablesManager::GetOSVariable(const char* name) {
#ifdef WINDOWS
  size_t sz = 0;
  assert(getenv_s(&sz, NULL, 0, name) == 0);
  if (sz == 0) return std::string();
  std::vector<char> value(sz + 1);
  assert(getenv_s(&sz, &value[0], sz, name) == 0);
  return std::string(&value[0], sz - 1);
#else
  const char* const value = std::getenv(name);
  return value ? value : "";
#endif
}
int
setenv(const char *name, const char *value, int overwrite)
{
    int errcode = 0;

    if (!overwrite) {
	size_t envsize = 0;

#ifdef HAVE_GETENV_S
	errcode = getenv_s(&envsize, NULL, 0, name);
#else
	if (getenv(name) == NULL)
	    errcode = EINVAL;
#endif
	if (errcode || envsize)
	    return errcode;
    }
#ifdef HAVE__PUTENV_S
    return _putenv_s(name, value);
#else
    {
	size_t maxlen = strlen(name)+strlen(value)+2;
	char *keyval = (char *)malloc(maxlen);
	if (!keyval)
	    return ENOMEM;
	snprintf(keyval, maxlen, "%s=%s", name, value);
	return putenv(keyval);
    }
#endif
}
Пример #6
0
/****************************************************************************
* GetOwnIP
*
****************************************************************************/
void GetOwnIP() {
	int j;
	size_t aSize;
	struct hostent * pHost;
	WSADATA wsdata;
	WORD wVersionRequested = MAKEWORD( 2, 2 );
	WSAStartup( wVersionRequested, &wsdata );
	char aName[256];
	char *namePtr=&aName[0];
	getenv_s(&aSize,namePtr,256,"COMPUTERNAME");
	CString temp=namePtr;
	temp.MakeLower();
	strcpy_s(applHostName,temp);

	pHost = gethostbyname(applHostName);
	if((pHost!=NULL)&&(pHost->h_addr_list[0]!=NULL)) {
		//original went through al aliases  for( i = 0; pHost!= NULL && pHost->h_addr_list[i]!= NULL; i++ )	{
		CString str,addr;
		for( j = 0; j < pHost->h_length; j++ ){
			if( j > 0 )
				str += ".";
			addr.Format("%u", (unsigned int)((unsigned char*)pHost->h_addr_list[0])[j]);
			str += addr;
		}
		strcpy_s(applHostIP,str);  //Set global variable ownIP
	} else {
		strcpy_s(applHostIP,"127.0.0.1");  //What other option do we have..
		logger(Error,"Failed to obtain Host IP address. Using 127.0.0.1.");
	}

	WSACleanup();

}
Пример #7
0
int git_init()
{
	char path[MAX_PATH+1];
	int ret;
	size_t homesize;

	_fmode = _O_BINARY;
	_setmode(_fileno(stdin), _O_BINARY);
	_setmode(_fileno(stdout), _O_BINARY);
	_setmode(_fileno(stderr), _O_BINARY);

	// set HOME if not set already
	getenv_s(&homesize, NULL, 0, "HOME");
	if (!homesize)
	{
		_wputenv_s(L"HOME", wget_windows_home_directory());
	}
	GetModuleFileName(NULL, path, MAX_PATH);
	convert_slash(path);

	git_extract_argv0_path(path);
	g_prefix = setup_git_directory();
	ret = git_config(git_default_config, NULL);

	if (!homesize)
	{
		_putenv_s("HOME","");/* clear home evironment to avoid affact third part software*/
	}

	return ret;
}
Пример #8
0
 std::string getEnv(const std::string &name)
 {
     char value[MAX_PATH] = "";
     size_t envsize = 0;
     getenv_s(&envsize, value, MAX_PATH, name.c_str());
     return value;
 }
Пример #9
0
void main( void )
{
    char    buffer[128];
    size_t  len;

    if( getenv_s( &len, buffer, sizeof( buffer ), "INCLUDE" ) == 0 )
        printf( "INCLUDE=%s\n", buffer );
}
Пример #10
0
std::string getEnv(const char* envVar)
{
#ifdef _MSC_VER
    size_t requiredSize;
    getenv_s(&requiredSize, nullptr, 0, envVar);
    if (requiredSize == 0)
        return std::string();

    // std::string doesn't need terminating null
    std::string res(requiredSize - 1, 0);
    getenv_s(&requiredSize, &res[0], requiredSize, envVar);
    return res;
#else
    auto res = getenv(envVar);
    return res ? res : std::string();
#endif
}
Пример #11
0
std::string
Broker::Options::getHome() {
    std::string home;
    char home_c[MAX_PATH+1];
    size_t unused;
    if (0 == getenv_s (&unused, home_c, sizeof(home_c), "HOME"))
        home += home_c;
    return home;
}
Пример #12
0
std::string OFXGetEnv( const char* e )
{
	#if !defined( __GNUC__ ) && defined( WINDOWS )
	std::size_t requiredSize;
	getenv_s( &requiredSize, 0, 0, e );
	std::vector<char> buffer( requiredSize );
	if( requiredSize > 0 )
	{
		getenv_s( &requiredSize, &buffer.front(), requiredSize, e );
		return &buffer.front();
	}
	return "";
	#else
	const char* env_value = getenv( e );
	if( env_value == NULL )
		return "";
	return env_value;
	#endif
}
Пример #13
0
bool EnvironmentVariablesManager::IsOSVariableSet(const char* name) {
#ifdef WINDOWS
  size_t sz = 0;
  assert(getenv_s(&sz, NULL, 0, name) == 0);
  return sz > 0;
#else
  const char* value = std::getenv(name);
  return value != NULL && *value != '\0';
#endif
}
Пример #14
0
int setenv(QString name, QString value, bool overwrite)
{
    int errcode = 0;
    if(!overwrite) {
        size_t envsize = 0;
        errcode = getenv_s(&envsize, NULL, 0, name.toLatin1().constData());
        if(errcode || envsize) return errcode;
    }

    // make the update
    return _putenv_s(name.toLatin1().constData(), value.toLatin1().constData());
}
Пример #15
0
int setenv(const char *name, const char *value, int overwrite)
{
        int errorcode = 0;

        if(!overwrite) {
                size_t envsize = 0;
                errorcode = getenv_s(&envsize, NULL, 0, name);
                if(errorcode || envsize)
                        return errorcode;
        }

        return _putenv_s(name, value);
}
Пример #16
0
static void
set_mongoc_test_host(void)
{
#ifdef _MSC_VER
   size_t buflen;

   if (0 != getenv_s (&buflen, MONGOC_TEST_HOST, sizeof MONGOC_TEST_HOST, "MONGOC_TEST_HOST")) {
      bson_strncpy (MONGOC_TEST_HOST, "localhost", sizeof MONGOC_TEST_HOST);
   }
#else
   if (getenv("MONGOC_TEST_HOST")) {
      bson_strncpy (MONGOC_TEST_HOST, getenv("MONGOC_TEST_HOST"), sizeof MONGOC_TEST_HOST);
   } else {
      bson_strncpy (MONGOC_TEST_HOST, "localhost", sizeof MONGOC_TEST_HOST);
   }
#endif
}
Пример #17
0
bool SVNAdminDir::Init()
{
    if (m_nInit==0)
    {
        m_bVSNETHack = false;
        m_pool = svn_pool_create(NULL);
        size_t ret = 0;
        getenv_s(&ret, NULL, 0, "SVN_ASP_DOT_NET_HACK");
        if (ret)
        {
            svn_error_clear(svn_wc_set_adm_dir("_svn", m_pool));
            m_bVSNETHack = true;
        }
    }
    m_nInit++;
    return true;
}
Пример #18
0
// windows has renamed the setenv func to _putenv_s
int setenv(const char *name, const char *value, int overwrite)
{
	if (!overwrite) 
	{
		// see if env var already exists
		size_t envsize = 0;
		int ret = getenv_s(&envsize, NULL, 0, name);
		// if exists, don't overwrite
		if (ret || envsize)
		{
			return ret;
		}
	}

	// set env var
	return _putenv_s(name, value);
}
Пример #19
0
	std::string getenv(const std::string & name)
	{
#ifdef WIN32
		size_t result = 0;

		char buffer[1024];

		if(0 != getenv_s(&result,buffer,sizeof(buffer),name.c_str())) return "";

		return buffer;
#else
		char *val = getenv(varname);

		if(NULL == val) return "";

		return val;
#endif //WIN32
	}
Пример #20
0
/** 获取用户UID */
inline int32 getUserUID()
{
#if KBE_PLATFORM == PLATFORM_WIN32
	// VS2005:
	#if _MSC_VER >= 1400
		char uid[16];
		size_t sz;
		return getenv_s( &sz, uid, sizeof( uid ), "UID" ) == 0 ? atoi( uid ) : 0;

	// VS2003:
	#elif _MSC_VER < 1400
		char * uid = getenv( "UID" );
		return uid ? atoi( uid ) : 0;
	#endif
#else
// Linux:
	char * uid = getenv( "UID" );
	return uid ? atoi( uid ) : getuid();
#endif
}
Пример #21
0
STRING Port::GetEnv(const char * var)
{
	STRING env;
#ifdef WIN32
	size_t tLen = 0;
#ifdef UNICODE
	wchar_t path[80];
	wchar_t var2[256] = {0};
	int size = strlen(var)+1;
	mbstowcs_s(&tLen, var2, size, var, size);
	_wgetenv_s(&tLen, path, 80, var2);
#else
	char path[80];
	getenv_s(&tLen, path, 80, var);
#endif
	env = path;
#elif defined(UNIX)
	char * temp = getenv(var);
	env.assign(temp, temp+strlen(temp));
#endif
	return env;
}
Пример #22
0
// returns the temp directory for the appropriate platform
void GetTempDirectory(string& tempDirectory) {

	const char* MOSAIK_TMP = "MOSAIK_TMP";
	// get hostname
	char hostname[256];
	uint32_t isHostname;
	isHostname = gethostname( hostname, sizeof(hostname) );


#ifdef WIN32

	// allocate the memory needed to store the larger variable
	size_t requiredTmpSize       = 0;
	size_t requiredMosaikTmpSize = 0;

	getenv_s(&requiredTmpSize,       NULL, 0, "TMP");
	getenv_s(&requiredMosaikTmpSize, NULL, 0, MOSAIK_TMP);

	size_t requiredSize = max(requiredTmpSize, requiredMosaikTmpSize);

	char* tmpDir = new char[requiredSize];

	// get the environment variables
	bool foundProblem = false;
	if(requiredMosaikTmpSize != 0) {
		getenv_s(&requiredMosaikTmpSize, tmpDir, requiredMosaikTmpSize, MOSAIK_TMP);
	} 

	getenv_s(&requiredTmpSize,       tmpDir, requiredTmpSize,       "TMP");

	tempDirectory = tmpDir;
	tempDirectory += '\\';

	tempDirectory += "FILEUTIL.";
	if ( isHostname == 0 ) {
		tempDirectory += hostname;
		tempDirectory += '.';
	}

	char pidChar[ 16 ];
	memset( pidChar, 0, sizeof(char) * 16 );
	sprintf( pidChar, "%u", getpid() );
	tempDirectory += pidChar;
	tempDirectory += '\\';

	// checks if a directory exists, creates it otherwise
	CreateDir( tempDirectory.c_str() );


	// clean up
	delete [] tmpDir;
#else
	char* tmpDir = getenv( MOSAIK_TMP );
	if( tmpDir ) {
		tempDirectory = tmpDir;
		if( tempDirectory[ tempDirectory.size() - 1 ] != OS_DIRECTORY_SEPARATOR)
			tempDirectory += OS_DIRECTORY_SEPARATOR;
	} else {
		tempDirectory = "/tmp/";
	}

	tempDirectory += "FILEUTIL.";
	if ( isHostname == 0 ) {
		tempDirectory += hostname;
		tempDirectory += '.';
	}

	char pidChar[ 16 ];
	memset( pidChar, 0, sizeof(char) * 16 );
	sprintf( pidChar, "%u", getpid() );
	tempDirectory += pidChar;
	tempDirectory += OS_DIRECTORY_SEPARATOR;

	// checks if a directory exists, creates it otherwise
	CreateDir( tempDirectory.c_str() );

#endif
}
    static JNIEnv *getNewEnv() {
        
        JNIEnv *env; /* pointer to native method interface */
        JavaVM * jvmBuf[1];
        jsize nVMs;
        char *debugJ4CppEnv = NULL;
        char *classPathEnv = NULL;
        char *jvmOptionsEnv = NULL;
#if defined(_WIN32) || defined(_WIN64)
        errno_t errno_val;
        size_t requiredSize;
        errno_val =  getenv_s( &requiredSize, NULL, 0, "DEBUG_J4CPP");
        if(requiredSize > 0) {
            debugJ4CppEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, debugJ4CppEnv, requiredSize, "DEBUG_J4CPP");
        }
        errno_val =  getenv_s( &requiredSize, NULL, 0, "CLASSPATH");
        if(requiredSize > 0) {
            classPathEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, classPathEnv, requiredSize, "CLASSPATH");
        }
        errno_val =  getenv_s( &requiredSize, NULL, 0, "JVM_OPTIONS");
        if(requiredSize > 0) {
            jvmOptionsEnv = (char *) malloc(requiredSize);
            errno_val =  getenv_s( &requiredSize, jvmOptionsEnv, requiredSize, "JVM_OPTIONS");
        }
#else 
        debugJ4CppEnv = getenv("DEBUG_J4CPP");
        classPathEnv = getenv("CLASSPATH");
        jvmOptionsEnv = getenv("JVM_OPTIONS");
#endif
        debug_j4cpp = debug_j4cpp || (debugJ4CppEnv != NULL && debugJ4CppEnv[0] != 0);
        std::string str;
        str += "%CLASSPATH_PREFIX%";
        if (classPathEnv != NULL) {
            std::string classPathEnvStr(classPathEnv);
            if (debug_j4cpp) std::cout << "classPathEnv=" << classPathEnvStr << std::endl;
            str += "%PATH_SEPERATOR%";
            str += classPathEnvStr;
        }
        if (debug_j4cpp) std::cout << "str=" << str << std::endl;
#if defined(_WIN32) || defined(_WIN64)
        _putenv_s("CLASSPATH", str.c_str());
#else
        setenv("CLASSPATH", str.c_str(), 1);
#endif
        std::string optsString;
        optsString += "-Djava.class.path=";
        optsString += str;
        if (jvmOptionsEnv != NULL) {
            std::string jvmOptionsEnvStr(jvmOptionsEnv);
            if (debug_j4cpp) std::cout << "jvmOptionsEnvStr=" << jvmOptionsEnvStr << std::endl;
            optsString += " ";
            optsString += jvmOptionsEnvStr;
        }
        if (debug_j4cpp) std::cout << "optsString=" << optsString << std::endl;
        jint v = JNI_GetCreatedJavaVMs(jvmBuf, 1, &nVMs);
        if (nVMs > 0) {
            jvm = jvmBuf[0];
            jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
            return env;
        }
        JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
        JavaVMOption* options = new JavaVMOption[1];
        options[0].optionString = (char *) optsString.c_str();
        vm_args.version = JNI_VERSION_1_6;
        vm_args.nOptions = NULL != options[0].optionString ? 1 : 0;
        vm_args.options = options;
        vm_args.ignoreUnrecognized = false;
        /* load and initialize a Java VM, return a JNI interface
         * pointer in env */
        JNI_CreateJavaVM(&jvm,
                ((void **) (&env)),
                ((void *) (&vm_args)));
        delete options;
#if defined(_WIN32) || defined(_WIN64)
        if(debugJ4CppEnv != NULL) {
            free(debugJ4CppEnv);
            debugJ4CppEnv = NULL;
        }
        if(classPathEnv != NULL) {
            free(classPathEnv);
            classPathEnv = NULL;
        }
        if(jvmOptionsEnv != NULL) {
            free(jvmOptionsEnv);
            jvmOptionsEnv = NULL;
        }
#endif
        registerNativeMethods(env);
//        static JNINativeMethod methods[1];
//        jclass loaderclass = env->FindClass("java/lang/ClassLoader");
//        std::cout << "loaderclass = " << loaderclass << std::endl;
//        jmethodID mid = env->GetStaticMethodID(loaderclass,"getSystemClassLoader","()Ljava/lang/ClassLoader;");
//        std::cout << "mid = " << mid << std::endl;
//        jobject loader = env->CallStaticObjectMethod(loaderclass,mid);
//        std::cout << "loader = " << loader << std::endl;
//        jclass rn_clss = env->FindClass("NativeRunnable");
//        std::cout << "rn_clss = " << rn_clss << std::endl;
//        if(NULL != rn_clss) {
//            methods[0].name = (char *) "run";
//            methods[0].signature = (char *) "()V";
//            methods[0].fnPtr = (void *) Java_NativeRunnable_run;
//            jint rn_ret = env->RegisterNatives(rn_clss,methods,1);
//            std::cout << "rn_ret = " << rn_ret << std::endl;
//        }
        return env;
    }
Пример #24
0
std::vector<EkayaKeyboard*>
KmflKeyboardFactory::loadKeyboards(const char * installPath)
{
	std::vector<EkayaKeyboard*> keyboards;
    MessageLogger::logMessage("Loading keyboards\n");
	char* appDir = NULL;
    size_t requiredSize;
	
    getenv_s( &requiredSize, NULL, 0, "APPDATA");
	appDir = new char[requiredSize];
	if (!appDir)
		return keyboards;
	std::string basePath;
	std::string pattern;
	if (appDir)
	{
		getenv_s( &requiredSize, appDir, requiredSize, "APPDATA" );
		basePath = std::string(appDir) + THANLWINSOFT_KMFL_DIR;
		pattern = basePath + KMFL_PATTERN;
	}
	else
	{
		return keyboards;
	}
	HANDLE hFind = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATAA ffd;

	// read files in user's APPDATA dir
	hFind = FindFirstFileA(pattern.c_str(), &ffd);
	while (INVALID_HANDLE_VALUE != hFind)
	{
        std::string kmflFileName = basePath + ffd.cFileName;
        MessageLogger::logMessage("Loading %s\n", kmflFileName.c_str());
		int kmflId = kmfl_load_keyboard((kmflFileName).c_str());
		if (kmflId > -1)
		{
			keyboards.push_back(new KmflKeyboard(kmflId, basePath, ffd.cFileName));
		}
        else
        {
            MessageLogger::logMessage("Failed to load %s\n", kmflFileName.c_str());
        }
		if (FindNextFileA(hFind, &ffd) == 0) break;
	}
	delete [] appDir;
    appDir = NULL;
	// read files under Program Files
    if (installPath == NULL)
    {
	    getenv_s( &requiredSize, NULL, 0, "ProgramFiles");
	    appDir = new char[requiredSize];
	    if (!appDir)
		    return keyboards;
    	getenv_s( &requiredSize, appDir, requiredSize, "ProgramFiles" );
        basePath = std::string(appDir) + THANLWINSOFT_KMFL_DIR;
    }
    else
    {
        basePath = std::string(installPath) + KMFL_DIR;
    }
	pattern = basePath + KMFL_PATTERN;
	hFind = FindFirstFileA(pattern.c_str(), &ffd);
	while (INVALID_HANDLE_VALUE != hFind)
	{
        std::string kmflFileName = basePath + ffd.cFileName;
        MessageLogger::logMessage("Loading %s\n", kmflFileName.c_str());
		int kmflId = kmfl_load_keyboard(kmflFileName.c_str());
		if (kmflId > -1)
		{
			keyboards.push_back(new KmflKeyboard(kmflId, basePath, ffd.cFileName));
		}
        else
        {
            MessageLogger::logMessage("Failed to load %s\n", kmflFileName.c_str());
        }
		if (FindNextFileA(hFind, &ffd) == 0) break;
	}
    if (installPath == NULL)
    {
	    delete [] appDir;
    }
    MessageLogger::logMessage("Loaded %d keyboards\n", keyboards.size());
	return keyboards;
}
Пример #25
0
/*
 * getopt_internal --
 *	Parse argc/argv argument vector.  Called by user level routines.
 */
static int
getopt_internal(int nargc, char * const *nargv, const char *options,
	const struct option *long_options, int *idx, int flags)
{
	char *oli;				/* option letter list index */
	int optchar, short_too;
	static int posixly_correct = -1;

	if (options == NULL)
		return (-1);

	/*
	 * XXX Some GNU programs (like cvs) set optind to 0 instead of
	 * XXX using optreset.  Work around this braindamage.
	 */
	if (optind == 0)
		optind = optreset = 1;

	/*
	 * Disable GNU extensions if POSIXLY_CORRECT is set or options
	 * string begins with a '+'.
	 *
	 * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or
	 *                 optreset != 0 for GNU compatibility.
	 */
	if (posixly_correct == -1 || optreset != 0) {
#ifdef _MSC_VER
		size_t requiredSize;

		getenv_s(&requiredSize, NULL, 0, "POSIXLY_CORRECT");
		posixly_correct = requiredSize > 0;
#else
		posixly_correct = (getenv("POSIXLY_CORRECT") != NULL);
#endif
	}
	if (*options == '-')
		flags |= FLAG_ALLARGS;
	else if (posixly_correct || *options == '+')
		flags &= ~FLAG_PERMUTE;
	if (*options == '+' || *options == '-')
		options++;

	optarg = NULL;
	if (optreset)
		nonopt_start = nonopt_end = -1;
start:
	if (optreset || !*place) {		/* update scanning pointer */
		optreset = 0;
		if (optind >= nargc) {          /* end of argument vector */
			place = EMSG;
			if (nonopt_end != -1) {
				/* do permutation, if we have to */
				permute_args(nonopt_start, nonopt_end,
				    optind, nargv);
				optind -= nonopt_end - nonopt_start;
			}
			else if (nonopt_start != -1) {
				/*
				 * If we skipped non-options, set optind
				 * to the first of them.
				 */
				optind = nonopt_start;
			}
			nonopt_start = nonopt_end = -1;
			return (-1);
		}
		if (*(place = nargv[optind]) != '-' ||
		    (place[1] == '\0' && strchr(options, '-') == NULL)) {
			place = EMSG;		/* found non-option */
			if (flags & FLAG_ALLARGS) {
				/*
				 * GNU extension:
				 * return non-option as argument to option 1
				 */
				optarg = nargv[optind++];
				return (INORDER);
			}
			if (!(flags & FLAG_PERMUTE)) {
				/*
				 * If no permutation wanted, stop parsing
				 * at first non-option.
				 */
				return (-1);
			}
			/* do permutation */
			if (nonopt_start == -1)
				nonopt_start = optind;
			else if (nonopt_end != -1) {
				permute_args(nonopt_start, nonopt_end,
				    optind, nargv);
				nonopt_start = optind -
				    (nonopt_end - nonopt_start);
				nonopt_end = -1;
			}
			optind++;
			/* process next argument */
			goto start;
		}
		if (nonopt_start != -1 && nonopt_end == -1)
			nonopt_end = optind;

		/*
		 * If we have "-" do nothing, if "--" we are done.
		 */
		if (place[1] != '\0' && *++place == '-' && place[1] == '\0') {
			optind++;
			place = EMSG;
			/*
			 * We found an option (--), so if we skipped
			 * non-options, we have to permute.
			 */
			if (nonopt_end != -1) {
				permute_args(nonopt_start, nonopt_end,
				    optind, nargv);
				optind -= nonopt_end - nonopt_start;
			}
			nonopt_start = nonopt_end = -1;
			return (-1);
		}
	}

	/*
	 * Check long options if:
	 *  1) we were passed some
	 *  2) the arg is not just "-"
	 *  3) either the arg starts with -- we are getopt_long_only()
	 */
	if (long_options != NULL && place != nargv[optind] &&
	    (*place == '-' || (flags & FLAG_LONGONLY))) {
		short_too = 0;
		if (*place == '-')
			place++;		/* --foo long option */
		else if (*place != ':' && strchr(options, *place) != NULL)
			short_too = 1;		/* could be short option too */

		optchar = parse_long_options(nargv, options, long_options,
		    idx, short_too);
		if (optchar != -1) {
			place = EMSG;
			return (optchar);
		}
	}

	if ((optchar = (int)*place++) == (int)':' ||
	    (optchar == (int)'-' && *place != '\0') ||
	    (oli = strchr(options, optchar)) == NULL) {
		/*
		 * If the user specified "-" and  '-' isn't listed in
		 * options, return -1 (non-option) as per POSIX.
		 * Otherwise, it is an unknown option character (or ':').
		 */
		if (optchar == (int)'-' && *place == '\0')
			return (-1);
		if (!*place)
			++optind;
		if (PRINT_ERROR)
			warnx(illoptchar, optchar);
		optopt = optchar;
		return (BADCH);
	}
	if (long_options != NULL && optchar == 'W' && oli[1] == ';') {
		/* -W long-option */
		if (*place)			/* no space */
			/* NOTHING */;
		else if (++optind >= nargc) {	/* no arg */
			place = EMSG;
			if (PRINT_ERROR)
				warnx(recargchar, optchar);
			optopt = optchar;
			return (BADARG);
		} else				/* white space */
			place = nargv[optind];
		optchar = parse_long_options(nargv, options, long_options,
		    idx, 0);
		place = EMSG;
		return (optchar);
	}
	if (*++oli != ':') {			/* doesn't take argument */
		if (!*place)
			++optind;
	} else {				/* takes (optional) argument */
		optarg = NULL;
		if (*place)			/* no white space */
			optarg = place;
		else if (oli[1] != ':') {	/* arg not optional */
			if (++optind >= nargc) {	/* no arg */
				place = EMSG;
				if (PRINT_ERROR)
					warnx(recargchar, optchar);
				optopt = optchar;
				return (BADARG);
			} else
				optarg = nargv[optind];
		}
		place = EMSG;
		++optind;
	}
	/* dump back option letter */
	return (optchar);
}
Пример #26
0
LLBC_String LLBC_Directory::HomeDir()
{
#if LLBC_TARGET_PLATFORM_WIN32
    size_t requiredSize = 0;
    if (getenv_s(&requiredSize, NULL, 0, "HOMEPATH") != 0)
    {
        LLBC_SetLastError(LLBC_ERROR_CLIB);
        return LLBC_String();
    }
    else if (requiredSize == 0)
    {
        LLBC_SetLastError(LLBC_ERROR_NOT_FOUND);
        return LLBC_String();
    }

    char *envVal = LLBC_Malloc(char, requiredSize);
    if (getenv_s(&requiredSize, envVal, requiredSize, "HOMEPATH") != 0)
    {
        LLBC_Free(envVal);
        LLBC_SetLastError(LLBC_ERROR_CLIB);
        return LLBC_String();
    }

    LLBC_String path(envVal);
    LLBC_Free(envVal);
#else // Non-Win32
    char *envVal = getenv("HOME");
    if (!envVal)
    {
        LLBC_SetLastError(LLBC_ERROR_NOT_FOUND);
        return "";
    }
    const LLBC_String path(envVal);
#endif // Win32

#if LLBC_TARGET_PLATFORM_WIN32
    const size_t pathLen = path.length();
    if (path[pathLen - 1] == LLBC_SLASH_A ||
        path[pathLen - 1] == LLBC_BACKLASH_A)
    {
        if (pathLen == 3 &&
            LLBC_String::isalpha(path[0]) &&
            path[1] == ':')
            return path;
        else
            return path.substr(0, pathLen - 1);
    }
    else
    {
        return path;
    }
#else // Non-Win32
    const size_t pathLen = path.length();
    if (path[pathLen - 1] == LLBC_SLASH_A)
    {
        if (pathLen == 1)
            return path;
        else
            return path.substr(0, path.length() -1);
    }
    else
    {
        return path;
    }
#endif // Win32
}
Пример #27
0
CDrvrGlobal::CDrvrGlobal() : gOdbcMsg(DRVRMSG_DLL)
{
	OSVERSIONINFO		VersionInformation;
	void				*pVersionInfo;
	VS_FIXEDFILEINFO	*pInfo;
	UINT				wInfoLen;
	DWORD				dwVersionInfoSz;
	DWORD				hFile;
	unsigned long		len;

	WORD* langInfo;
    UINT cbLang;
	TCHAR tszVerStrName[128];
	LPVOID lpt;

	InitializeCriticalSection(&gCSObject);
	InitializeCriticalSection(&gHandleCSObject);
	InitializeCriticalSection(&gCollectionCSObject);
	strcpy(gCapsuleName, "TRAF ODBC Driver");
	len = sizeof(gComputerName);
	if (GetComputerName(gComputerName, &len) == 0)
		strcpy(gComputerName, "UNKNOWN");
	gProcessId = GetCurrentProcessId();

	//referer to the enum cnv_charset in csconvert.h
	//TranslateOption <4bytes from charset,4 bytes to charset>
	gUTF8_To_UTF16_TranslateOption = ((DWORD)0x00010002L);
	gUTF16_To_UTF8_TranslateOption = ((DWORD)0x00020001L);

	VersionInformation.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
	if (GetVersionEx( &VersionInformation ) == 0)
	{
		gPlatformId = 0;
		gMinorVersion = 0;
	}
	else
	{
		gPlatformId = VersionInformation.dwPlatformId;
		gMinorVersion = VersionInformation.dwMinorVersion;
	}

	gClientVersion.componentId = 0; // Unknown
	strcpy(gDriverDLLName, DRIVER_DLL_NAME);
	if ((gModuleHandle = GetModuleHandle(DRIVER_DLL_NAME)) != NULL)
	{
		if (GetModuleFileName(gModuleHandle, gDriverDLLName, sizeof(gDriverDLLName)))
		{
			if ((dwVersionInfoSz = GetFileVersionInfoSize(gDriverDLLName, &hFile)) != 0)
			{
				pVersionInfo = (void *)new char[dwVersionInfoSz];
				if (GetFileVersionInfo(gDriverDLLName, hFile, dwVersionInfoSz, (LPVOID)pVersionInfo)
					&& VerQueryValue((LPVOID)pVersionInfo, "\\",(LPVOID *)&pInfo, &wInfoLen) )
				{
					gClientVersion.componentId = WIN_UNICODE_DRVR_COMPONENT;
					gClientVersion.majorVersion = HIWORD(pInfo->dwProductVersionMS);
					gClientVersion.minorVersion = LOWORD(pInfo->dwProductVersionMS);
					gClientVersion.buildId = LOWORD(pInfo->dwFileVersionLS);
					// Get the vproc in the Comments field
					strncpy(gClientVproc, VprocString, sizeof(gClientVproc)-1);
					gClientVproc[sizeof(gClientVproc)-1] = '\0';
				}
				delete[] pVersionInfo;
			}
		}
	}
	if (gClientVersion.componentId == 0)
	{
		gClientVersion.componentId = DRVR_COMPONENT; 
		gClientVersion.majorVersion = 3;
		gClientVersion.minorVersion = 51;
		gClientVersion.buildId = 0;
	}

	gCEEInitialized = FALSE;
	gCEESyncEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	gCEEExecuteThread = NULL;

	gDefaultTxnIsolation = SQL_TXN_READ_COMMITTED;
	gWaitCursor = LoadCursor(NULL, IDC_WAIT); 
	
	gCEEMessageFilter = TRUE;
	ghWindow = NULL;
    gSpecial_1 = false;

	loadTransportAndTranslateDll();
	SecurityInitialize();
	noSchemaInDSN = false; // Assume that DSN has a schema value
	char envValue[STRICT_SCHEMA_ENV_VAL_SIZE];
	size_t valueSize = STRICT_SCHEMA_ENV_VAL_SIZE ;
	size_t returnLen=0 ;
	RestrictSchema = false;
	if (getenv_s(&returnLen, envValue, valueSize, "TRAFODBC-SQLTABLES-RESTRICT-DSNSCHEMA") == 0) //success
		if(returnLen != 0)
			RestrictSchema = true;
#ifdef TRACE_COMPRESSION                                                                                                            
   char *envTraceCompression=NULL;                                                                                                  
   gTraceCompression=false;                                                                                                         
   if( (envTraceCompression = getenv("TRAFODBC_TRACE_COMPRESSION")) != NULL)
   {                                                                                                                                
      if(strcmp(envTraceCompression,"1")==0)                                                                                        
      {                                                                                                                             
         gTraceCompression=true;                                                                                                    
      }                                                                                                                             
   }                                                                                                                                
#endif

}
Пример #28
0
int _tmain(int argc, _TCHAR* argv[])
{
    // we have three parameters
    const TCHAR * src = NULL;
    const TCHAR * dst = NULL;
    const TCHAR * wc = NULL;
    BOOL bErrOnMods = FALSE;
    BOOL bErrOnUnversioned = FALSE;
    BOOL bErrOnMixed = FALSE;
    BOOL bQuiet = FALSE;
    BOOL bUseSubWCRevIgnore = TRUE;
    SubWCRev_t SubStat;

    SetDllDirectory(L"");
    CCrashReportTSVN crasher(L"SubWCRev " _T(APP_X64_STRING));

    if (argc >= 2 && argc <= 5)
    {
        // WC path is always first argument.
        wc = argv[1];
    }
    if (argc == 4 || argc == 5)
    {
        // SubWCRev Path Tmpl.in Tmpl.out [-params]
        src = argv[2];
        dst = argv[3];
        if (!PathFileExists(src))
        {
            _tprintf(L"File '%s' does not exist\n", src);
            return ERR_FNF;     // file does not exist
        }
    }
    if (argc == 3 || argc == 5)
    {
        // SubWCRev Path -params
        // SubWCRev Path Tmpl.in Tmpl.out -params
        const TCHAR * Params = argv[argc-1];
        if (Params[0] == '-')
        {
            if (wcschr(Params, 'q') != 0)
                bQuiet = TRUE;
            if (wcschr(Params, 'n') != 0)
                bErrOnMods = TRUE;
            if (wcschr(Params, 'N') != 0)
                bErrOnUnversioned = TRUE;
            if (wcschr(Params, 'm') != 0)
                bErrOnMixed = TRUE;
            if (wcschr(Params, 'd') != 0)
            {
                if ((dst != NULL) && PathFileExists(dst))
                {
                    _tprintf(L"File '%s' already exists\n", dst);
                    return ERR_OUT_EXISTS;
                }
            }
            // the 'f' option is useful to keep the revision which is inserted in
            // the file constant, even if there are commits on other branches.
            // For example, if you tag your working copy, then half a year later
            // do a fresh checkout of that tag, the folder in your working copy of
            // that tag will get the HEAD revision of the time you check out (or
            // do an update). The files alone however won't have their last-committed
            // revision changed at all.
            if (wcschr(Params, 'f') != 0)
                SubStat.bFolders = TRUE;
            if (wcschr(Params, 'e') != 0)
                SubStat.bExternals = TRUE;
            if (wcschr(Params, 'E') != 0)
                SubStat.bExternalsNoMixedRevision = TRUE;
            if (wcschr(Params, 'x') != 0)
                SubStat.bHexPlain = TRUE;
            if (wcschr(Params, 'X') != 0)
                SubStat.bHexX = TRUE;
            if (wcschr(Params, 'F') != 0)
                bUseSubWCRevIgnore = FALSE;
        }
        else
        {
            // Bad params - abort and display help.
            wc = NULL;
        }
    }

    if (wc == NULL)
    {
        _tprintf(L"SubWCRev %d.%d.%d, Build %d - %s\n\n",
            TSVN_VERMAJOR, TSVN_VERMINOR,
            TSVN_VERMICRO, TSVN_VERBUILD,
            _T(TSVN_PLATFORM));
        _putts(_T(HelpText1));
        _putts(_T(HelpText2));
        _putts(_T(HelpText3));
        _putts(_T(HelpText4));
        _putts(_T(HelpText5));
        return ERR_SYNTAX;
    }

    DWORD reqLen = GetFullPathName(wc, 0, NULL, NULL);
    auto wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
    GetFullPathName(wc, reqLen, wcfullPath.get(), NULL);
    // GetFullPathName() sometimes returns the full path with the wrong
    // case. This is not a problem on Windows since its filesystem is
    // case-insensitive. But for SVN that's a problem if the wrong case
    // is inside a working copy: the svn wc database is case sensitive.
    // To fix the casing of the path, we use a trick:
    // convert the path to its short form, then back to its long form.
    // That will fix the wrong casing of the path.
    int shortlen = GetShortPathName(wcfullPath.get(), NULL, 0);
    if (shortlen)
    {
        auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
        if (GetShortPathName(wcfullPath.get(), shortPath.get(), shortlen + 1))
        {
            reqLen = GetLongPathName(shortPath.get(), NULL, 0);
            wcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
            GetLongPathName(shortPath.get(), wcfullPath.get(), reqLen);
        }
    }
    wc = wcfullPath.get();
    std::unique_ptr<TCHAR[]> dstfullPath = nullptr;
    if (dst)
    {
        reqLen = GetFullPathName(dst, 0, NULL, NULL);
        dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
        GetFullPathName(dst, reqLen, dstfullPath.get(), NULL);
        shortlen = GetShortPathName(dstfullPath.get(), NULL, 0);
        if (shortlen)
        {
            auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
            if (GetShortPathName(dstfullPath.get(), shortPath.get(), shortlen+1))
            {
                reqLen = GetLongPathName(shortPath.get(), NULL, 0);
                dstfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
                GetLongPathName(shortPath.get(), dstfullPath.get(), reqLen);
            }
        }
        dst = dstfullPath.get();
    }
    std::unique_ptr<TCHAR[]> srcfullPath = nullptr;
    if (src)
    {
        reqLen = GetFullPathName(src, 0, NULL, NULL);
        srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
        GetFullPathName(src, reqLen, srcfullPath.get(), NULL);
        shortlen = GetShortPathName(srcfullPath.get(), NULL, 0);
        if (shortlen)
        {
            auto shortPath = std::make_unique<TCHAR[]>(shortlen + 1);
            if (GetShortPathName(srcfullPath.get(), shortPath.get(), shortlen+1))
            {
                reqLen = GetLongPathName(shortPath.get(), NULL, 0);
                srcfullPath = std::make_unique<TCHAR[]>(reqLen + 1);
                GetLongPathName(shortPath.get(), srcfullPath.get(), reqLen);
            }
        }
        src = srcfullPath.get();
    }

    if (!PathFileExists(wc))
    {
        _tprintf(L"Directory or file '%s' does not exist\n", wc);
        if (wcschr(wc, '\"') != NULL) // dir contains a quotation mark
        {
            _tprintf(L"The WorkingCopyPath contains a quotation mark.\n");
            _tprintf(L"this indicates a problem when calling SubWCRev from an interpreter which treats\n");
            _tprintf(L"a backslash char specially.\n");
            _tprintf(L"Try using double backslashes or insert a dot after the last backslash when\n");
            _tprintf(L"calling SubWCRev\n");
            _tprintf(L"Examples:\n");
            _tprintf(L"SubWCRev \"path to wc\\\\\"\n");
            _tprintf(L"SubWCRev \"path to wc\\.\"\n");
        }
        return ERR_FNF;         // dir does not exist
    }
    std::unique_ptr<char[]> pBuf = nullptr;
    DWORD readlength = 0;
    size_t filelength = 0;
    size_t maxlength  = 0;
    if (dst != NULL)
    {
        // open the file and read the contents
        CAutoFile hFile = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
        if (!hFile)
        {
            _tprintf(L"Unable to open input file '%s'\n", src);
            return ERR_OPEN;        // error opening file
        }
        filelength = GetFileSize(hFile, NULL);
        if (filelength == INVALID_FILE_SIZE)
        {
            _tprintf(L"Could not determine file size of '%s'\n", src);
            return ERR_READ;
        }
        maxlength = filelength+4096;    // We might be increasing file size.
        pBuf = std::make_unique<char[]>(maxlength);
        if (pBuf == NULL)
        {
            _tprintf(L"Could not allocate enough memory!\n");
            return ERR_ALLOC;
        }
        if (!ReadFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, NULL))
        {
            _tprintf(L"Could not read the file '%s'\n", src);
            return ERR_READ;
        }
        if (readlength != filelength)
        {
            _tprintf(L"Could not read the file '%s' to the end!\n", src);
            return ERR_READ;
        }
    }
    // Now check the status of every file in the working copy
    // and gather revision status information in SubStat.

    apr_pool_t * pool;
    svn_error_t * svnerr = NULL;
    svn_client_ctx_t * ctx;
    const char * internalpath;

    apr_initialize();
    svn_dso_initialize2();
    apr_pool_create_ex (&pool, NULL, abort_on_pool_failure, NULL);
    svn_client_create_context2(&ctx, NULL, pool);

    size_t ret = 0;
    getenv_s(&ret, NULL, 0, "SVN_ASP_DOT_NET_HACK");
    if (ret)
    {
        svn_wc_set_adm_dir("_svn", pool);
    }

    char *wc_utf8 = Utf16ToUtf8(wc, pool);
    internalpath = svn_dirent_internal_style (wc_utf8, pool);
    if (bUseSubWCRevIgnore)
    {
        const char *wcroot;
        svnerr = svn_client_get_wc_root(&wcroot, internalpath, ctx, pool, pool);
        if ((svnerr == SVN_NO_ERROR) && wcroot)
            LoadIgnorePatterns(wcroot, &SubStat);
        svn_error_clear(svnerr);
        LoadIgnorePatterns(internalpath, &SubStat);
    }

    svnerr = svn_status(    internalpath,   //path
                            &SubStat,       //status_baton
                            TRUE,           //noignore
                            ctx,
                            pool);

    if (svnerr)
    {
        svn_handle_error2(svnerr, stdout, FALSE, "SubWCRev : ");
    }
    TCHAR wcfullpath[MAX_PATH] = { 0 };
    LPTSTR dummy;
    GetFullPathName(wc, MAX_PATH, wcfullpath, &dummy);
    apr_status_t e = 0;
    if (svnerr)
    {
        e = svnerr->apr_err;
        svn_error_clear(svnerr);
    }
    apr_terminate2();
    if (svnerr)
    {
        if (e == SVN_ERR_WC_NOT_DIRECTORY)
            return ERR_NOWC;
        return ERR_SVN_ERR;
    }

    char wcfull_oem[MAX_PATH] = { 0 };
    CharToOem(wcfullpath, wcfull_oem);
    _tprintf(L"SubWCRev: '%hs'\n", wcfull_oem);


    if (bErrOnMods && SubStat.HasMods)
    {
        _tprintf(L"Working copy has local modifications!\n");
        return ERR_SVN_MODS;
    }
    if (bErrOnUnversioned && SubStat.HasUnversioned)
    {
        _tprintf(L"Working copy has unversioned items!\n");
        return ERR_SVN_UNVER;
    }

    if (bErrOnMixed && (SubStat.MinRev != SubStat.MaxRev))
    {
        if (SubStat.bHexPlain)
            _tprintf(L"Working copy contains mixed revisions %lX:%lX!\n", SubStat.MinRev, SubStat.MaxRev);
        else if (SubStat.bHexX)
            _tprintf(L"Working copy contains mixed revisions %#lX:%#lX!\n", SubStat.MinRev, SubStat.MaxRev);
        else
            _tprintf(L"Working copy contains mixed revisions %ld:%ld!\n", SubStat.MinRev, SubStat.MaxRev);
        return ERR_SVN_MIXED;
    }

    if (!bQuiet)
    {
        if (SubStat.bHexPlain)
            _tprintf(L"Last committed at revision %lX\n", SubStat.CmtRev);
        else if (SubStat.bHexX)
            _tprintf(L"Last committed at revision %#lX\n", SubStat.CmtRev);
        else
            _tprintf(L"Last committed at revision %ld\n", SubStat.CmtRev);

        if (SubStat.MinRev != SubStat.MaxRev)
        {
            if (SubStat.bHexPlain)
                _tprintf(L"Mixed revision range %lX:%lX\n", SubStat.MinRev, SubStat.MaxRev);
            else if (SubStat.bHexX)
                _tprintf(L"Mixed revision range %#lX:%#lX\n", SubStat.MinRev, SubStat.MaxRev);
            else
                _tprintf(L"Mixed revision range %ld:%ld\n", SubStat.MinRev, SubStat.MaxRev);
        }
        else
        {
            if (SubStat.bHexPlain)
                _tprintf(L"Updated to revision %lX\n", SubStat.MaxRev);
            else if (SubStat.bHexX)
                _tprintf(L"Updated to revision %#lX\n", SubStat.MaxRev);
            else
                _tprintf(L"Updated to revision %ld\n", SubStat.MaxRev);
        }

        if (SubStat.HasMods)
        {
            _tprintf(L"Local modifications found\n");
        }

        if (SubStat.HasUnversioned)
        {
            _tprintf(L"Unversioned items found\n");
        }
    }

    if (dst == NULL)
    {
        return 0;
    }

    // now parse the file contents for version defines.

    size_t index = 0;

    while (InsertRevision(VERDEF, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFAND, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFAND), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFOFFSET1, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFOFFSET1), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(VERDEFOFFSET2, pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(VERDEFOFFSET2), (wchar_t*)pBuf.get(), index, filelength, maxlength, -1, SubStat.CmtRev, &SubStat));

    index = 0;
    while (InsertRevision(RANGEDEF, pBuf.get(), index, filelength, maxlength, SubStat.MinRev, SubStat.MaxRev, &SubStat));
    index = 0;
    while (InsertRevisionW(TEXT(RANGEDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.MinRev, SubStat.MaxRev, &SubStat));

    index = 0;
    while (InsertDate(DATEDEF, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(DATEDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(DATEWFMTDEF, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDate(DATEWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));
    index = 0;
    while (InsertDateW(TEXT(DATEWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.CmtDate));

    index = 0;
    while (InsertDate(NOWDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWWFMTDEF, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertDate(NOWWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));
    index = 0;
    while (InsertDateW(TEXT(NOWWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, USE_TIME_NOW));

    index = 0;
    while (InsertBoolean(MODDEF, pBuf.get(), index, filelength, SubStat.HasMods));
    index = 0;
    while (InsertBooleanW(TEXT(MODDEF), (wchar_t*)pBuf.get(), index, filelength, SubStat.HasMods));

    index = 0;
    while (InsertBoolean(UNVERDEF, pBuf.get(), index, filelength, SubStat.HasUnversioned));
    index = 0;
    while (InsertBooleanW(TEXT(UNVERDEF), (wchar_t*)pBuf.get(), index, filelength, SubStat.HasUnversioned));

    index = 0;
    while (InsertBoolean(MIXEDDEF, pBuf.get(), index, filelength, (SubStat.MinRev != SubStat.MaxRev) || SubStat.bIsExternalMixed));
    index = 0;
    while (InsertBooleanW(TEXT(MIXEDDEF), (wchar_t*)pBuf.get(), index, filelength, (SubStat.MinRev != SubStat.MaxRev) || SubStat.bIsExternalMixed));

    index = 0;
    while (InsertBoolean(EXTALLFIXED, pBuf.get(), index, filelength, !SubStat.bIsExternalsNotFixed));
    index = 0;
    while (InsertBooleanW(TEXT(EXTALLFIXED), (wchar_t*)pBuf.get(), index, filelength, !SubStat.bIsExternalsNotFixed));

    index = 0;
    while (InsertBoolean(ISTAGGED, pBuf.get(), index, filelength, SubStat.bIsTagged));
    index = 0;
    while (InsertBooleanW(TEXT(ISTAGGED), (wchar_t*)pBuf.get(), index, filelength, SubStat.bIsTagged));

    index = 0;
    while (InsertUrl(URLDEF, pBuf.get(), index, filelength, maxlength, SubStat.Url));
    index = 0;
    while (InsertUrlW(TEXT(URLDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.Url).c_str()));

    index = 0;
    while (InsertBoolean(ISINSVN, pBuf.get(), index, filelength, SubStat.bIsSvnItem));
    index = 0;
    while (InsertBooleanW(TEXT(ISINSVN), (wchar_t*)pBuf.get(), index, filelength, SubStat.bIsSvnItem));

    index = 0;
    while (InsertBoolean(NEEDSLOCK, pBuf.get(), index, filelength, SubStat.LockData.NeedsLocks));
    index = 0;
    while (InsertBooleanW(TEXT(NEEDSLOCK), (wchar_t*)pBuf.get(), index, filelength, SubStat.LockData.NeedsLocks));

    index = 0;
    while (InsertBoolean(ISLOCKED, pBuf.get(), index, filelength, SubStat.LockData.IsLocked));
    index = 0;
    while (InsertBooleanW(TEXT(ISLOCKED), (wchar_t*)pBuf.get(), index, filelength, SubStat.LockData.IsLocked));

    index = 0;
    while (InsertDate(LOCKDATE, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKDATE), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKDATEUTC, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKDATEUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKWFMTDEF, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKWFMTDEF), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertDate(LOCKWFMTDEFUTC, pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));
    index = 0;
    while (InsertDateW(TEXT(LOCKWFMTDEFUTC), (wchar_t*)pBuf.get(), index, filelength, maxlength, SubStat.LockData.CreationDate));

    index = 0;
    while (InsertUrl(LOCKOWNER, pBuf.get(), index, filelength, maxlength, SubStat.LockData.Owner));
    index = 0;
    while (InsertUrlW(TEXT(LOCKOWNER), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.LockData.Owner).c_str()));

    index = 0;
    while (InsertUrl(LOCKCOMMENT, pBuf.get(), index, filelength, maxlength, SubStat.LockData.Comment));
    index = 0;
    while (InsertUrlW(TEXT(LOCKCOMMENT), (wchar_t*)pBuf.get(), index, filelength, maxlength, Utf8ToWide(SubStat.LockData.Comment).c_str()));

    CAutoFile hFile = CreateFile(dst, GENERIC_WRITE|GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, NULL, NULL);
    if (!hFile)
    {
        _tprintf(L"Unable to open output file '%s' for writing\n", dst);
        return ERR_OPEN;
    }

    size_t filelengthExisting = GetFileSize(hFile, NULL);
    BOOL sameFileContent = FALSE;
    if (filelength == filelengthExisting)
    {
        DWORD readlengthExisting = 0;
        auto pBufExisting = std::make_unique<char[]>(filelength);
        if (!ReadFile(hFile, pBufExisting.get(), (DWORD)filelengthExisting, &readlengthExisting, NULL))
        {
            _tprintf(L"Could not read the file '%s'\n", dst);
            return ERR_READ;
        }
        if (readlengthExisting != filelengthExisting)
        {
            _tprintf(L"Could not read the file '%s' to the end!\n", dst);
            return ERR_READ;
        }
        sameFileContent = (memcmp(pBuf.get(), pBufExisting.get(), filelength) == 0);
    }

    // The file is only written if its contents would change.
    // this object prevents the timestamp from changing.
    if (!sameFileContent)
    {
        SetFilePointer(hFile, 0, NULL, FILE_BEGIN);

        WriteFile(hFile, pBuf.get(), (DWORD)filelength, &readlength, NULL);
        if (readlength != filelength)
        {
            _tprintf(L"Could not write the file '%s' to the end!\n", dst);
            return ERR_READ;
        }

        if (!SetEndOfFile(hFile))
        {
            _tprintf(L"Could not truncate the file '%s' to the end!\n", dst);
            return ERR_READ;
        }
    }

    return 0;
}