Example #1
0
// ---
BOOL CAvpFileFindW::FindFile(LPCWSTR pstrName /* = NULL */,	DWORD dwUnused /* = 0 */) {
	Close();
	m_pNextInfo = new WIN32_FIND_DATAW;
	m_bGotLast = FALSE;

	if (pstrName == NULL)
		pstrName = L"*.*";
/*
	if ( (wcslen(pstrName) + 1) > _countof(((WIN32_FIND_DATAW*) m_pNextInfo)->cFileName) )
		// Это ошибка, конечно. В этом случае мы все равно ничего не найдем. Но, наверное, нужно выполнять
		// поиск с переходом в каталог
		return FALSE;

	wcscpy(((WIN32_FIND_DATAW*) m_pNextInfo)->cFileName, pstrName);
*/
#if defined(_UNICODE)
	m_hContext = ::FindFirstFile(pstrName, (WIN32_FIND_DATAW*) m_pNextInfo);
#else
	if ( g_bUnicodePlatform )
		m_hContext = ::FindFirstFileW(pstrName, (WIN32_FIND_DATAW*) m_pNextInfo);
	else {
		WIN32_FIND_DATAA rcContext;
		//::WContext2AContext( (WIN32_FIND_DATAW*) m_pNextInfo, &rcContext );
		CAPointer<char> pConverted = ::UnicodeToMbcs( pstrName );
		m_hContext = ::FindFirstFileA( pConverted, &rcContext );
		::AContext2WContext( &rcContext, (WIN32_FIND_DATAW*) m_pNextInfo );
	}
#endif

	if (m_hContext == INVALID_HANDLE_VALUE)	{
		DWORD dwTemp = ::GetLastError();
		Close();
		::SetLastError(dwTemp);
		return FALSE;
	}

#if 0 // Dont use this technique - \\?\ problem
	LPWSTR pstrRoot = m_strRoot;
	LPCWSTR pstr = NULL;
#if defined(_UNICODE)
	pstr = _tfullpath(pstrRoot, pstrName, _countof(m_strRoot));
#else
	if ( g_bUnicodePlatform )
		pstr = _wfullpath(pstrRoot, pstrName, _countof(m_strRoot));
	else {
		CAPointer<char> pConverted = ::UnicodeToMbcs( pstrName );
		CHAR strRoot[_MAX_PATH];
		LPCSTR pAStr = _fullpath(strRoot, pConverted, _countof(strRoot));
		if ( pAStr ) {
			::MbcsToUnicode( strRoot, pstrRoot, _countof(m_strRoot) );
			pstr = pstrRoot;
		}
	}
#endif

	// passed name isn't a valid path but was found by the API
	if (pstr == NULL)	{
		Close();
		::SetLastError(ERROR_INVALID_NAME);
		return FALSE;
	}
	else {
		// find the last forward or backward whack
		LPWSTR pstrBack  = wcsrchr(pstrRoot, L'\\');
		LPWSTR pstrFront = wcsrchr(pstrRoot, L'/');

		if (pstrFront != NULL || pstrBack != NULL) {
			if (pstrFront == NULL)
				pstrFront = pstrRoot;
			if (pstrBack == NULL)
				pstrBack = pstrRoot;

			// from the start to the last whack is the root

			if (pstrFront >= pstrBack)
				*pstrFront = L'\0';
			else
				*pstrBack = L'\0';
		}
	}
#endif
	return TRUE;
}
Example #2
0
/*
 * Helper function for search_path
 */
static wchar_t* search_path_join_test(const wchar_t* dir,
                                      int dir_len,
                                      const wchar_t* name,
                                      int name_len,
                                      const wchar_t* ext,
                                      int ext_len,
                                      const wchar_t* cwd,
                                      int cwd_len) {
  wchar_t *result, *result_pos;
  DWORD attrs;

  if (dir_len >= 1 && (dir[0] == L'/' || dir[0] == L'\\')) {
    /* It's a full path without drive letter, use cwd's drive letter only */
    cwd_len = 2;
  } else if (dir_len >= 2 && dir[1] == L':' &&
      (dir_len < 3 || (dir[2] != L'/' && dir[2] != L'\\'))) {
    /* It's a relative path with drive letter (ext.g. D:../some/file)
     * Replace drive letter in dir by full cwd if it points to the same drive,
     * otherwise use the dir only.
     */
    if (cwd_len < 2 || _wcsnicmp(cwd, dir, 2) != 0) {
      cwd_len = 0;
    } else {
      dir += 2;
      dir_len -= 2;
    }
  } else if (dir_len > 2 && dir[1] == L':') {
    /* It's an absolute path with drive letter
     * Don't use the cwd at all
     */
    cwd_len = 0;
  }

  /* Allocate buffer for output */
  result = result_pos =
      (wchar_t*)malloc(sizeof(wchar_t) * (cwd_len + 1 + dir_len + 1 + name_len + 1 + ext_len + 1));

  /* Copy cwd */
  wcsncpy(result_pos, cwd, cwd_len);
  result_pos += cwd_len;

  /* Add a path separator if cwd didn't end with one */
  if (cwd_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
    result_pos[0] = L'\\';
    result_pos++;
  }

  /* Copy dir */
  wcsncpy(result_pos, dir, dir_len);
  result_pos += dir_len;

  /* Add a separator if the dir didn't end with one */
  if (dir_len && wcsrchr(L"\\/:", result_pos[-1]) == NULL) {
    result_pos[0] = L'\\';
    result_pos++;
  }

  /* Copy filename */
  wcsncpy(result_pos, name, name_len);
  result_pos += name_len;

  /* Copy extension */
  if (ext_len) {
    result_pos[0] = L'.';
    result_pos++;
    wcsncpy(result_pos, ext, ext_len);
    result_pos += ext_len;
  }

  /* Null terminator */
  result_pos[0] = L'\0';

  attrs = GetFileAttributesW(result);

  if (attrs != INVALID_FILE_ATTRIBUTES &&
     !(attrs & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) {
    return result;
  }

  free(result);
  return NULL;
}
Example #3
0
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
    // --CHANGED by Anton Likhtarov for resource support
    rs::hInst = hInstance;
    // --END

	WSADATA			wData;
	WORD			wVersion = MAKEWORD(1,1);
    if (dwReason == DLL_PROCESS_ATTACH)
    {
	    if( WSAStartup(wVersion, &wData) )
	    {
		    return FALSE;
	    }

		hMlang = LoadLibrary(L"mlang.dll");
		fConvertINetMultiByteToUnicode = (HRESULT (__stdcall *)(LPDWORD, DWORD, LPCSTR, LPINT, LPWSTR, LPINT))
			GetProcAddress(hMlang, "ConvertINetMultiByteToUnicode");

		HKEY hKeyDB, hKeyCP;
		wchar_t cp_subkey[256], cp_fullpath[256];

		if (RegOpenKeyEx(HKEY_CLASSES_ROOT, L"MIME\\DataBase\\Codepage", 0, KEY_READ, &hKeyDB) == ERROR_SUCCESS) {
			DWORD n_cps;
			RegQueryInfoKey(hKeyDB,NULL,NULL,NULL,&n_cps,NULL,NULL,NULL,NULL,NULL,NULL,NULL);      

			for (int i = 0; i < n_cps; i++) {
				DWORD dwSize = sizeof(cp_subkey);
				RegEnumKeyEx(hKeyDB,i,cp_subkey,&dwSize,NULL,NULL,NULL,NULL);

				UINT cp = _wtoi(cp_subkey);
				
				swprintf(cp_fullpath, L"MIME\\DataBase\\Codepage\\%ls", cp_subkey);
				if (RegOpenKeyEx(HKEY_CLASSES_ROOT, cp_fullpath, 0, KEY_READ, &hKeyCP) != ERROR_SUCCESS)
					continue;
				
				wstring cp_name;
				GetStringRegKey(hKeyCP, L"WebCharset", cp_name);
				if (cp_name.length() == 0)
					GetStringRegKey(hKeyCP, L"BodyCharset", cp_name);
				if (cp_name.length() > 0 && cp_name[0] != L'_') {
					transform(cp_name.begin(), cp_name.end(), cp_name.begin(), ::towlower);
					CPNames[cp] = cp_name;
					CPIDs[cp_name] = cp;
				}
			}

			RegCloseKey(hKeyDB);
		}

		MudCodePage = GetACP();

        InitializeCriticalSection(&secSubstSection);
        InitializeCriticalSection(&secHotkeys);
        InitializeCriticalSection(&secStatusSection);
//vls-begin// #system
        InitializeCriticalSection(&secSystemExec);
        InitializeCriticalSection(&secSystemList);
//vls-end//
//vls-begin// script files
        InitializeCriticalSection(&secScriptFiles);
        InitializeCriticalSection(&secReadingConfig);
        eventReadingConfig = CreateEvent(NULL, TRUE, FALSE, NULL);
        eventReadingHasUse = CreateEvent(NULL, TRUE, FALSE, NULL);
        eventReadingFirst = CreateEvent(NULL, TRUE, FALSE, NULL);
//vls-end//
        eventAllObjectEvent = CreateEvent(NULL, FALSE, FALSE, NULL );
        SetEvent(eventAllObjectEvent );

        eventMudEmuTextArrives = CreateEvent(NULL, TRUE, FALSE, NULL );

//vls-begin// base dir
        GetModuleFileName(NULL, szBASE_DIR, MAX_PATH);
        wchar_t *p = wcsrchr(szBASE_DIR, L'\\');
        if (p) *p = '\0';

        wcscpy(szSETTINGS_DIR, szBASE_DIR);
        wcscat(szSETTINGS_DIR, L"\\settings");
//vls-end//

        _Module.Init(ObjectMap, hInstance, &LIBID_TTCOREEXLib);
        DisableThreadLibraryCalls(hInstance);

		hPingThread = CreateThread(NULL, 0, &PingThread, NULL, 0, &dwPingThreadID);

		strLastCommand[0] = L'\0';

		last_line[0] = L'\0';
    }
    else if (dwReason == DLL_PROCESS_DETACH){
//vls-begin// multiple output
        StopLogging();
//vls-end//
//vls-begin// bugfix
        CloseHandle(eventMudEmuTextArrives);
//vls-end//
//vls-begin// script files
        CloseHandle(eventReadingFirst);
        CloseHandle(eventReadingHasUse);
        CloseHandle(eventReadingConfig);
        DeleteCriticalSection(&secReadingConfig);
        DeleteCriticalSection(&secScriptFiles);
//vls-end//
//vls-begin// #system
        systemkill_command(L"all");
        DeleteCriticalSection(&secSystemList);
        DeleteCriticalSection(&secSystemExec);
//vls-end//

        DeleteCriticalSection(&secSubstSection);
        DeleteCriticalSection(&secHotkeys);
        DeleteCriticalSection(&secStatusSection);
        CloseHandle(eventAllObjectEvent);

#ifdef _DEBUG_LOG
        if ( hExLog ) 
            CloseHandle(hExLog);
#endif
        _Module.Term();
    }
    return TRUE;    // ok
}
Example #4
0
//--------------------------------------------------------------------------------------
// Helper function to try to find the location of a media file
//--------------------------------------------------------------------------------------
HRESULT FindMediaFileCch( WCHAR* strDestPath, int cchDest, LPCWSTR strFilename )
{
    bool bFound = false;

    if( NULL == strFilename || strFilename[0] == 0 || NULL == strDestPath || cchDest < 10 )
        return E_INVALIDARG;

    // Get the exe name, and exe path
    WCHAR strExePath[MAX_PATH] = {0};
    WCHAR strExeName[MAX_PATH] = {0};
    WCHAR* strLastSlash = NULL;
    GetModuleFileName( NULL, strExePath, MAX_PATH );
    strExePath[MAX_PATH - 1] = 0;
    strLastSlash = wcsrchr( strExePath, TEXT( '\\' ) );
    if( strLastSlash )
    {
        StringCchCopy( strExeName, MAX_PATH, &strLastSlash[1] );

        // Chop the exe name from the exe path
        *strLastSlash = 0;

        // Chop the .exe from the exe name
        strLastSlash = wcsrchr( strExeName, TEXT( '.' ) );
        if( strLastSlash )
            *strLastSlash = 0;
    }

    StringCchCopy( strDestPath, cchDest, strFilename );
    if( GetFileAttributes( strDestPath ) != 0xFFFFFFFF )
        return S_OK;

    // Search all parent directories starting at .\ and using strFilename as the leaf name
    WCHAR strLeafName[MAX_PATH] = {0};
    StringCchCopy( strLeafName, MAX_PATH, strFilename );

    WCHAR strFullPath[MAX_PATH] = {0};
    WCHAR strFullFileName[MAX_PATH] = {0};
    WCHAR strSearch[MAX_PATH] = {0};
    WCHAR* strFilePart = NULL;

    GetFullPathName( L".", MAX_PATH, strFullPath, &strFilePart );
    if( strFilePart == NULL )
        return E_FAIL;

    while( strFilePart != NULL && *strFilePart != '\0' )
    {
        StringCchPrintf( strFullFileName, MAX_PATH, L"%s\\%s", strFullPath, strLeafName );
        if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF )
        {
            StringCchCopy( strDestPath, cchDest, strFullFileName );
            bFound = true;
            break;
        }

        StringCchPrintf( strFullFileName, MAX_PATH, L"%s\\%s\\%s", strFullPath, strExeName, strLeafName );
        if( GetFileAttributes( strFullFileName ) != 0xFFFFFFFF )
        {
            StringCchCopy( strDestPath, cchDest, strFullFileName );
            bFound = true;
            break;
        }

        StringCchPrintf( strSearch, MAX_PATH, L"%s\\..", strFullPath );
        GetFullPathName( strSearch, MAX_PATH, strFullPath, &strFilePart );
    }
    if( bFound )
        return S_OK;

    // On failure, return the file as the path but also return an error code
    StringCchCopy( strDestPath, cchDest, strFilename );

    return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );
}
Example #5
0
// Resolve - Creates a nicely formatted rendition of the CallStack, including
//   symbolic information (function names and line numbers) if available. and 
//   saves it for later retrieval. This is almost identical to Callstack::dump above.
//
//   Note: The symbol handler must be initialized prior to calling this
//     function.
//
//  - showInternalFrames (IN): If true, then all frames in the CallStack will be
//      dumped. Otherwise, frames internal to the heap will not be dumped.
//
//  Return Value:
//
//    None.
//
void CallStack::resolve(BOOL showInternalFrames)
{
    if (m_resolved)
    {
        // already resolved, no need to do it again
        // resolving twice may report an incorrect module for the stack frames
        // if the memory was leaked in a dynamic library that was already unloaded.
        return;
    }
    if (m_status & CALLSTACK_STATUS_INCOMPLETE) {
        // This call stack appears to be incomplete. Using StackWalk64 may be
        // more reliable.
        Report(L"    HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n"
            L"      in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n"
            L"      complete stack trace.\n");
    }

    IMAGEHLP_LINE64  sourceInfo = { 0 };
    sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    BYTE symbolBuffer [sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 };
    
    WCHAR callingModuleName [MAX_PATH] = L"";
    WCHAR lowerCaseName [MAX_PATH];

    const size_t max_line_length = MAXREPORTLENGTH + 1;
    m_resolvedCapacity = m_size * max_line_length;
    m_resolved = new WCHAR[m_resolvedCapacity];
    const size_t allocedBytes = m_resolvedCapacity * sizeof(WCHAR);
    ZeroMemory(m_resolved, allocedBytes);
    
    // Iterate through each frame in the call stack.
    for (UINT32 frame = 0; frame < m_size; frame++)
    {
        // Try to get the source file and line number associated with
        // this program counter address.
        SIZE_T programCounter = (*this)[frame];
        g_symbolLock.Enter();
        BOOL             foundline = FALSE;
        DWORD            displacement = 0;

        // It turns out that calls to SymGetLineFromAddrW64 may free the very memory we are scrutinizing here
        // in this method. If this is the case, m_Resolved will be null after SymGetLineFromAddrW64 returns. 
        // When that happens there is nothing we can do except crash.
        DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId());
        foundline = SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo);
        assert(m_resolved != NULL);

        if (foundline && !showInternalFrames) {
            wcscpy_s(lowerCaseName, sourceInfo.FileName);
            _wcslwr_s(lowerCaseName, wcslen(lowerCaseName) + 1);
            if (isInternalModule(lowerCaseName)) {
                // Don't show frames in files internal to the heap.
                g_symbolLock.Leave();
                continue;
            }
        }

        // Initialize structures passed to the symbol handler.
        SYMBOL_INFO* functionInfo = (SYMBOL_INFO*)&symbolBuffer;
        functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
        functionInfo->MaxNameLen = MAX_SYMBOL_NAME_LENGTH;

        // Try to get the name of the function containing this program
        // counter address.
        DWORD64          displacement64 = 0;
        LPWSTR           functionName;
        DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId());
        if (SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo)) {
            functionName = functionInfo->Name;
        }
        else {
            // GetFormattedMessage( GetLastError() );
            functionName = L"(Function name unavailable)";
            displacement64 = 0;
        }
        g_symbolLock.Leave();

        HMODULE hCallingModule = GetCallingModule(programCounter);
        LPWSTR moduleName = L"(Module name unavailable)";
        if (hCallingModule && 
            GetModuleFileName(hCallingModule, callingModuleName, _countof(callingModuleName)) > 0)
        {
            moduleName = wcsrchr(callingModuleName, L'\\');
            if (moduleName == NULL)
                moduleName = wcsrchr(callingModuleName, L'/');
            if (moduleName != NULL)
                moduleName++;
            else
                moduleName = callingModuleName;
        }

        // Use static here to increase performance, and avoid heap allocs. Hopefully this won't
        // prove to be an issue in thread safety. If it does, it will have to be simply non-static.
        static WCHAR stack_line[max_line_length] = L"";
        int NumChars = -1;
        // Display the current stack frame's information.
        if (foundline) {
            // Just truncate anything that is too long.
            if (displacement == 0)
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    %s (%d): %s!%s\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    %s (%d): %s!%s + 0x%X bytes\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName, displacement);
        }
        else {
            if (displacement64 == 0)
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s\n", 
                programCounter, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s + 0x%X bytes\n", 
                programCounter, moduleName, functionName, (DWORD)displacement64);
        }

        if (NumChars >= 0) {
            assert(m_resolved != NULL);
            m_resolvedLength += NumChars;
            wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars);
        }
    } // end for loop
}
Example #6
0
Bool
CodeSet_Init(const char *icuDataDir) // IN: ICU data file location in Current code page.
                                     //     Default is used if NULL.
{
#ifdef NO_ICU
   /* Nothing required if not using ICU. */
   return TRUE;
#else // NO_ICU
   DynBuf dbpath;
#ifdef _WIN32
   DWORD attribs;
   utf16_t *modPath = NULL;
   utf16_t *lastSlash;
   utf16_t *wpath;
   HANDLE hFile = INVALID_HANDLE_VALUE;
   HANDLE hMapping = NULL;
   void *memMappedData = NULL;
#else
   struct stat finfo;
#endif
   char *path = NULL;
   Bool ret = FALSE;

   DynBuf_Init(&dbpath);

#ifdef USE_ICU
   /*
    * We're using system ICU, which finds its own data. So nothing to
    * do here.
    */
   dontUseIcu = FALSE;
   ret = TRUE;
   goto exit;
#endif

  /*
   * ********************* WARNING
   * Must avoid recursive calls into the codeset library here, hence
   * the idiotic hoop-jumping. DO NOT change any of these calls to
   * wrapper equivalents or call any other functions that may perform
   * string conversion.
   * ********************* WARNING
   */

#ifdef _WIN32 // {

#if vmx86_devel && !defined(TEST_CUSTOM_ICU_DATA_FILE)
   /*
    * Devel builds use toolchain directory first.
    */
   {
      WCHAR icuFilePath[MAX_PATH] = { 0 };
      DWORD n = ExpandEnvironmentStringsW(ICU_DATA_FILE_PATH,
                                          icuFilePath, ARRAYSIZE(icuFilePath));
      if (n > 0 && n < ARRAYSIZE(icuFilePath)) {
         attribs = GetFileAttributesW(icuFilePath);
         if ((INVALID_FILE_ATTRIBUTES != attribs) ||
             (attribs & FILE_ATTRIBUTE_DIRECTORY) == 0) {
            if (!CodeSetOld_Utf16leToCurrent((const char *) icuFilePath,
                                             n * sizeof *icuFilePath,
                                             &path, NULL)) {
               goto exit;
            }
            goto found;
         }
      }
   }
#endif

   if (icuDataDir) {
      /*
       * Data file must be in the specified directory.
       */
      size_t length = strlen(icuDataDir);

      if (!DynBuf_Append(&dbpath, icuDataDir, length)) {
         goto exit;
      }
      if (length && icuDataDir[length - 1] != DIRSEPC) {
         if (!DynBuf_Append(&dbpath, DIRSEPS, strlen(DIRSEPS))) {
            goto exit;
         }
      }
      if (!DynBuf_Append(&dbpath, ICU_DATA_FILE, strlen(ICU_DATA_FILE)) ||
          !DynBuf_Append(&dbpath, "\0", 1)) {
         goto exit;
      }

      /*
       * Check for file existence.
       */
      attribs = GetFileAttributesA(DynBuf_Get(&dbpath));

      if ((INVALID_FILE_ATTRIBUTES == attribs) ||
          (attribs & FILE_ATTRIBUTE_DIRECTORY)) {
         goto exit;
      }

      path = (char *) DynBuf_Detach(&dbpath);
   } else {
      /*
       * Data file must be in the directory of the current module
       * (i.e. the module that contains CodeSet_Init()).
       */
      HMODULE hModule = W32Util_GetModuleByAddress((void *) CodeSet_Init);
      if (!hModule) {
         goto exit;
      }

      modPath = CodeSetGetModulePath(hModule);
      if (!modPath) {
         goto exit;
      }

      lastSlash = wcsrchr(modPath, DIRSEPC_W);
      if (!lastSlash) {
         goto exit;
      }

      *lastSlash = L'\0';

      if (!DynBuf_Append(&dbpath, modPath,
                         wcslen(modPath) * sizeof(utf16_t)) ||
          !DynBuf_Append(&dbpath, DIRSEPS_W,
                         wcslen(DIRSEPS_W) * sizeof(utf16_t)) ||
          !DynBuf_Append(&dbpath, ICU_DATA_FILE_W,
                         wcslen(ICU_DATA_FILE_W) * sizeof(utf16_t)) ||
          !DynBuf_Append(&dbpath, L"\0", 2)) {
         goto exit;
      }

      /*
       * Since u_setDataDirectory can't handle UTF-16, we would have to
       * now convert this path to local encoding. But that fails when
       * the module is in a path containing characters not in the
       * local encoding (see 282524). So we'll memory-map the file
       * instead and call udata_setCommonData() below.
       */
      wpath = (utf16_t *) DynBuf_Get(&dbpath);
      hFile = CreateFileW(wpath, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0,
                          NULL);
      if (INVALID_HANDLE_VALUE == hFile) {
         goto exit;
      }
      hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
      if (NULL == hMapping) {
         goto exit;
      }
      memMappedData = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
      if (NULL == memMappedData) {
         goto exit;
      }
   }

#else // } _WIN32 {

#if vmx86_devel && !defined(TEST_CUSTOM_ICU_DATA_FILE)
   {
      char *modPath;
      char *lastSlash;

      /*
       * Devel builds use toolchain directory first.
       */
      if (stat(ICU_DATA_FILE_PATH, &finfo) >= 0 && !S_ISDIR(finfo.st_mode)) {
         if ((path = strdup(ICU_DATA_FILE_PATH)) == NULL) {
            goto exit;
         }
         goto found;
      }

      /*
       * Then we try module directory, if we can get it.
       */
      modPath = CodeSetGetModulePath(HGMP_PRIVILEGE);
      if (modPath) {
         lastSlash = strrchr(modPath, DIRSEPC);
         if (lastSlash) {
            *lastSlash = '\0';

            if (DynBuf_Append(&dbpath, modPath, strlen(modPath)) &&
                DynBuf_Append(&dbpath, DIRSEPS, strlen(DIRSEPS)) &&
                DynBuf_Append(&dbpath, ICU_DATA_FILE,
                              strlen(ICU_DATA_FILE)) &&
                DynBuf_Append(&dbpath, "\0", 1)) {

               if ((stat((const char *) DynBuf_Get(&dbpath), &finfo) >= 0) &&
                   !S_ISDIR(finfo.st_mode)) {
                  free(modPath);
                  path = DynBuf_Detach(&dbpath);
                  goto found;
               } else {
                  DynBuf_SetSize(&dbpath, 0);
               }
            }
         }

         free(modPath);
      }
   }
#endif // vmx86_devel

   if (icuDataDir) {
      /* Use the caller-specified ICU data dir. */
      if (!DynBuf_Append(&dbpath, icuDataDir, strlen(icuDataDir))) {
         goto exit;
      }
   } else {
      /* Use a default ICU data dir. */
#   if defined __APPLE__
      Location_GetLibrary_Type *Location_GetLibrary =
         Location_GetLibrary_Addr();

      if (Location_GetLibrary) {
         char *libDir = Location_GetLibrary();
         Bool success =    libDir
                        && DynBuf_Append(&dbpath, libDir, strlen(libDir));

         free(libDir);
         if (!success) {
            goto exit;
         }
      } else
#   endif

      {
         if (!DynBuf_Append(&dbpath, POSIX_ICU_DIR, strlen(POSIX_ICU_DIR))) {
            goto exit;
         }
      }

      if (!DynBuf_Append(&dbpath, "/icu", strlen("/icu"))) {
         goto exit;
      }
   }
   if (!DynBuf_Append(&dbpath, DIRSEPS, strlen(DIRSEPS)) ||
       !DynBuf_Append(&dbpath, ICU_DATA_FILE, strlen(ICU_DATA_FILE)) ||
       !DynBuf_Append(&dbpath, "\0", 1)) {
      goto exit;
   }

   /*
    * Check for file existence. (DO NOT CHANGE TO 'stat' WRAPPER).
    */
   path = (char *) DynBuf_Detach(&dbpath);
   if (stat(path, &finfo) < 0 || S_ISDIR(finfo.st_mode)) {
      goto exit;
   }

#endif // } _WIN32

#if vmx86_devel && !defined(TEST_CUSTOM_ICU_DATA_FILE)
found:
#endif

#ifdef _WIN32
   if (memMappedData) {
      /*
       * Tell ICU to use this mapped data.
       */
      UErrorCode uerr = U_ZERO_ERROR;
      ASSERT(memMappedData);

      udata_setCommonData(memMappedData, &uerr);
      if (uerr != U_ZERO_ERROR) {
         UnmapViewOfFile(memMappedData);
         goto exit;
      }
      udata_setAppData(ICU_DATA_ITEM, memMappedData, &uerr);
      if (uerr != U_ZERO_ERROR) {
         UnmapViewOfFile(memMappedData);
         goto exit;
      }
   } else {
#endif
      /*
       * Tell ICU to use this directory.
       */
      u_setDataDirectory(path);
#ifdef _WIN32
   }
#endif

   dontUseIcu = FALSE;
   ret = TRUE;

  exit:
   if (!ret) {
      /*
       * There was an error initing ICU, but if we can fall back on
       * non-ICU (old CodeSet) then things are OK.
       */
      if (CODESET_CAN_FALLBACK_ON_NON_ICU) {
         ret = TRUE;
         dontUseIcu = TRUE;

#ifdef _WIN32
         OutputDebugStringW(L"CodeSet_Init: no ICU\n");
#endif
      }
   }

#ifdef _WIN32
   free(modPath);
   if (hMapping) {
      CloseHandle(hMapping);
   }
   if (hFile != INVALID_HANDLE_VALUE) {
      CloseHandle(hFile);
   }
#endif
   free(path);
   DynBuf_Destroy(&dbpath);

   return ret;
#endif
}
/*--------------------------------------------------------------------------*/
char *getScilabDirectory(BOOL UnixStyle)
{
    char *SciPathName = NULL;
    wchar_t* wcSciPathName = NULL;
    wchar_t ScilabModuleName[MAX_PATH + 1];
    wchar_t drive[_MAX_DRIVE];
    wchar_t dir[_MAX_DIR];
    wchar_t fname[_MAX_FNAME];
    wchar_t ext[_MAX_EXT];
    wchar_t *DirTmp = NULL;


    if (!GetModuleFileNameW ((HINSTANCE)GetModuleHandleW(L"core"), (wchar_t*) ScilabModuleName, MAX_PATH))
    {
        return NULL;
    }

    os_wsplitpath(ScilabModuleName, drive, dir, fname, ext);

    if (dir[wcslen(dir) - 1] == L'\\')
    {
        dir[wcslen(dir) - 1] = L'\0';
    }

    DirTmp = wcsrchr (dir, L'\\');

    if (wcslen(dir) - wcslen(DirTmp) > 0)
    {
        dir[wcslen(dir) - wcslen(DirTmp)] = L'\0';
    }
    else
    {
        return NULL;
    }

    wcSciPathName = (wchar_t*)MALLOC((int)( wcslen(drive) + wcslen(dir) + 5) * sizeof(wchar_t));
    if (wcSciPathName)
    {
        _wmakepath(wcSciPathName, drive, dir, NULL, NULL);
        if ( UnixStyle )
        {
            int i = 0;
            for (i = 0; i < (int)wcslen(wcSciPathName); i++)
            {
                if (wcSciPathName[i] == L'\\')
                {
                    wcSciPathName[i] = L'/';
                }
            }
        }
        wcSciPathName[wcslen(wcSciPathName) - 1] = '\0';

        SciPathName = wide_string_to_UTF8(wcSciPathName);
        FREE(wcSciPathName);
        wcSciPathName = NULL;
    }

    if (SciPathName)
    {
        setSCI(SciPathName);
    }

    return SciPathName;
}
Example #8
0
void LoadLangDll()
{
	if (g_langid != g_ShellCache.GetLangID() && (g_langTimeout == 0 || g_langTimeout < GetTickCount64()))
	{
		g_langid = g_ShellCache.GetLangID();
		DWORD langId = g_langid;
		TCHAR langDll[MAX_PATH*4] = {0};
		HINSTANCE hInst = nullptr;
		TCHAR langdir[MAX_PATH] = {0};
		char langdirA[MAX_PATH] = {0};
		if (GetModuleFileName(g_hmodThisDll, langdir, _countof(langdir))==0)
			return;
		if (GetModuleFileNameA(g_hmodThisDll, langdirA, _countof(langdirA))==0)
			return;
		TCHAR* dirpoint = wcsrchr(langdir, L'\\');
		char * dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = L'\0';
		if (dirpointA)
			*dirpointA = '\0';
		dirpoint = wcsrchr(langdir, L'\\');
		dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = L'\0';
		if (dirpointA)
			*dirpointA = '\0';
		strcat_s(langdirA, "\\Languages");

		BOOL bIsWow = FALSE;
		IsWow64Process(GetCurrentProcess(), &bIsWow);

		do
		{
			if (bIsWow)
				swprintf_s(langDll, L"%s\\Languages\\TortoiseProc32%lu.dll", langdir, langId);
			else
				swprintf_s(langDll, L"%s\\Languages\\TortoiseProc%lu.dll", langdir, langId);
			BOOL versionmatch = TRUE;

			struct TRANSARRAY
			{
				WORD wLanguageID;
				WORD wCharacterSet;
			};

			DWORD dwReserved,dwBufferSize;
			dwBufferSize = GetFileVersionInfoSize((LPTSTR)langDll,&dwReserved);

			if (dwBufferSize > 0)
			{
				LPVOID pBuffer = (void*) malloc(dwBufferSize);

				if (pBuffer)
				{
					UINT        nInfoSize = 0;
					UINT        nFixedLength = 0;
					LPSTR       lpVersion = nullptr;
					VOID*       lpFixedPointer;

					if (GetFileVersionInfo((LPTSTR)langDll,
						dwReserved,
						dwBufferSize,
						pBuffer))
					{
						// Query the current language
						if (VerQueryValue(	pBuffer,
							L"\\VarFileInfo\\Translation",
							&lpFixedPointer,
							&nFixedLength))
						{
							auto lpTransArray = reinterpret_cast<TRANSARRAY*>(lpFixedPointer);
							TCHAR strLangProductVersion[MAX_PATH] = { 0 };

							swprintf_s(strLangProductVersion, L"\\StringFileInfo\\%04x%04x\\ProductVersion",
								lpTransArray[0].wLanguageID, lpTransArray[0].wCharacterSet);

							if (VerQueryValue(pBuffer, (LPTSTR)strLangProductVersion, (LPVOID*)&lpVersion, &nInfoSize))
								versionmatch = (wcscmp((LPCTSTR)lpVersion, _T(STRPRODUCTVER)) == 0);

						}
					}
					free(pBuffer);
				} // if (pBuffer)
			} // if (dwBufferSize > 0)
			else
				versionmatch = FALSE;

			if (versionmatch)
				hInst = LoadLibrary(langDll);
			if (hInst)
			{
				if (g_hResInst != g_hmodThisDll)
					FreeLibrary(g_hResInst);
				g_hResInst = hInst;
			}
			else
			{
				DWORD lid = SUBLANGID(langId);
				lid--;
				if (lid > 0)
					langId = MAKELANGID(PRIMARYLANGID(langId), lid);
				else
					langId = 0;
			}
		} while (!hInst && langId != 0);
		if (!hInst)
		{
			// either the dll for the selected language is not present, or
			// it is the wrong version.
			// fall back to English and set a timeout so we don't retry
			// to load the language dll too often
			if (g_hResInst != g_hmodThisDll)
				FreeLibrary(g_hResInst);
			g_hResInst = g_hmodThisDll;
			g_langid = 1033;
			// set a timeout of 10 seconds
			if (g_ShellCache.GetLangID() != 1033)
				g_langTimeout = GetTickCount64() + 10000;
		}
		else
			g_langTimeout = 0;
	} // if (g_langid != g_ShellCache.GetLangID())
}
CNamedHKey::CNamedHKey(
    BSTR          bstrRegFullKeyValueName,
    SPLITKEYVALUE skv /* =KEYANDVALUE */)
    : m_skv(skv)
{
    m_hk = m_hkNonRemote = NULL;
    m_bstrRegFullKeyValueName = bstrRegFullKeyValueName;
    m_ptszComputername = m_ptszKeyname = m_ptszValuename = NULL;
    m_lErr = ERROR_SUCCESS;

    if (bstrRegFullKeyValueName == NULL)
    {
        _Cleanup(ERROR_INVALID_DATA);
        return;
    }

    // check for leading "\\computername\"
    if (bstrRegFullKeyValueName[0] == L'\\'
        &&  bstrRegFullKeyValueName[1] == L'\\')
    {
        BSTR bstrHKey = wcschr(bstrRegFullKeyValueName + 2, L'\\');

        // no '\' terminating computername or zero-length computername?
        if (bstrHKey == NULL  ||  bstrHKey == bstrRegFullKeyValueName + 2)
        {
            _Cleanup(ERROR_INVALID_DATA);
            return;
        }

        m_ptszComputername = TcsNDup(bstrRegFullKeyValueName,
                                     bstrHKey - bstrRegFullKeyValueName);
        if (m_ptszComputername == NULL)
        {
            _Cleanup(ERROR_OUTOFMEMORY);
            return;
        }
        bstrRegFullKeyValueName = bstrHKey + 1;
    }

    // Parse out the leading HKEY_xxx
    if ((m_hkNonRemote = _ParseHKeyRoot(bstrRegFullKeyValueName)) == NULL)
    {
        _Cleanup(ERROR_INVALID_HANDLE);
        return;
    }

    if (m_skv == KEYONLY)
    {
        // do not split into Key\Value pair
        m_ptszKeyname = TcsNDup(bstrRegFullKeyValueName);
        m_ptszValuename = NULL;
    }
    else if (m_skv == KEYANDVALUE)
    {
        // Look for last '\' to split off Valuename
        BSTR bstrValue = wcsrchr(bstrRegFullKeyValueName, L'\\');
        
        // Have name of form "HKLM\foo"; i.e., only one component?
        if (bstrValue == NULL)
        {
            m_ptszKeyname = TcsNDup(OLESTR(""));
            m_ptszValuename = TcsNDup(bstrRegFullKeyValueName);
        }
        else
        {
            m_ptszKeyname = TcsNDup(bstrRegFullKeyValueName,
                                    bstrValue - bstrRegFullKeyValueName);
            m_ptszValuename = TcsNDup(bstrValue + 1);
        }

        if (m_ptszValuename == NULL)
        {
            _Cleanup(ERROR_OUTOFMEMORY);
            return;
        }
    }
    else
    {
        _Cleanup(ERROR_INVALID_DATA);
        return;
    }
    
    if (m_ptszKeyname == NULL)
    {
        _Cleanup(ERROR_OUTOFMEMORY);
        return;
    }

    // Open the key on a remote registry?
    if (m_ptszComputername == NULL)
    {
        m_hk = m_hkNonRemote;
        m_hkNonRemote = NULL;
    }
    else
    {
        m_lErr = ::RegConnectRegistry(m_ptszComputername,
                                      m_hkNonRemote, &m_hk);
        
        if (m_lErr != ERROR_SUCCESS)
            _Cleanup(m_lErr);
    }
    
    // At this point, if m_hk == NULL, there's been an error.
    // Otherwise, m_hk is the key we'll use.
    //   If m_hkNonRemote != NULL, it's one of the predefined
    //     constants, HKEY_CLASSES_ROOT ... HKEY_DYN_DATA
    //     and m_hk refers to a key on a remote registry.
    //   else HKEY_CLASSES_ROOT <= m_hk <= HKEY_DYN_DATA.

    TRACE(_T("computer = `%s', keyname = `%s'\n")
          _T("\tvaluename = `%s', hk = %x, hkNonRemote = %x, ")
          _T("split = %d, err = %x\n"),
          m_ptszComputername, m_ptszKeyname,
          m_ptszValuename, (UINT) m_hk, (UINT) m_hkNonRemote,
          (int) m_skv, m_lErr);
}
Example #10
0
static HRESULT DeleteEmptyDirectory(
    __in LEGACY_FILE_TYPE fileType,
    __in_z LPCWSTR wzPath
    )
{
    HRESULT hr = S_OK;

    LPWSTR sczParentDirectory = NULL;
    DWORD dwIndex = 0;
    LPWSTR pwcLastBackslash = NULL;

    // If it's an individual file and it exists, no point trying to delete any directories for it
    if (LEGACY_FILE_PLAIN == fileType)
    {
        if (FileExistsEx(wzPath, NULL))
        {
            ExitFunction1(hr = S_OK);
        }
    }
    else
    {
        // It's a directory, so delete children first
        hr = DeleteEmptyDirectoryChildren(wzPath);
        // This code is just an FYI that the directory was not empty and so wasn't deleted. It's not an error, so ignore it.
        if (FAILED(hr))
        {
            ExitFunction1(hr = S_OK);
        }
        ExitOnFailure(hr, "Failed to check for empty directories and delete them at path: %ls", wzPath);
    }

    hr = StrAllocString(&sczParentDirectory, wzPath, 0);
    ExitOnFailure(hr, "Failed to allocate copy of directory");

    // Eliminate any trailing backslashes from the directory first, if there are any
    dwIndex = lstrlenW(sczParentDirectory);
    if (0 == dwIndex)
    {
        hr = E_INVALIDARG;
        ExitOnFailure(hr, "Unexpected empty parent directory encountered while deleting empty directories");
    }

    --dwIndex; // Start at the last character of the string
    while (dwIndex > 0 && sczParentDirectory[dwIndex] == L'\\')
    {
        sczParentDirectory[dwIndex] = L'\0';
        --dwIndex;
    }

    if (0 == dwIndex)
    {
        hr = E_INVALIDARG;
        ExitOnFailure(hr, "Parent directory was entirely composed of backslashes!");
    }

    // Now delete any empty parent directories we see as well
    while (NULL != (pwcLastBackslash = wcsrchr(sczParentDirectory, L'\\')))
    {
        hr = DirEnsureDelete(sczParentDirectory, FALSE, FALSE);
        if (FAILED(hr))
        {
            LogErrorString(hr, "Failed to check for empty parent directories and delete them at directory: %ls", sczParentDirectory);
            hr = S_OK;
            break;
        }

        *pwcLastBackslash = L'\0';
    }

LExit:
    ReleaseStr(sczParentDirectory);

    return hr;
}
Example #11
0
HRESULT ConfigParser::SetOutputFile(const WCHAR* outputFile, const WCHAR* openMode)
{
    // If present, replace the {PID} token with the process ID
    const WCHAR* pidStr = nullptr;
    WCHAR buffer[_MAX_PATH];
    if ((pidStr = wcsstr(outputFile, L"{PID}")) != nullptr)
    {
        size_t pidStartPosition = pidStr - outputFile;

        WCHAR* pDest = buffer;
        size_t bufferLen = _MAX_PATH;

        // Copy the filename before the {PID} token
        wcsncpy_s(pDest, bufferLen, outputFile, pidStartPosition);
        pDest += pidStartPosition;
        bufferLen = bufferLen - pidStartPosition;

        // Copy the PID
        _ultow_s(GetCurrentProcessId(), pDest, /*bufferSize=*/_MAX_PATH - pidStartPosition, /*radix=*/10);
#pragma prefast(suppress: 26014, "ultow string length is smaller than 256")
        pDest += wcslen(pDest);
        bufferLen = bufferLen - wcslen(pDest);

        // Copy the rest of the string.
#pragma prefast(suppress: 26014, "Overwriting pDset's null terminator is intentional since the string being copied is null terminated")
        wcscpy_s(pDest, bufferLen, outputFile + pidStartPosition + /*length of {PID}*/ 5);

        outputFile = buffer;
    }

    wchar_t fileName[_MAX_PATH];
    wchar_t moduleName[_MAX_PATH];
    GetModuleFileName(0, moduleName, _MAX_PATH);
    _wsplitpath_s(moduleName, nullptr, 0, nullptr, 0, fileName, _MAX_PATH, nullptr, 0);
    if (_wcsicmp(fileName, L"WWAHost") == 0 || _wcsicmp(fileName, L"ByteCodeGenerator") == 0 ||
        _wcsicmp(fileName, L"spartan") == 0 || _wcsicmp(fileName, L"spartan_edge") == 0 ||
        _wcsicmp(fileName, L"MicrosoftEdge") == 0 || _wcsicmp(fileName, L"MicrosoftEdgeCP") == 0)
    {

        // we need to output to %temp% directory in wwa. we don't have permission otherwise.
        if (GetEnvironmentVariable(L"temp", fileName, _MAX_PATH) != 0)
        {
            wcscat_s(fileName, _MAX_PATH, L"\\");
            const wchar_t * fileNameOnly = wcsrchr(outputFile, L'\\');
            // if outputFile is full path we just need filename, discard the path
            wcscat_s(fileName, _MAX_PATH, fileNameOnly == nullptr ? outputFile : fileNameOnly);
        }
        else
        {
            AssertMsg(FALSE, "Get temp environment failed");
        }
        outputFile = fileName;
    }

    FILE *fp;
    if ((fp = _wfsopen(outputFile, openMode, _SH_DENYWR)) != nullptr)
    {
        Output::SetOutputFile(fp);
        return S_OK;
    }

    AssertMsg(false, "Could not open file for logging output.");
    return E_FAIL;
}
Example #12
0
static HRESULT DeleteEmptyRegistryKeys(
    __in LEGACY_SYNC_PRODUCT_SESSION *pSyncProductSession
    )
{
    HRESULT hr = S_OK;
    const LEGACY_REGISTRY_KEY *rgRegKeys = pSyncProductSession->product.rgRegKeys;
    const DWORD cRegKeys = pSyncProductSession->product.cRegKeys;
    DWORD dwIndex = 0;
    LPWSTR pwcLastBackslash = NULL;
    LPWSTR sczParentKey = NULL;

    for (DWORD i = 0; i < cRegKeys; ++i)
    {
        hr = DeleteEmptyRegistryKeyChildren(rgRegKeys[i].dwRoot, rgRegKeys[i].sczKey);
        // This code is just an FYI that the key was not empty and so wasn't deleted. It's not an error, so ignore it.
        if (HRESULT_FROM_WIN32(ERROR_DIR_NOT_EMPTY) == hr)
        {
            hr = S_OK;
            continue;
        }
        ExitOnFailure(hr, "Failed to check for empty keys and delete them at root: %u, subkey: %ls", rgRegKeys[i].dwRoot, rgRegKeys[i].sczKey);

        hr = StrAllocString(&sczParentKey, rgRegKeys[i].sczKey, 0);
        ExitOnFailure(hr, "Failed to allocate copy of subkey");

        // Eliminate any trailing backslashes from the key first, if there are any
        dwIndex = lstrlenW(sczParentKey);
        if (0 == dwIndex)
        {
            hr = E_INVALIDARG;
            ExitOnFailure(hr, "Unexpected empty parent key encountered while deleting empty registry keys");
        }

        --dwIndex; // Start at the last character of the string
        while (dwIndex > 0 && sczParentKey[dwIndex] == L'\\')
        {
            sczParentKey[dwIndex] = L'\0';
            --dwIndex;
        }

        if (0 == dwIndex)
        {
            hr = E_INVALIDARG;
            ExitOnFailure(hr, "Parent key was entirely composed of backslashes!");
        }

        // Now delete any empty parent keys we see as well
        while (NULL != (pwcLastBackslash = wcsrchr(sczParentKey, L'\\')))
        {
            hr = RegDelete(ManifestConvertToRootKey(rgRegKeys[i].dwRoot), sczParentKey, REG_KEY_DEFAULT, FALSE);
            // This code is just an FYI that the key was not empty and so wasn't deleted. It's not an error, so ignore it.
            if (FAILED(hr))
            {
                LogErrorString(hr, "Failed to check for empty parent keys and delete them at root: %u, subkey: %ls", rgRegKeys[i].dwRoot, sczParentKey);
                hr = S_OK;
                break;
            }

            *pwcLastBackslash = L'\0';
        }
    }

LExit:
    ReleaseStr(sczParentKey);

    return hr;
}
Example #13
0
static
NTSTATUS
OpenRegistryHandlesFromSymbolicLink(IN PUNICODE_STRING SymbolicLinkName,
                                    IN ACCESS_MASK DesiredAccess,
                                    IN OPTIONAL PHANDLE GuidKey,
                                    IN OPTIONAL PHANDLE DeviceKey,
                                    IN OPTIONAL PHANDLE InstanceKey)
{
    OBJECT_ATTRIBUTES ObjectAttributes;
    WCHAR PathBuffer[MAX_PATH];
    UNICODE_STRING BaseKeyU;
    UNICODE_STRING GuidString, SubKeyName, ReferenceString;
    PWCHAR StartPosition, EndPosition;
    HANDLE ClassesKey;
    PHANDLE GuidKeyRealP, DeviceKeyRealP, InstanceKeyRealP;
    HANDLE GuidKeyReal, DeviceKeyReal, InstanceKeyReal;
    NTSTATUS Status;

    SubKeyName.Buffer = NULL;

    if (GuidKey != NULL)
        GuidKeyRealP = GuidKey;
    else
        GuidKeyRealP = &GuidKeyReal;

    if (DeviceKey != NULL)
        DeviceKeyRealP = DeviceKey;
    else
        DeviceKeyRealP = &DeviceKeyReal;

    if (InstanceKey != NULL)
        InstanceKeyRealP = InstanceKey;
    else
        InstanceKeyRealP = &InstanceKeyReal;

    *GuidKeyRealP = INVALID_HANDLE_VALUE;
    *DeviceKeyRealP = INVALID_HANDLE_VALUE;
    *InstanceKeyRealP = INVALID_HANDLE_VALUE;

    BaseKeyU.Buffer = PathBuffer;
    BaseKeyU.Length = 0;
    BaseKeyU.MaximumLength = MAX_PATH * sizeof(WCHAR);

    RtlAppendUnicodeToString(&BaseKeyU, BaseKeyString);

    /* Open the DeviceClasses key */
    InitializeObjectAttributes(&ObjectAttributes,
                               &BaseKeyU,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               NULL,
                               NULL);
    Status = ZwOpenKey(&ClassesKey,
                       DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ\n", &BaseKeyU);
        goto cleanup;
    }

    StartPosition = wcschr(SymbolicLinkName->Buffer, L'{');
    EndPosition = wcschr(SymbolicLinkName->Buffer, L'}');
    if (!StartPosition || !EndPosition || StartPosition > EndPosition)
    {
        DPRINT1("Bad symbolic link: %wZ\n", SymbolicLinkName);
        return STATUS_INVALID_PARAMETER_1;
    }
    GuidString.Buffer = StartPosition;
    GuidString.MaximumLength = GuidString.Length = (USHORT)((ULONG_PTR)(EndPosition + 1) - (ULONG_PTR)StartPosition);

    InitializeObjectAttributes(&ObjectAttributes,
                               &GuidString,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               ClassesKey,
                               NULL);
    Status = ZwOpenKey(GuidKeyRealP,
                       DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                       &ObjectAttributes);
    ZwClose(ClassesKey);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ (%x)\n", &BaseKeyU, &GuidString, Status);
        goto cleanup;
    }

    SubKeyName.MaximumLength = SymbolicLinkName->Length + sizeof(WCHAR);
    SubKeyName.Length = 0;
    SubKeyName.Buffer = ExAllocatePool(PagedPool, SubKeyName.MaximumLength);
    if (!SubKeyName.Buffer)
    {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto cleanup;
    }

    RtlAppendUnicodeStringToString(&SubKeyName,
                                   SymbolicLinkName);

    SubKeyName.Buffer[SubKeyName.Length / sizeof(WCHAR)] = UNICODE_NULL;

    SubKeyName.Buffer[0] = L'#';
    SubKeyName.Buffer[1] = L'#';
    SubKeyName.Buffer[2] = L'?';
    SubKeyName.Buffer[3] = L'#';

    ReferenceString.Buffer = wcsrchr(SubKeyName.Buffer, '\\');
    if (ReferenceString.Buffer != NULL)
    {
        ReferenceString.Buffer[0] = L'#';

        SubKeyName.Length = (USHORT)((ULONG_PTR)(ReferenceString.Buffer) - (ULONG_PTR)SubKeyName.Buffer);
        ReferenceString.Length = SymbolicLinkName->Length - SubKeyName.Length;
    }
    else
    {
        RtlInitUnicodeString(&ReferenceString, L"#");
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &SubKeyName,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               *GuidKeyRealP,
                               NULL);
    Status = ZwOpenKey(DeviceKeyRealP,
                       DesiredAccess | KEY_ENUMERATE_SUB_KEYS,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ\\%wZ\n", &BaseKeyU, &GuidString, &SubKeyName);
        goto cleanup;
    }

    InitializeObjectAttributes(&ObjectAttributes,
                               &ReferenceString,
                               OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                               *DeviceKeyRealP,
                               NULL);
    Status = ZwOpenKey(InstanceKeyRealP,
                       DesiredAccess,
                       &ObjectAttributes);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Failed to open %wZ%wZ\\%wZ%\\%wZ (%x)\n", &BaseKeyU, &GuidString, &SubKeyName, &ReferenceString, Status);
        goto cleanup;
    }

    Status = STATUS_SUCCESS;

cleanup:
    if (SubKeyName.Buffer != NULL)
       ExFreePool(SubKeyName.Buffer);

    if (NT_SUCCESS(Status))
    {
       if (!GuidKey)
          ZwClose(*GuidKeyRealP);

       if (!DeviceKey)
          ZwClose(*DeviceKeyRealP);

       if (!InstanceKey)
          ZwClose(*InstanceKeyRealP);
    }
    else
    {
       if (*GuidKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*GuidKeyRealP);

       if (*DeviceKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*DeviceKeyRealP);

       if (*InstanceKeyRealP != INVALID_HANDLE_VALUE)
          ZwClose(*InstanceKeyRealP);
    }

    return Status;
}
Example #14
0
DXResourceHandle CDXShaderManager::CreateResource(void* pShaderDesc, WCHAR* szCustomKey)
{
    DXResourceKey key;
    DXResourceMapInsertResult insertResult;
    DXResourceHandle returnValue;
    DXShaderDesc* pDesc;
    CDXShader* pShader;

    pDesc = (DXShaderDesc*)pShaderDesc;
    pShader = nullptr;

    // Custom key given? Well and good. But it's better not to provide a
    // custom key for shaders.
    if (szCustomKey)
    {
        wcscpy_s(key.m_szName, DX_MAX_RESOURCE_KEY_NAME, szCustomKey);
    }
    else // No? Process a key name of format %FILE%_%ENTRY%_%PROFILE%
    {
        WCHAR szFileName[DX_MAX_FILE_NAME];
        WCHAR* pFileName;
        WCHAR* pDot;

        // Find the last slash.
        pFileName = wcsrchr(pDesc->szFileName, '\\');
        // If not found, then only the file name is present.
        if (!pFileName)
        {
            pFileName = pDesc->szFileName;
        }
        // Copy the file name to a local variable.
        wcscpy_s(szFileName, DX_MAX_FILE_NAME, pFileName);
        // Find the extension full stop.
        pDot = wcsrchr(szFileName, '.');
        // We don't need the file extension.
        if (pDot)
        {
            *pDot = 0;
        }

        // Format our key name: %FILE%_%ENTRY%_%PROFILE%
        // So keep file and function names small.
        wsprintf(key.m_szName, L"%s_%s_%s", szFileName, pDesc->szEntryPoint, pDesc->szShaderLevel);
    }

    // Try to insert the shader with the key into the map.
    insertResult = InsertResource(key, pShader);
    if (insertResult.second) // New resource inserted?
    {
        HRESULT hr = S_OK;

        // New shader resource on the heap.
        pShader = new CDXShader();
        // Create the resource. NOTE: This does not create the resource
        // in the graphics memory. It only prepares the resource so that it
        // can be created anytime using Recreate() method.
        DX_V(pShader->Create(pShaderDesc));
        if (FAILED(hr)) // Failed?
        {
            DX_DEBUG_OUTPUT2(L"Failed on a shader: FILE:%s, ENTRY: %s.", pDesc->szFileName, pDesc->szEntryPoint);
            // Free the memory.
            DX_SAFE_DELETE(pShader);
            return returnValue;
        }

        // Success!
        insertResult.first->second = pShader;
        AddMemoryUsage(pShader->GetSize());
    }
    else // Existing element returned.
    {
        pShader = (CDXShader*)insertResult.first->second;
    }

    pShader->AddRef();
    returnValue.key = key;
    returnValue.pResource = pShader;

    return returnValue;
}
Example #15
0
BOOL
CheckThreads (
    __in DWORD ProcId
    )
/*++

Routine Description:

    Enumerates all threads (or optionally only threads for one
    process) in the system.  It the calls the WCT API on each of them.

Arguments:

    ProcId--Specifies the process ID to analyze.  If '0' all processes
        in the system will be checked.

Return Value:

    TRUE if processes could be checked; FALSE if a general failure
    occurred.

--*/
{
    DWORD processes[1024];
    DWORD numProcesses;
    DWORD i;

    // Try to enable the SE_DEBUG_NAME privilege for this process.  We
    // continue even if this fails--we just won't be able to retrieve
    // wait chains for processes not owned by the current user.
    if (!GrantDebugPrivilege())
    {
        printf("Couldn't enable debug privilege");
    }

    // Get a list of all processes currently running.
    if (EnumProcesses(processes, sizeof(processes), &numProcesses) == FALSE)
    {
        printf("Couldn't enumerate processes");
        return FALSE;
    }

    for (i = 0; i < numProcesses / sizeof(DWORD); i++)
    {
        HANDLE process;
        HANDLE snapshot;

        if (processes[i] == GetCurrentProcessId())
        {
            continue;
        }

        // If the caller specified a Process ID, check if we have a match.
        if (ProcId != 0)
        {
            if (processes[i] != ProcId)
            {
                continue;
            }
        }

        // Get a handle to this process.
        process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processes[i]);
        if (process)
        {
            WCHAR file[MAX_PATH];

            printf("Process 0x%x - ", processes[i]);

            // Retrieve the EXE's name and print it.
            if (GetProcessImageFileName(process, file, ARRAYSIZE(file)) > 0)
            {
                PCWSTR filePart = wcsrchr(file, L'\\');
                if (filePart)
                {
                    filePart++;
                }
                else
                {
                    filePart = file;
                }

                printf("%S", filePart);
            }

            printf("\n----------------------------------\n");

            // Get a snapshot of this process.  This allows us to
            // enumerate its threads.
            snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD,
                                                processes[i]);
            if (snapshot)
            {
                THREADENTRY32 thread;
                thread.dwSize = sizeof(thread);

                // Walk the thread list and print the wait chain
                // for each.
                if (Thread32First(snapshot, &thread))
                {
                    do
                    {
                        if (thread.th32OwnerProcessID == processes[i])
                        {
                            // Open a handle to this specific thread,...
                            HANDLE threadHandle = OpenThread(THREAD_ALL_ACCESS,
                                                             FALSE,
                                                             thread.th32ThreadID);
                            if (threadHandle)
                            {
                                // ...check if it is still running,...
                                DWORD exitCode;
                                GetExitCodeThread(threadHandle, &exitCode);

                                if (exitCode == STILL_ACTIVE)
                                {
                                    // ...and print its wait chain.
                                    PrintWaitChain(thread.th32ThreadID);
                                }

                                CloseHandle(threadHandle);
                            }
                        }
                    } while (Thread32Next(snapshot, &thread));
                }
                CloseHandle(snapshot);
            }

            CloseHandle(process);
            printf("\n");
        }
    }
    return TRUE;
}
Example #16
0
static bool InitDbgHelp()
{
	static bool doinit = true;
	static bool ret = false;

	if(!doinit)
		return ret;

	doinit = false;

	HMODULE module = NULL;
	
	// can't reliably co-exist with dbghelp already being used in the process
	if(GetModuleHandleA("dbghelp.dll") != NULL)
	{
		ret = false;
		return false;
	}
	else
	{
		wchar_t path[MAX_PATH] = {0};
		GetModuleFileNameW(GetModuleHandleA("renderdoc.dll"), path, MAX_PATH-1);

		wchar_t *slash = wcsrchr(path, '\\');

		if(slash)
		{
			*slash = 0;
		}
		else
		{
			slash = wcsrchr(path, '/');

			if(slash == 0)
			{
				ret = false;
				return false;
			}

			*slash = 0;
		}

#if defined(WIN64)
		wcscat_s(path, L"/pdblocate/x64/dbghelp.dll");
#else
		wcscat_s(path, L"/pdblocate/x86/dbghelp.dll");
#endif

		module = LoadLibraryW(path);
	}

	if(!module)
	{
		RDCWARN("Couldn't open dbghelp.dll");
		ret = false;
		return false;
	}

	dynSymInitializeW = (PSYMINITIALIZEW)GetProcAddress(module, "SymInitializeW");
	dynSymEnumerateModules64W = (PSYMENUMERATEMODULES64W)GetProcAddress(module, "SymEnumerateModulesW64");
	dynSymGetModuleInfo64W = (PSYMGETMODULEINFO64W)GetProcAddress(module, "SymGetModuleInfoW64");
	
	if(!dynSymInitializeW ||
		!dynSymEnumerateModules64W ||
		!dynSymGetModuleInfo64W)
	{
		RDCERR("Couldn't get some dbghelp function");
		ret = false;
		return ret;
	}

	dynSymInitializeW(GetCurrentProcess(), L".", TRUE);
	
	HMODULE hModule = NULL;
	GetModuleHandleEx(
		GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
		(LPCTSTR)&dllLocator,
		&hModule);

	if(hModule != NULL)
	{
		MODULEINFO modinfo = { 0 };

		BOOL result = GetModuleInformation(GetCurrentProcess(), hModule, &modinfo, sizeof(modinfo));

		if(result != FALSE)
		{
			renderdocBase = modinfo.lpBaseOfDll;
			renderdocSize = modinfo.SizeOfImage;
		}
	}
		 
	ret = true;
	return ret;
}
Example #17
0
NTSTATUS Log_Rotate()
{
	NTSTATUS Status = STATUS_SUCCESS;
	HANDLE hFile = NULL;
	OBJECT_ATTRIBUTES fAttrs;
	UNICODE_STRING FileName;
	IO_STATUS_BLOCK StatusBlock = { 0 };
	ULONG RotateIndex = 0;
	FILE_RENAME_INFORMATION *RenameBuffer = NULL;
	LPCWSTR BaseFileName = LogFileName;
	ULONG BaseFileNameLength = 0;

	if (!LogFileName || !LogFile)
		return STATUS_INVALID_DEVICE_STATE;

	LPWSTR End1 = wcsrchr(LogFileName, L'\\'), End2 = wcsrchr(LogFileName, L'/');
	if ((SIZE_T)End1 > (SIZE_T)End2 > 0)
		BaseFileName = End1 ? End1 + 1 : LogFileName;
	else
		BaseFileName = End2 ? End2 + 1 : LogFileName;
	BaseFileNameLength = (ULONG)(wcslen(BaseFileName) + 4) * sizeof(WCHAR);

	ULONG FileNameLength = (ULONG)(wcslen(LogFileName) + 5) * sizeof(WCHAR);
	RenameBuffer = ExAllocatePoolWithTag(PagedPool, FileNameLength + FIELD_OFFSET(FILE_RENAME_INFORMATION, FileName),
		LogAllocationTag);
	if (!RenameBuffer) {
		Status = STATUS_INSUFFICIENT_RESOURCES;
		goto Cleanup;
	}
	RenameBuffer->FileNameLength = BaseFileNameLength;
	RenameBuffer->ReplaceIfExists = FALSE;
	RenameBuffer->RootDirectory = NULL;

	// Rename already rotated files first
	Status = StringCbPrintf(RenameBuffer->FileName, FileNameLength, L"%ws.%03d", LogFileName, LogSettings.MaxKeptRotatedFiles);
	if (!SUCCEEDED(Status))
		goto Cleanup;
	RtlInitUnicodeString(&FileName, RenameBuffer->FileName);
	InitializeObjectAttributes(&fAttrs, &FileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
	ZwDeleteFile(&fAttrs);

	for (RotateIndex = LogSettings.MaxKeptRotatedFiles - 1; RotateIndex > 0; RotateIndex--)
	{
		Status = StringCbPrintf(RenameBuffer->FileName, FileNameLength, L"%ws.%03d", LogFileName, RotateIndex);
		if (!SUCCEEDED(Status))
			goto Cleanup;
		RtlInitUnicodeString(&FileName, RenameBuffer->FileName);
		InitializeObjectAttributes(&fAttrs, &FileName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, NULL);
		Status = ZwOpenFile(&hFile, DELETE, &fAttrs, &StatusBlock, 0, 0);
		if (!NT_SUCCESS(Status))
			continue;

		Status = StringCbPrintf(RenameBuffer->FileName, FileNameLength, L"%ws.%03d", BaseFileName, RotateIndex + 1);
		if (!SUCCEEDED(Status))
			goto Cleanup;
		Status = ZwSetInformationFile(hFile, &StatusBlock, RenameBuffer, FileNameLength + FIELD_OFFSET(FILE_RENAME_INFORMATION, FileName),
			FileRenameInformation);
		if (!NT_SUCCESS(Status))
			goto Cleanup;

		ZwClose(hFile);
		hFile = NULL;
	}

	// Rename it
	Status = StringCbPrintf(RenameBuffer->FileName, FileNameLength, L"%ws.%03d", BaseFileName, 1);
	if (!SUCCEEDED(Status))
		goto Cleanup;

	// Compress
	Status = Log_CompressFile(LogFile);

	Status = ZwSetInformationFile(LogFile, &StatusBlock, RenameBuffer, FileNameLength + FIELD_OFFSET(FILE_RENAME_INFORMATION, FileName),
		FileRenameInformation);
	if (!NT_SUCCESS(Status))
		goto Cleanup;

	// And start logging into the new file
	ZwClose(LogFile);
	LogFile = NULL;
	Status = Log_StartFileLogging(LogFileName);

Cleanup:
	if (hFile)
		ZwClose(hFile);
	if (RenameBuffer)
		ExFreePoolWithTag(RenameBuffer, LogAllocationTag);
	
	return Status;
}
Example #18
0
VOID
GetVersionInfo(
    BOOL Verbose
    )
{
    WCHAR          NameBuffer[MAXVERSIONBUFFER];
    WCHAR          Title1[128];
    WCHAR          Title2[128];
    WCHAR          wszPID[MAXVERSIONSTRING];
    WCHAR          wszPro[MAXVERSIONSTRING];
    WCHAR          wszSrv[MAXVERSIONSTRING];
    WCHAR          wszPBuild[MAXVERSIONSTRING];
    WCHAR          wszEvaluation[MAXVERSIONSTRING];
    UNICODE_STRING UserBuildString;
    UNICODE_STRING UserTypeString;
    UNICODE_STRING UserCSDString;
    NTSTATUS       Status;


    RTL_QUERY_REGISTRY_TABLE BaseServerRegistryConfigurationTable[] = {

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CurrentBuildNumber",
         &UserBuildString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CurrentType",
         &UserTypeString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         RTL_QUERY_REGISTRY_DIRECT,
         L"CSDVersion",
         &UserCSDString,
         REG_NONE,
         NULL,
         0},

        {NULL,
         0,
         NULL,
         NULL,
         REG_NONE,
         NULL,
         0}
    };

    UserBuildString.Buffer          = &NameBuffer[OFFSET_BLDSTRING];
    UserBuildString.Length          = 0;
    UserBuildString.MaximumLength   = MAXVERSIONSTRING * sizeof(WCHAR);

    UserTypeString.Buffer           = &NameBuffer[OFFSET_TYPSTRING];
    UserTypeString.Length           = 0;
    UserTypeString.MaximumLength    = MAXVERSIONSTRING * sizeof(WCHAR);

    UserCSDString.Buffer            = &NameBuffer[OFFSET_CSDSTRING];
    UserCSDString.Length            = 0;
    UserCSDString.MaximumLength     = MAXVERSIONSTRING * sizeof(WCHAR);

    Status = RtlQueryRegistryValues(RTL_REGISTRY_WINDOWS_NT,
                                    L"",
                                    BaseServerRegistryConfigurationTable,
                                    NULL,
                                    NULL);

    if (!NT_SUCCESS(Status)) {
        RIPMSG1(RIP_WARNING, "GetVersionInfo failed with status %x", Status);
        return;
    }

    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTID, wszPID, ARRAY_SIZE(wszPID) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTPRO, wszPro, ARRAY_SIZE(wszPro) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTSRV, wszSrv, ARRAY_SIZE(wszSrv) );
    ServerLoadString( hModuleWin, STR_DTBS_PRODUCTBUILD, wszPBuild, ARRAY_SIZE(wszPBuild) );

    /*
     * Write out Debugging Version message.
     */

    /*
     * Bug 280256 - joejo
     * Create new desktop build information strings
     */
    swprintf(
        wszProductName,
        wszPID,
        ((USER_SHARED_DATA->NtProductType == NtProductWinNt) ? wszPro : wszSrv)
        );

    
    if (gfUnsignedDrivers) {
        /* This takes precedence */
        ServerLoadString( hModuleWin, STR_TESTINGONLY, wszEvaluation, ARRAY_SIZE(wszEvaluation) );
    } else if (USER_SHARED_DATA->SystemExpirationDate.QuadPart) {
        ServerLoadString(hModuleWin, STR_DTBS_EVALUATION, wszEvaluation,
                ARRAY_SIZE(wszEvaluation));
    } else {
        wszEvaluation[0] = '\0';
    }

    swprintf(
        wszProductBuild,
        wszPBuild,
        wszEvaluation,
        UserBuildString.Buffer
        );

    if (Verbose) {

        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE1, Title1, ARRAY_SIZE(Title1) );
        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE2, Title2, ARRAY_SIZE(Title2) );

        swprintf(
            wszT,
            UserCSDString.Length == 0 ? Title1 : Title2,
            UserBuildString.Buffer,
            UserCSDString.Buffer,
            USER_SHARED_DATA->NtSystemRoot
            );

    } else {
        PWSTR s = wcsrchr( UserTypeString.Buffer, L' ' );
        if (s) {
            s += 1;
        } else {
            s = UserTypeString.Buffer;
        }

        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE3, Title1, ARRAY_SIZE(Title1) );
        ServerLoadString( hModuleWin, STR_SAFEMODE_TITLE4, Title2, ARRAY_SIZE(Title2) );

        swprintf(
            wszT,
            UserCSDString.Length == 0 ? Title1 : Title2,
            UserBuildString.Buffer,
            UserCSDString.Buffer,
            s
            );
    }
}
Example #19
0
File: extra.c Project: skyguy94/R
int winAccessW(const wchar_t *path, int mode)
{
    DWORD attr = GetFileAttributesW(path);

    if(attr == 0xffffffff) return -1;
    if(mode == F_OK) return 0;

    if(mode & X_OK)
	if(!(attr & FILE_ATTRIBUTE_DIRECTORY)) { /* Directory, so OK */
	    /* Look at extension for executables */
	    wchar_t *p = wcsrchr(path, '.');
	    if(p == NULL ||
	       !((wcsicmp(p, L".exe") == 0) || (wcsicmp(p, L".com") == 0) ||
		 (wcsicmp(p, L".bat") == 0) || (wcsicmp(p, L".cmd") == 0)) )
		return -1;
	}
    {
	/* Now look for file security info */
	SECURITY_DESCRIPTOR *sdPtr = NULL;
	DWORD size = 0;
	GENERIC_MAPPING genMap;
	HANDLE hToken = NULL;
	DWORD desiredAccess = 0;
	DWORD grantedAccess = 0;
	BOOL accessYesNo = FALSE;
	PRIVILEGE_SET privSet;
	DWORD privSetSize = sizeof(PRIVILEGE_SET);
	int error;

	/* get size */
	GetFileSecurityW(path,
			 OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
			 | DACL_SECURITY_INFORMATION, 0, 0, &size);
	error = GetLastError();
	if (error != ERROR_INSUFFICIENT_BUFFER) return -1;
	sdPtr = (SECURITY_DESCRIPTOR *) alloca(size);
	if(!GetFileSecurityW(path,
			     OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION
			     | DACL_SECURITY_INFORMATION, sdPtr, size, &size))
	    return -1;
	/*
	 * Perform security impersonation of the user and open the
	 * resulting thread token.
	 */
	if(!ImpersonateSelf(SecurityImpersonation)) return -1;
	if(!OpenThreadToken(GetCurrentThread (),
			    TOKEN_DUPLICATE | TOKEN_QUERY, FALSE,
			    &hToken)) return -1;
	if (mode & R_OK) desiredAccess |= FILE_GENERIC_READ;
	if (mode & W_OK) desiredAccess |= FILE_GENERIC_WRITE;
	if (mode & X_OK) desiredAccess |= FILE_GENERIC_EXECUTE;

	memset(&genMap, 0x0, sizeof (GENERIC_MAPPING));
	genMap.GenericRead = FILE_GENERIC_READ;
	genMap.GenericWrite = FILE_GENERIC_WRITE;
	genMap.GenericExecute = FILE_GENERIC_EXECUTE;
	genMap.GenericAll = FILE_ALL_ACCESS;
	if(!AccessCheck(sdPtr, hToken, desiredAccess, &genMap, &privSet,
			&privSetSize, &grantedAccess, &accessYesNo)) {
	    CloseHandle(hToken);
	    return -1;
	}
	CloseHandle(hToken);
	if (!accessYesNo) return -1;

	if ((mode & W_OK)
	    && !(attr & FILE_ATTRIBUTE_DIRECTORY)
	    && (attr & FILE_ATTRIBUTE_READONLY)) return -1;
    }
    return 0;
}
Example #20
0
static BOOL
ViewTree_LoadTree(HKEY hKey, LPCWSTR pszKeyName, DWORD dwParentID)
{
    DWORD dwIndex;
    WCHAR szKeyName[64], szText[MAX_PATH], *pch;
    DWORD Size, Value;
    PVIEWTREE_ENTRY pAllocated;

    // resize s_ViewTreeEntries
    Size = (s_ViewTreeEntryCount + 1) * sizeof(VIEWTREE_ENTRY);
    pAllocated = (PVIEWTREE_ENTRY)realloc(s_ViewTreeEntries, Size);
    if (pAllocated == NULL)
        return FALSE;   // failure
    else
        s_ViewTreeEntries = pAllocated;

    PVIEWTREE_ENTRY pEntry = &s_ViewTreeEntries[s_ViewTreeEntryCount];

    // dwID, dwParentID, szKeyName
    pEntry->dwID = s_ViewTreeEntryCount;
    pEntry->dwParentID = dwParentID;
    lstrcpynW(pEntry->szKeyName, pszKeyName, _countof(pEntry->szKeyName));

    // Text, ResourceID
    pEntry->szText[0] = 0;
    pEntry->dwResourceID = 0;
    szText[0] = 0;
    Size = sizeof(szText);
    RegQueryValueExW(hKey, L"Text", NULL, NULL, LPBYTE(szText), &Size);
    if (szText[0] == L'@')
    {
        pch = wcsrchr(szText, L',');
        if (pch)
        {
            *pch = 0;
            dwIndex = abs(_wtoi(pch + 1));
            pEntry->dwResourceID = dwIndex;
        }
        HINSTANCE hInst = LoadLibraryW(&szText[1]);
        LoadStringW(hInst, dwIndex, szText, _countof(szText));
        FreeLibrary(hInst);
    }
    else
    {
        pEntry->dwResourceID = DWORD(-1);
    }
    lstrcpynW(pEntry->szText, szText, _countof(pEntry->szText));

    // Type
    szText[0] = 0;
    RegQueryValueExW(hKey, L"Type", NULL, NULL, LPBYTE(szText), &Size);
    if (lstrcmpiW(szText, L"checkbox") == 0)
        pEntry->dwType = AETYPE_CHECKBOX;
    else if (lstrcmpiW(szText, L"radio") == 0)
        pEntry->dwType = AETYPE_RADIO;
    else if (lstrcmpiW(szText, L"group") == 0)
        pEntry->dwType = AETYPE_GROUP;
    else
        return FALSE;   // failure

    pEntry->nIconID = -1;
    if (pEntry->dwType == AETYPE_GROUP)
    {
        // Bitmap (Icon)
        UINT nIconIndex = 0;
        Size = sizeof(szText);
        szText[0] = 0;
        RegQueryValueExW(hKey, L"Bitmap", NULL, NULL, LPBYTE(szText), &Size);

        WCHAR szExpanded[MAX_PATH];
        ExpandEnvironmentStringsW(szText, szExpanded, _countof(szExpanded));
        pch = wcsrchr(szExpanded, L',');
        if (pch)
        {
            *pch = 0;
            nIconIndex = abs(_wtoi(pch + 1));
        }
        pEntry->nIconID = ViewTree_AddIcon(szExpanded, nIconIndex);
    }

    if (pEntry->dwType == AETYPE_GROUP)
    {
        pEntry->hkeyRoot = NULL;
        pEntry->szRegPath[0] = 0;
        pEntry->szValueName[0] = 0;
        pEntry->dwCheckedValue = 0;
        pEntry->bHasUncheckedValue = FALSE;
        pEntry->dwUncheckedValue = 0;
        pEntry->dwDefaultValue = 0;
        pEntry->hItem = NULL;
        pEntry->bGrayed = FALSE;
        pEntry->bChecked = FALSE;
    }
    else
    {
        // HKeyRoot
        HKEY HKeyRoot = HKEY_CURRENT_USER;
        Size = sizeof(HKeyRoot);
        RegQueryValueExW(hKey, L"HKeyRoot", NULL, NULL, LPBYTE(&HKeyRoot), &Size);
        pEntry->hkeyRoot = HKeyRoot;

        // RegPath
        pEntry->szRegPath[0] = 0;
        Size = sizeof(szText);
        RegQueryValueExW(hKey, L"RegPath", NULL, NULL, LPBYTE(szText), &Size);
        lstrcpynW(pEntry->szRegPath, szText, _countof(pEntry->szRegPath));

        // ValueName
        pEntry->szValueName[0] = 0;
        Size = sizeof(szText);
        RegQueryValueExW(hKey, L"ValueName", NULL, NULL, LPBYTE(szText), &Size);
        lstrcpynW(pEntry->szValueName, szText, _countof(pEntry->szValueName));

        // CheckedValue
        Size = sizeof(Value);
        Value = 0x00000001;
        RegQueryValueExW(hKey, L"CheckedValue", NULL, NULL, LPBYTE(&Value), &Size);
        pEntry->dwCheckedValue = Value;

        // UncheckedValue
        Size = sizeof(Value);
        Value = 0x00000000;
        pEntry->bHasUncheckedValue = TRUE;
        if (RegQueryValueExW(hKey, L"UncheckedValue", NULL,
                             NULL, LPBYTE(&Value), &Size) != ERROR_SUCCESS)
        {
            pEntry->bHasUncheckedValue = FALSE;
        }
        pEntry->dwUncheckedValue = Value;

        // DefaultValue
        Size = sizeof(Value);
        Value = 0x00000001;
        RegQueryValueExW(hKey, L"DefaultValue", NULL, NULL, LPBYTE(&Value), &Size);
        pEntry->dwDefaultValue = Value;

        // hItem
        pEntry->hItem = NULL;

        // bGrayed, bChecked
        HKEY hkeyTarget;
        Value = pEntry->dwDefaultValue;
        pEntry->bGrayed = TRUE;
        if (RegOpenKeyExW(HKEY(pEntry->hkeyRoot), pEntry->szRegPath, 0,
                          KEY_READ, &hkeyTarget) == ERROR_SUCCESS)
        {
            Size = sizeof(Value);
            if (RegQueryValueExW(hkeyTarget, pEntry->szValueName, NULL, NULL,
                                 LPBYTE(&Value), &Size) == ERROR_SUCCESS)
            {
                pEntry->bGrayed = FALSE;
            }
            RegCloseKey(hkeyTarget);
        }
        pEntry->bChecked = (Value == pEntry->dwCheckedValue);
    }

    // Grayed (ReactOS extension)
    Size = sizeof(Value);
    Value = FALSE;
    RegQueryValueExW(hKey, L"Grayed", NULL, NULL, LPBYTE(&Value), &Size);
    if (!pEntry->bGrayed)
        pEntry->bGrayed = Value;

    BOOL bIsGroup = (pEntry->dwType == AETYPE_GROUP);
    dwParentID = pEntry->dwID;
    ++s_ViewTreeEntryCount;

    if (!bIsGroup)
        return TRUE;    // success

    // load the children
    dwIndex = 0;
    while (RegEnumKeyW(hKey, dwIndex, szKeyName,
                       _countof(szKeyName)) == ERROR_SUCCESS)
    {
        HKEY hkeyChild;
        if (RegOpenKeyExW(hKey, szKeyName, 0, KEY_READ,
                          &hkeyChild) != ERROR_SUCCESS)
        {
            ++dwIndex;
            continue;   // failure
        }

        ViewTree_LoadTree(hkeyChild, szKeyName, dwParentID);
        RegCloseKey(hkeyChild);

        ++dwIndex;
    }

    return TRUE;    // success
}
Example #21
0
static wcstring file_get_desc(const wcstring &filename,
                              int lstat_res,
                              struct stat lbuf,
                              int stat_res,
                              struct stat buf,
                              int err)
{
    const wchar_t *suffix;

    if (!lstat_res)
    {
        if (S_ISLNK(lbuf.st_mode))
        {
            if (!stat_res)
            {
                if (S_ISDIR(buf.st_mode))
                {
                    return COMPLETE_DIRECTORY_SYMLINK_DESC;
                }
                else
                {

                    if ((buf.st_mode & S_IXUSR) ||
                            (buf.st_mode & S_IXGRP) ||
                            (buf.st_mode & S_IXOTH))
                    {

                        if (waccess(filename, X_OK) == 0)
                        {
                            /*
                              Weird group permissions and other such
                              issues make it non-trivial to find out
                              if we can actually execute a file using
                              the result from stat. It is much safer
                              to use the access function, since it
                              tells us exactly what we want to know.
                            */
                            return COMPLETE_EXEC_LINK_DESC;
                        }
                    }
                }

                return COMPLETE_SYMLINK_DESC;

            }
            else
            {
                switch (err)
                {
                    case ENOENT:
                    {
                        return COMPLETE_ROTTEN_SYMLINK_DESC;
                    }

                    case ELOOP:
                    {
                        return COMPLETE_LOOP_SYMLINK_DESC;
                    }
                }
                /*
                  On unknown errors we do nothing. The file will be
                  given the default 'File' description or one based on the suffix.
                */
            }

        }
        else if (S_ISCHR(buf.st_mode))
        {
            return COMPLETE_CHAR_DESC;
        }
        else if (S_ISBLK(buf.st_mode))
        {
            return COMPLETE_BLOCK_DESC;
        }
        else if (S_ISFIFO(buf.st_mode))
        {
            return COMPLETE_FIFO_DESC;
        }
        else if (S_ISSOCK(buf.st_mode))
        {
            return COMPLETE_SOCKET_DESC;
        }
        else if (S_ISDIR(buf.st_mode))
        {
            return COMPLETE_DIRECTORY_DESC;
        }
        else
        {
            if ((buf.st_mode & S_IXUSR) ||
                    (buf.st_mode & S_IXGRP) ||
                    (buf.st_mode & S_IXOTH))
            {

                if (waccess(filename, X_OK) == 0)
                {
                    /*
                      Weird group permissions and other such issues
                      make it non-trivial to find out if we can
                      actually execute a file using the result from
                      stat. It is much safer to use the access
                      function, since it tells us exactly what we want
                      to know.
                    */
                    return COMPLETE_EXEC_DESC;
                }
            }
        }
    }

    suffix = wcsrchr(filename.c_str(), L'.');
    if (suffix != 0 && !wcsrchr(suffix, L'/'))
    {
        return complete_get_desc_suffix(suffix);
    }

    return COMPLETE_FILE_DESC ;
}
Example #22
0
void CDropbox::RequestAccountInfo()
{
	HttpRequest *request = new HttpRequest(hNetlibUser, REQUEST_GET, DROPBOX_API_URL "/account/info");
	request->AddBearerAuthHeader(db_get_sa(NULL, MODULE, "TokenSecret"));
	mir_ptr<NETLIBHTTPREQUEST> response(request->Send());

	delete request;

	MCONTACT hContact = CDropbox::GetDefaultContact();

	if (response && response->resultCode == HTTP_STATUS_OK)
	{
		JSONROOT root(response->pData);
		if (root)
		{
			JSONNODE *node = json_get(root, "referral_link");
			if (node)
			{
				ptrW referral_link = ptrW(json_as_string(node));
				db_set_ws(hContact, MODULE, "Homepage", referral_link);
			}

			node = json_get(root, "display_name");
			if (node)
			{
				ptrW display_name = ptrW(json_as_string(node));
				wchar_t *sep = wcsrchr(display_name, L' ');
				if (sep)
				{
					db_set_ws(hContact, MODULE, "LastName", sep + 1);
					display_name[wcslen(display_name) - wcslen(sep)] = '\0';
					db_set_ws(hContact, MODULE, "FirstName", display_name);
				}
				else
				{
					db_set_ws(hContact, MODULE, "FirstName", display_name);
					db_unset(hContact, MODULE, "LastName");
				}
			}

			node = json_get(root, "country");
			if (node)
			{
				ptrW isocodeW(json_as_string(node));
				ptrA isocode(mir_u2a(isocodeW));

				if (!strlen(isocode))
					db_unset(hContact, MODULE, "Country");
				else
				{
					char *country = (char *)CallService(MS_UTILS_GETCOUNTRYBYISOCODE, (WPARAM)isocode, 0);
					db_set_s(hContact, MODULE, "Country", country);
				}
			}

			node = json_get(root, "quota_info");
			JSONNODE *nroot = json_as_node(node);
			if (nroot)
			{
				node = json_get(nroot, "shared");
				if (node)
					db_set_dw(hContact, MODULE, "SharedQuota", json_as_int(node));
				node = json_get(nroot, "normal");
				if (node)
					db_set_dw(hContact, MODULE, "NormalQuota", json_as_int(node));
				node = json_get(nroot, "quota");
				if (node)
					db_set_dw(hContact, MODULE, "TotalQuota", json_as_int(node));
			}
		}
	}

	HandleHttpResponseError(hNetlibUser, response);
}
Example #23
0
// dump - Dumps a nicely formatted rendition of the CallStack, including
//   symbolic information (function names and line numbers) if available.
//
//   Note: The symbol handler must be initialized prior to calling this
//     function.
//
//  - showinternalframes (IN): If true, then all frames in the CallStack will be
//      dumped. Otherwise, frames internal to the heap will not be dumped.
//
//  Return Value:
//
//    None.
//
void CallStack::dump(BOOL showInternalFrames, UINT start_frame) const
{
    // The stack was dumped already
    if (m_resolved)
    {
        dumpResolved();
        return;
    }

    if (m_status & CALLSTACK_STATUS_INCOMPLETE) {
        // This call stack appears to be incomplete. Using StackWalk64 may be
        // more reliable.
        Report(L"    HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n"
            L"      in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n"
            L"      complete stack trace.\n");
    }

    IMAGEHLP_LINE64  sourceInfo = { 0 };
    sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    BYTE symbolBuffer [sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 };

    WCHAR lowerCaseName [MAX_PATH];
    WCHAR callingModuleName [MAX_PATH];

    const size_t max_size = MAXREPORTLENGTH + 1;

    // Iterate through each frame in the call stack.
    for (UINT32 frame = start_frame; frame < m_size; frame++)
    {
        // Try to get the source file and line number associated with
        // this program counter address.
        SIZE_T programCounter = (*this)[frame];
        g_symbolLock.Enter();
        BOOL             foundline = FALSE;
        DWORD            displacement = 0;
        DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId());
        foundline = SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo);
        if (foundline && !showInternalFrames) {
            wcscpy_s(lowerCaseName, sourceInfo.FileName);
            _wcslwr_s(lowerCaseName, wcslen(lowerCaseName) + 1);
            if (isInternalModule(lowerCaseName)) {
                // Don't show frames in files internal to the heap.
                g_symbolLock.Leave();
                continue;
            }
        }

        // Initialize structures passed to the symbol handler.
        SYMBOL_INFO* functionInfo = (SYMBOL_INFO*)&symbolBuffer;
        functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
        functionInfo->MaxNameLen = MAX_SYMBOL_NAME_LENGTH;

        // Try to get the name of the function containing this program
        // counter address.
        DWORD64          displacement64 = 0;
        LPWSTR           functionName;
        DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId());
        if (SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo)) {
            functionName = functionInfo->Name;
        }
        else {
            // GetFormattedMessage( GetLastError() );
            functionName = L"(Function name unavailable)";
            displacement64 = 0;
        }
        g_symbolLock.Leave();

        HMODULE hCallingModule = GetCallingModule(programCounter);
        LPWSTR moduleName = L"(Module name unavailable)";
        if (hCallingModule && 
            GetModuleFileName(hCallingModule, callingModuleName, _countof(callingModuleName)) > 0)
        {
            moduleName = wcsrchr(callingModuleName, L'\\');
            if (moduleName == NULL)
                moduleName = wcsrchr(callingModuleName, L'/');
            if (moduleName != NULL)
                moduleName++;
            else
                moduleName = callingModuleName;
        }

        // Use static here to increase performance, and avoid heap allocs. Hopefully this won't
        // prove to be an issue in thread safety. If it does, it will have to be simply non-static.
        static WCHAR stack_line[MAXREPORTLENGTH + 1] = L"";
        int NumChars = -1;
        // Display the current stack frame's information.
        if (foundline) {
            if (displacement == 0)
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    %s (%d): %s!%s\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    %s (%d): %s!%s + 0x%X bytes\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName, displacement);
        }
        else {
            if (displacement64 == 0)
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s\n", 
                programCounter, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s + 0x%X bytes\n", 
                programCounter, moduleName, functionName, (DWORD)displacement64);	
        }

        Print(stack_line);
    }
}
Example #24
0
// используется в GUI при загрузке настроек
void FindComspec(ConEmuComspec* pOpt, bool bCmdAlso /*= true*/)
{
	if (!pOpt)
		return;

	pOpt->Comspec32[0] = 0;
	pOpt->Comspec64[0] = 0;

	// Ищем tcc.exe
	if (pOpt->csType == cst_AutoTccCmd)
	{
		HKEY hk;
		BOOL bWin64 = IsWindows64();
		wchar_t szPath[MAX_PATH+1];

		// If tcc.exe can be found near to ConEmu location
		LPCWSTR ppszPredefined[] = {
			L"%ConEmuBaseDir%\\tcc.exe",
			L"%ConEmuDir%\\tcc.exe",
			// Sort of PortableApps locations
			L"%ConEmuDir%\\..\\tcc\\tcc.exe",
			L"%ConEmuDir%\\..\\..\\tcc\\tcc.exe",
			// End of predefined list
			NULL};
		for (INT_PTR i = 0; ppszPredefined[i]; i++)
		{
			DWORD nExpand = ExpandEnvironmentStrings(ppszPredefined[i], szPath, countof(szPath));
			if (nExpand && (nExpand < countof(szPath)))
			{
				if (FileExists(szPath))
				{
					wcscpy_c(pOpt->Comspec32, szPath);
					wcscpy_c(pOpt->Comspec64, szPath);
					break;
				}
			}
		}

		// On this step - check "Take Command"!
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\JP Software\Take Command 13.0]
			// @="\"C:\\Program Files\\JPSoft\\TCMD13\\tcmd.exe\""
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\JP Software", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD k = 0; !bFound && !RegEnumKeyEx(hk, k, szName, &(nLen = countof(szName)-1), 0,0,0,0); k++)
					{
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							// Just in case, check "Path" too
							LPCWSTR rsNames[] = {NULL, L"Path"};

							for (size_t n = 0; n < countof(rsNames); n++)
							{
								ZeroStruct(szPath); DWORD nSize = (countof(szPath)-1)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, rsNames[n], NULL, NULL, (LPBYTE)szPath, &nSize) && *szPath)
								{
									wchar_t* psz, *pszEnd;
									psz = (wchar_t*)Unquote(szPath, true);
									pszEnd = wcsrchr(psz, L'\\');
									if (!pszEnd || lstrcmpi(pszEnd, L"\\tcmd.exe") || !FileExists(psz))
										continue;
									lstrcpyn(pszEnd+1, L"tcc.exe", 8);
									if (FileExists(psz))
									{
										bFound = true;
										if (b == 0)
											wcscpy_c(pOpt->Comspec32, psz);
										else
											wcscpy_c(pOpt->Comspec64, psz);
									}
								}
							} // for (size_t n = 0; n < countof(rsNames); n++)
							RegCloseKey(hk2);
						}
					} //  for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\JP Software"
			} // for (int b = 0; b <= 1; b++)

			// Если установлен TCMD - предпочтительно использовать именно его, независимо от битности
			if (*pOpt->Comspec32 && !*pOpt->Comspec64)
				wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
			else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
				wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
		}

		// If "Take Command" not installed - try "TCC/LE"
		if (!*pOpt->Comspec32 || !*pOpt->Comspec64)
		{
			// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{16A21882-4138-4ADA-A390-F62DC27E4504}]
			// "DisplayVersion"="13.04.60"
			// "Publisher"="JP Software"
			// "DisplayName"="Take Command 13.0"
			// или
			// "DisplayName"="TCC/LE 13.0"
			// и наконец
			// "InstallLocation"="C:\\Program Files\\JPSoft\\TCMD13\\"
			for (int b = 0; b <= 1; b++)
			{
				// b==0 - 32bit, b==1 - 64bit
				if (b && !bWin64)
					continue;
				if (((b == 0) ? *pOpt->Comspec32 : *pOpt->Comspec64))
					continue; // этот уже нашелся в TCMD

				bool bFound = false;
				DWORD nOpt = (b == 0) ? (bWin64 ? KEY_WOW64_32KEY : 0) : (bWin64 ? KEY_WOW64_64KEY : 0);
				if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall", 0, KEY_READ|nOpt, &hk))
				{
					wchar_t szName[MAX_PATH+1]; DWORD nLen;
					for (DWORD n = 0; !bFound && !RegEnumKeyEx(hk, n, szName, &(nLen = countof(szName)-1), 0,0,0,0); n++)
					{
						if (*szName != L'{')
							continue;
						HKEY hk2;
						if (!RegOpenKeyEx(hk, szName, 0, KEY_READ|nOpt, &hk2))
						{
							ZeroStruct(szPath); DWORD nSize = (countof(szPath) - 1)*sizeof(szPath[0]);
							if (!RegQueryValueExW(hk2, L"Publisher", NULL, NULL, (LPBYTE)szPath, &nSize)
								&& !lstrcmpi(szPath, L"JP Software"))
							{
								nSize = (countof(szPath)-12)*sizeof(szPath[0]);
								if (!RegQueryValueExW(hk2, L"InstallLocation", NULL, NULL, (LPBYTE)szPath, &nSize)
									&& *szPath)
								{
									wchar_t* psz, *pszEnd;
									if (szPath[0] == L'"')
									{
										psz = szPath + 1;
										pszEnd = wcschr(psz, L'"');
										if (pszEnd)
											*pszEnd = 0;
									}
									else
									{
										psz = szPath;
									}
									if (*psz)
									{
										pszEnd = psz+lstrlen(psz);
										if (*(pszEnd-1) != L'\\')
											*(pszEnd++) = L'\\';
										lstrcpyn(pszEnd, L"tcc.exe", 8);
										if (FileExists(psz))
										{
											bFound = true;
											if (b == 0)
												wcscpy_c(pOpt->Comspec32, psz);
											else
												wcscpy_c(pOpt->Comspec64, psz);
										}
									}
								}
							}
							RegCloseKey(hk2);
						}
					} // for, подключи
					RegCloseKey(hk);
				} // L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
			} // for (int b = 0; b <= 1; b++)
		}

		// Попытаться "в лоб" из "Program Files"
		if (!*pOpt->Comspec32 && !*pOpt->Comspec64)
		{

			const wchar_t* pszTcmd  = L"C:\\Program Files\\JPSoft\\TCMD13\\tcc.exe";
			const wchar_t* pszTccLe = L"C:\\Program Files\\JPSoft\\TCCLE13\\tcc.exe";
			if (FileExists(pszTcmd))
				wcscpy_c(pOpt->Comspec32, pszTcmd);
			else if (FileExists(pszTccLe))
				wcscpy_c(pOpt->Comspec32, pszTccLe);
		}

		if (*pOpt->Comspec32 && !*pOpt->Comspec64)
			wcscpy_c(pOpt->Comspec64, pOpt->Comspec32);
		else if (*pOpt->Comspec64 && !*pOpt->Comspec32)
			wcscpy_c(pOpt->Comspec32, pOpt->Comspec64);
	} // if (pOpt->csType == cst_AutoTccCmd)

	// С поиском tcc закончили. Теперь, если pOpt->Comspec32/pOpt->Comspec64 остались не заполнены
	// нужно сначала попытаться обработать переменную окружения ComSpec, а потом - просто "cmd.exe"
	if (!*pOpt->Comspec32)
		GetComspecFromEnvVar(pOpt->Comspec32, countof(pOpt->Comspec32), csb_x32);
	if (!*pOpt->Comspec64)
		GetComspecFromEnvVar(pOpt->Comspec64, countof(pOpt->Comspec64), csb_x64);
}
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE previousInstance, LPTSTR commandLine, int showState)
{
    INT_PTR result;
    WCHAR qrexecClientPath[MAX_PATH] = { 0 };
    WCHAR *qrexecClientCmdLine;
    size_t cchQrexecClientCmdLine;
    WCHAR *pathSeparator;
    PROCESS_INFORMATION pi;
    STARTUPINFO si = { 0 };
    DWORD status;

    result = DialogBox(
        instance, // application instance
        MAKEINTRESOURCE(IDD_INPUTBOX), // dialog box resource
        NULL, // owner window
        InputBoxProc // dialog box window procedure
        );

    switch (result)
    {
    case 0:
        // cancel
        return 0;
    case -1:
        // error
        return 1;
    }

    // build qrexec-client-vm path, first get our own
    if (!GetModuleFileName(NULL, qrexecClientPath, RTL_NUMBER_OF(qrexecClientPath)))
    {
        status = perror("GetModuleFileName");
        ReportError(L"Failed to get " QREXEC_CLIENT_VM L" path");
        return status;
    }

    // cut off file name (qrexec_agent.exe)
    pathSeparator = wcsrchr(qrexecClientPath, L'\\');
    if (!pathSeparator)
    {
        LogError("Bad executable path");
        ReportError(L"Cannot find dir containing " QREXEC_CLIENT_VM);
        return ERROR_BAD_PATHNAME;
    }

    // Leave trailing backslash
    pathSeparator++;
    *pathSeparator = L'\0';
    // append target executable
    PathAppend(qrexecClientPath, QREXEC_CLIENT_VM);

    cchQrexecClientCmdLine = wcslen(QREXEC_CLIENT_VM) + wcslen((WCHAR *) result) + wcslen(commandLine) + 3;
    qrexecClientCmdLine = malloc(cchQrexecClientCmdLine * sizeof(WCHAR));

    if (!qrexecClientCmdLine)
    {
        LogError("malloc failed");
        ReportError(L"Out of memory");
        return ERROR_NOT_ENOUGH_MEMORY;
    }

    if (FAILED(StringCchPrintf(qrexecClientCmdLine, cchQrexecClientCmdLine, QREXEC_CLIENT_VM L" %s%c%s",
        (WCHAR *) result, QUBES_ARGUMENT_SEPARATOR, commandLine)))
    {
        LogError("Failed to construct command line");
        ReportError(L"Failed to construct command line");
        return ERROR_BAD_PATHNAME;
    }

    LogDebug("executing command: '%s'", qrexecClientCmdLine);
    si.cb = sizeof(si);

    if (!CreateProcess(qrexecClientPath, qrexecClientCmdLine, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))
    {
        status = perror("CreateProcess");
        ReportError(L"Failed to execute qrexec-client-vm.exe");
        return status;
    }

    return ERROR_SUCCESS;
}
Example #26
0
const wchar_t* CRes::GetName(CString &FileName)
{
	return wcsrchr(FileName.GetString(), _T('/'))+1;
}
Example #27
0
BOOL CYYManager::InitFactory()
{
	WCHAR wzSelfPath[MAX_PATH]; 
	memset( wzSelfPath, 0, sizeof(wzSelfPath) );
	GetModuleFileNameW( NULL, wzSelfPath, sizeof(wzSelfPath) );
	LPWSTR lpInsertPos = wcsrchr( wzSelfPath, L'\\' );
	*lpInsertPos = L'\0';
	lstrcatW( wzSelfPath, L"\\pipFactory.dll" );
	m_hFactory = LoadLibraryW( wzSelfPath );
	if( m_hFactory == NULL ) return FALSE;

	m_pfnInitInterface = (PFN_INITYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_InitInterface" );
	if( m_pfnInitInterface == NULL ) return FALSE;

	m_pfnGetInterface = (PFN_GETYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_GetInterface" );
	if( m_pfnGetInterface == NULL ) return FALSE;

	//call factory init func
	if( m_pfnInitInterface() == -1 ) return FALSE;

	/////////////////////////////////////////////////////////////////////////
	//all game must be call this func to show yy window
	m_pfnRunService = (PFN_RUNSERVICE)m_pfnGetInterface( "YYPIP_RunService" );
	if( m_pfnRunService == NULL ) return FALSE;

	m_pfnLoadInGame = (PFN_LOADINGAME)m_pfnGetInterface( "YYPIP_LoadInGame" );
	if( m_pfnLoadInGame == NULL ) return FALSE;

	m_pfnFreeGame = (PFN_FREEINGAME)m_pfnGetInterface( "YYPIP_FreeInGame" );
	if( m_pfnFreeGame == NULL ) return FALSE;

	m_pfnCheckClient = (PFN_CHECKCLIENT)m_pfnGetInterface( "YYPIP_CheckYYClient" );
	if( m_pfnCheckClient == NULL ) return FALSE;

	m_pfnIsPipSuccess = (PFN_ISPIPSUCCESS)m_pfnGetInterface( "YYPIP_IsPipRunSuccess" );
	if( m_pfnIsPipSuccess == NULL ) return FALSE;

	/////////////////////////////////////////////////////////////////////////
	//sometimes call this func to show yy window
	m_pfnMouseInput = (PFN_MOUSEINPUT)m_pfnGetInterface( "YYPIP_MouseInput" );
	if( m_pfnMouseInput == NULL ) return FALSE;

	m_pfnSetMainWnd = (PFN_SETMAINWND)m_pfnGetInterface( "YYPIP_SetMainWnd" );
	if( m_pfnSetMainWnd == NULL ) return FALSE;

	m_pfnCreateUI = (PFN_CREATEUI)m_pfnGetInterface( "YYPIP_CreateUI" );
	if( m_pfnCreateUI == NULL ) return FALSE;

	m_pfnDestoryUI = (PFN_DESTORYUI)m_pfnGetInterface( "YYPIP_DestoryUI" );
	if( m_pfnDestoryUI == NULL ) return FALSE;

	m_pfnRenderGUI = (PFN_RENDERGUI)m_pfnGetInterface( "YYPIP_RenderGUI" );
	if( m_pfnRenderGUI == NULL ) return FALSE;

	m_pfnGameWndMsg = (PFN_GAMEWNDMSG)m_pfnGetInterface( "YYPIP_GameWndMessage" );
	if( m_pfnGameWndMsg == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game used yy voice channel
	m_pfnJoinChannel = (PFN_JOINCHANNEL)m_pfnGetInterface( "YYPIP_JoinChannel" );
	if( m_pfnJoinChannel == NULL ) return FALSE;

	m_pfnSetTeamAdmin = (PFN_SETTEAMADMIN)m_pfnGetInterface( "YYPIP_SetTeamAdmin" );
	if( m_pfnSetTeamAdmin == NULL ) return FALSE;

	m_pfnSetUserName = (PFN_SETUSERNAME)m_pfnGetInterface( "YYPIP_SetUserName" );
	if( m_pfnSetUserName == NULL ) return FALSE;

	m_pfnJoinTeam = (PFN_JOINTEAM)m_pfnGetInterface( "YYPIP_JoinTeam" );
	if( m_pfnJoinTeam == NULL ) return FALSE;

	m_pfnSetTeamDevice = (PFN_SETTEAMDEVICE)m_pfnGetInterface( "YYPIP_SetTeamDevice" );
	if( m_pfnSetTeamDevice == NULL ) return FALSE;

	m_pfnSetTeamVoice = (PFN_SETTEAMVOICE)m_pfnGetInterface( "YYPIP_SetTeamVoice" );
	if( m_pfnSetTeamVoice == NULL ) return FALSE;

	m_pfnLockTeamVoice = (PFN_LOCKTEAMVOICE)m_pfnGetInterface( "YYPIP_LockTeamVoice" );
	if( m_pfnLockTeamVoice == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game to channel yy voice window
	m_pfnGetPipShow = (PFN_GETPIPSHOW)m_pfnGetInterface( "YYPIP_GetPipShow" );
	if( m_pfnGetPipShow == NULL ) return FALSE;

	m_pfnSetPipShow = (PFN_SETPIPSHOW)m_pfnGetInterface( "YYPIP_SetPipShow" );
	if( m_pfnSetPipShow == NULL ) return FALSE;

	m_pfnSetMsgShow = (PFN_SETMSGSHOW)m_pfnGetInterface( "YYPIP_SetMsgShow" );
	if( m_pfnSetMsgShow == NULL ) return FALSE;

	m_pfnMouseShow = (PFN_SETMOUSESHOW)m_pfnGetInterface( "YYPIP_SetMouseShow" );
	if( m_pfnMouseShow == NULL ) return FALSE;

	m_pfnLockWnd = (PFN_LOCKWINDOW)m_pfnGetInterface( "YYPIP_LockWindow" );
	if( m_pfnLockWnd == NULL ) return FALSE;

	m_pfnMoveWnd = (PFN_MOVEWINDOW)m_pfnGetInterface( "YYPIP_MoveWindow" );
	if( m_pfnMoveWnd == NULL ) return FALSE;


	/////////////////////////////////////////////////////////////////////////
	//game to used open id func 
	m_pfnShowOpid = (PFN_SHOWOPENID)m_pfnGetInterface( "YYPIP_ShowOpenId" );
	if( m_pfnShowOpid == NULL ) return FALSE;

	m_pfnLoginSucceed = (PFN_LOGINSUCCEED)m_pfnGetInterface( "YYPIP_LoginSucceed" );
	if( m_pfnLoginSucceed == NULL ) return FALSE;

	m_pfnLoginFailure = (PFN_LOGINFAILURE)m_pfnGetInterface( "YYPIP_LoginFailure" );
	if( m_pfnLoginFailure == NULL ) return FALSE;

	m_pfnSetLoginKey = (PFN_SETLOGINKEY)m_pfnGetInterface( "YYPIP_SetLoginKey" );
	if( m_pfnSetLoginKey == NULL ) return FALSE;

	m_pfnSetCallBack = (PFN_SETCALLBACK)m_pfnGetInterface( "YYPIP_SetCallBackFunc" );
	if( m_pfnSetCallBack == NULL ) return FALSE;

	return TRUE;
}
Example #28
0
/*enumerate directories*/
GF_EXPORT
GF_Err gf_enum_directory(const char *dir, Bool enum_directory, gf_enum_dir_item enum_dir_fct, void *cbck, const char *filter)
{
#ifdef WIN32
	wchar_t item_path[GF_MAX_PATH];
#else
	char item_path[GF_MAX_PATH];
#endif
	GF_FileEnumInfo file_info;

#if defined(_WIN32_WCE)
	char _path[GF_MAX_PATH];
	unsigned short path[GF_MAX_PATH];
	unsigned short w_filter[GF_MAX_PATH];
	char file[GF_MAX_PATH];
#elif defined(WIN32)
	wchar_t path[GF_MAX_PATH], *file;
	wchar_t w_filter[GF_MAX_PATH];
	wchar_t w_dir[GF_MAX_PATH];
	char *mbs_file, *mbs_item_path;
#else
	char path[GF_MAX_PATH], *file;
#endif

#ifdef WIN32
	WIN32_FIND_DATAW FindData;
	HANDLE SearchH;
#else
	DIR *the_dir;
	struct dirent* the_file;
	struct stat st;
#endif

	if (!dir || !enum_dir_fct) return GF_BAD_PARAM;

	if (filter && (!strcmp(filter, "*") || !filter[0])) filter=NULL;

	memset(&file_info, 0, sizeof(GF_FileEnumInfo) );

	if (!strcmp(dir, "/")) {
#if defined(WIN32) && !defined(_WIN32_WCE)
		u32 len;
		char *drives, *volume;
		len = GetLogicalDriveStrings(0, NULL);
		drives = (char*)gf_malloc(sizeof(char)*(len+1));
		drives[0]=0;
		GetLogicalDriveStrings(len, drives);
		len = (u32) strlen(drives);
		volume = drives;
		file_info.directory = GF_TRUE;
		file_info.drive = GF_TRUE;
		while (len) {
			enum_dir_fct(cbck, volume, "", &file_info);
			volume += len+1;
			len = (u32) strlen(volume);
		}
		gf_free(drives);
		return GF_OK;
#elif defined(__SYMBIAN32__)
		RFs iFs;
		TDriveList aList;
		iFs.Connect();
		iFs.DriveList(aList);
		for (TInt i=0; i<KMaxDrives; i++) {
			if (aList[i]) {
				char szDrive[10];
				TChar aDrive;
				iFs.DriveToChar(i, aDrive);
				sprintf(szDrive, "%c:", (TUint)aDrive);
				enum_dir_fct(cbck, szDrive, "", &file_info);
			}
		}
		iFs.Close();
		FlushItemList();
		return GF_OK;
#endif
	}


#if defined (_WIN32_WCE)
	switch (dir[strlen(dir) - 1]) {
	case '/':
	case '\\':
		sprintf(_path, "%s*", dir);
		break;
	default:
		sprintf(_path, "%s%c*", dir, GF_PATH_SEPARATOR);
		break;
	}
	CE_CharToWide(_path, path);
	CE_CharToWide((char *)filter, w_filter);
#elif defined(WIN32)
	{
		const char* tmpdir = dir;
		gf_utf8_mbstowcs(w_dir, sizeof(w_dir), &tmpdir);
	}
	switch (w_dir[wcslen(w_dir) - 1]) {
	case '/':
	case '\\':
		swprintf(path, MAX_PATH, L"%s*", w_dir);
		break;
	default:
		swprintf(path, MAX_PATH, L"%s%c*", w_dir, GF_PATH_SEPARATOR);
		break;
	}
	{
		const char* tmpfilter = filter;
		gf_utf8_mbstowcs(w_filter, sizeof(w_filter), &tmpfilter);
	}
#else
	strcpy(path, dir);
	if (path[strlen(path)-1] != '/') strcat(path, "/");
#endif

#ifdef WIN32
	SearchH= FindFirstFileW(path, &FindData);
	if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR;

#if defined (_WIN32_WCE)
	_path[strlen(_path)-1] = 0;
#else
	path[wcslen(path)-1] = 0;
#endif

	while (SearchH != INVALID_HANDLE_VALUE) {

#else

	the_dir = opendir(path);
	if (the_dir == NULL) {
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] Cannot open directory %s for enumeration: %d\n", path, errno));
		return GF_IO_ERR;
	}
	the_file = readdir(the_dir);
	while (the_file) {

#endif

		memset(&file_info, 0, sizeof(GF_FileEnumInfo) );


#if defined (_WIN32_WCE)
		if (!wcscmp(FindData.cFileName, _T(".") )) goto next;
		if (!wcscmp(FindData.cFileName, _T("..") )) goto next;
#elif defined(WIN32)
		if (!wcscmp(FindData.cFileName, L".")) goto next;
		if (!wcscmp(FindData.cFileName, L"..")) goto next;
#else
		if (!strcmp(the_file->d_name, "..")) goto next;
		if (the_file->d_name[0] == '.') goto next;
#endif

#ifdef WIN32
		file_info.directory = (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? GF_TRUE : GF_FALSE;
		if (!enum_directory && file_info.directory) goto next;
		if (enum_directory && !file_info.directory) goto next;
#endif

		if (filter) {
#if defined (_WIN32_WCE)
			short ext[30];
			short *sep = wcsrchr(FindData.cFileName, (wchar_t) '.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#elif defined(WIN32)
			wchar_t ext[30];
			wchar_t *sep = wcsrchr(FindData.cFileName, L'.');
			if (!sep) goto next;
			wcscpy(ext, sep+1);
			wcslwr(ext);
			if (!wcsstr(w_filter, ext)) goto next;
#else
			char ext[30];
			char *sep = strrchr(the_file->d_name, '.');
			if (!sep) goto next;
			strcpy(ext, sep+1);
			strlwr(ext);
			if (!strstr(filter, sep+1)) goto next;
#endif
		}

#if defined(WIN32)
		file_info.hidden = (FindData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ? GF_TRUE : GF_FALSE;
		file_info.system = (FindData.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) ? GF_TRUE : GF_FALSE;
		file_info.size = MAXDWORD;
		file_info.size += 1;
		file_info.size *= FindData.nFileSizeHigh;
		file_info.size += FindData.nFileSizeLow;
		file_info.last_modified = (u64) ((*(LONGLONG *) &FindData.ftLastWriteTime - TIMESPEC_TO_FILETIME_OFFSET) / 10000000);
#endif

#if defined (_WIN32_WCE)
		CE_WideToChar(FindData.cFileName, file);
		strcpy(item_path, _path);
		strcat(item_path, file);
#elif defined(WIN32)
		wcscpy(item_path, path);
		wcscat(item_path, FindData.cFileName);
		file = FindData.cFileName;
#else
		strcpy(item_path, path);
		strcat(item_path, the_file->d_name);
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] Checking file %s for enum\n", item_path));

		if (stat( item_path, &st ) != 0) goto next;

		file_info.directory = ((st.st_mode & S_IFMT) == S_IFDIR) ? GF_TRUE : GF_FALSE;
		if (enum_directory && !file_info.directory) goto next;
		if (!enum_directory && file_info.directory) goto next;

		file_info.size = st.st_size;

		{
			struct tm _t = * gmtime(& st.st_mtime);
			file_info.last_modified = mktime(&_t);
		}
		file = the_file->d_name;
		if (file && file[0]=='.') file_info.hidden = 1;

		if (file_info.directory) {
			char * parent_name = strrchr(item_path, '/');
			if (!parent_name) {
				file_info.drive = GF_TRUE;
			} else {
				struct stat st_parent;
				parent_name[0] = 0;
				if (stat(item_path, &st_parent) == 0)  {
					if ((st.st_dev != st_parent.st_dev) || ((st.st_dev == st_parent.st_dev) && (st.st_ino == st_parent.st_ino))) {
						file_info.drive = GF_TRUE;
					}
				}
				parent_name[0] = '/';
			}
		}
#endif

#ifdef WIN32
		mbs_file = wcs_to_utf8(file);
		mbs_item_path = wcs_to_utf8(item_path);
		if (!mbs_file || !mbs_item_path)
		{
			if (mbs_file) gf_free(mbs_file);
			if (mbs_item_path) gf_free(mbs_item_path);
			return GF_IO_ERR;
		}
		if (enum_dir_fct(cbck, mbs_file, mbs_item_path, &file_info)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(1) the following error code: %d\n", err));
			}
#else
		if (enum_dir_fct(cbck, file, item_path, &file_info)) {
#endif
			break;
		}

#ifdef WIN32
		gf_free(mbs_file);
		gf_free(mbs_item_path);
#endif

next:
#ifdef WIN32
		if (!FindNextFileW(SearchH, &FindData)) {
			BOOL ret = FindClose(SearchH);
			if (!ret) {
				DWORD err = GetLastError();
				GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[core] FindClose() in gf_enum_directory() returned(2) the following error code: %d\n", err));
			}
			break;
		}
#else
		the_file = readdir(the_dir);
#endif
	}
#ifndef WIN32
	closedir(the_dir);
#endif
	return GF_OK;
}

GF_EXPORT
u64 gf_ftell(FILE *fp)
{
#if defined(_WIN32_WCE)
	return (u64) ftell(fp);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) ftello64(fp);
#else
	return (u64) ftell(fp);
#endif
#elif defined(WIN32)
	return (u64) _ftelli64(fp);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return (u64) ftello64(fp);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return (u64) ftello(fp);
#else
	return (u64) ftell(fp);
#endif
}

GF_EXPORT
u64 gf_fseek(FILE *fp, s64 offset, s32 whence)
{
#if defined(_WIN32_WCE)
	return (u64) fseek(fp, (s32) offset, whence);
#elif defined(GPAC_CONFIG_WIN32) && !defined(__CYGWIN__)	/* mingw or cygwin */
#if (_FILE_OFFSET_BITS >= 64)
	return (u64) fseeko64(fp, offset, whence);
#else
	return (u64) fseek(fp, (s32) offset, whence);
#endif
#elif defined(WIN32)
	return (u64) _fseeki64(fp, offset, whence);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	return fseeko64(fp, (off64_t) offset, whence);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	return fseeko(fp, (off_t) offset, whence);
#else
	return fseek(fp, (s32) offset, whence);
#endif
}

GF_EXPORT
FILE *gf_fopen(const char *file_name, const char *mode)
{
	FILE *res = NULL;

#if defined(WIN32)
	wchar_t *wname;
	wchar_t *wmode;

	wname = utf8_to_wcs(file_name);
	wmode = utf8_to_wcs(mode);
	if (!wname || !wmode)
	{
		if (wname) gf_free(wname);
		if (wmode) gf_free(wmode);
		return NULL;
	}
	res = _wfsopen(wname, wmode, _SH_DENYNO);
	gf_free(wname);
	gf_free(wmode);
#elif defined(GPAC_CONFIG_LINUX) && !defined(GPAC_ANDROID)
	res = fopen64(file_name, mode);
#elif (defined(GPAC_CONFIG_FREEBSD) || defined(GPAC_CONFIG_DARWIN))
	res = fopen(file_name, mode);
#else
	res = fopen(file_name, mode);
#endif

	if (res) {
		gpac_file_handles++;
		GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[Core] file %s opened in mode %s - %d file handles\n", file_name, mode, gpac_file_handles));
	} else {
		if (strchr(mode, 'w') || strchr(mode, 'a')) {
#if defined(WIN32)
			u32 err = GetLastError();
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: 0x%08x\n", file_name, mode, err));
#else
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("[Core] system failure for file opening of %s in mode %s: %d\n", file_name, mode, errno));
#endif
		}
	}
	return res;
}

GF_EXPORT
s32 gf_fclose(FILE *file)
{
	if (file) {
		assert(gpac_file_handles);
		gpac_file_handles--;
	}
	return fclose(file);
}

#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! defined(_GNU_SOURCE) && !defined(WIN32)
#define HAVE_STRERROR_R 1
#endif

GF_EXPORT
size_t gf_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) {
	return fread(ptr, size, nmemb, stream);
}

GF_EXPORT
size_t gf_fwrite(const void *ptr, size_t size, size_t nmemb,
                 FILE *stream)
{
	size_t result = fwrite(ptr, size, nmemb, stream);
	if (result != nmemb) {
#ifdef _WIN32_WCE
		GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data: %d blocks to write but %d blocks written\n", nmemb, result));
#else
#if defined WIN32 && !defined(GPAC_CONFIG_WIN32)
		errno_t errno_save;
		_get_errno(&errno_save);
#else
		int errno_save = errno;
#endif
		//if (errno_save!=0)
		{
#ifdef HAVE_STRERROR_R
#define ERRSTR_BUF_SIZE 256
			char errstr[ERRSTR_BUF_SIZE];
			if(strerror_r(errno_save, errstr, ERRSTR_BUF_SIZE) != 0)
			{
				strerror_r(0, errstr, ERRSTR_BUF_SIZE);
			}
#else
			char *errstr = (char*)strerror(errno_save);
#endif
			GF_LOG(GF_LOG_ERROR, GF_LOG_CORE, ("Error writing data (%s): %d blocks to write but %d blocks written\n", errstr, nmemb, result));
		}
#endif
	}
	return result;
}
Example #29
0
/*
 * @implemented
 */
BOOL
WINAPI
GetBinaryTypeW (
    LPCWSTR lpApplicationName,
    LPDWORD lpBinaryType
)
{
    HANDLE hFile;
    DWORD BinType;

    if(!lpApplicationName || !lpBinaryType)
    {
        SetLastError(ERROR_INVALID_PARAMETER);
        return FALSE;
    }

    hFile = CreateFileW(lpApplicationName, GENERIC_READ, FILE_SHARE_READ, NULL,
                        OPEN_EXISTING, 0, 0);
    if(hFile == INVALID_HANDLE_VALUE)
    {
        return FALSE;
    }

    BinType = InternalGetBinaryType(hFile);
    CloseHandle(hFile);

    switch(BinType)
    {
    case BINARY_UNKNOWN:
    {
        WCHAR *dot;

        /*
         * guess from filename
         */
        if(!(dot = wcsrchr(lpApplicationName, L'.')))
        {
            return FALSE;
        }
        if(!lstrcmpiW(dot, L".COM"))
        {
            *lpBinaryType = SCS_DOS_BINARY;
            return TRUE;
        }
        if(!lstrcmpiW(dot, L".PIF"))
        {
            *lpBinaryType = SCS_PIF_BINARY;
            return TRUE;
        }
        return FALSE;
    }
    case BINARY_PE_EXE32:
    case BINARY_PE_DLL32:
    {
        *lpBinaryType = SCS_32BIT_BINARY;
        return TRUE;
    }
    case BINARY_PE_EXE64:
    case BINARY_PE_DLL64:
    {
        *lpBinaryType = SCS_64BIT_BINARY;
        return TRUE;
    }
    case BINARY_WIN16:
    {
        *lpBinaryType = SCS_WOW_BINARY;
        return TRUE;
    }
    case BINARY_OS216:
    {
        *lpBinaryType = SCS_OS216_BINARY;
        return TRUE;
    }
    case BINARY_DOS:
    {
        *lpBinaryType = SCS_DOS_BINARY;
        return TRUE;
    }
    case BINARY_UNIX_EXE:
    case BINARY_UNIX_LIB:
    {
        return FALSE;
    }
    }

    DPRINT1("Invalid binary type returned!\n", BinType);
    return FALSE;
}
Example #30
0
// Function checks, if we need drop first and last quotation marks
// Example: ""7z.exe" /?"
// Using cmd.exe rules
bool IsNeedDequote(LPCWSTR asCmdLine, bool abFromCmdCK, LPCWSTR* rsEndQuote/*=NULL*/)
{
	if (rsEndQuote)
		*rsEndQuote = NULL;

	if (!asCmdLine)
		return false;

	bool bDeQu = false;
	LPCWSTR pszQE, pszSP;
	if (asCmdLine[0] == L'"')
	{
		bDeQu = (asCmdLine[1] == L'"');
		// Всегда - нельзя. Иначе парсинг строки запуска некорректно идет
		// L"\"C:\\ConEmu\\ConEmuC64.exe\"  /PARENTFARPID=1 /C \"C:\\GIT\\cmdw\\ad.cmd CE12.sln & ci -m \"Solution debug build properties\"\""
		if (!bDeQu)
		{
			size_t nLen = lstrlen(asCmdLine);
			if (abFromCmdCK)
			{
				bDeQu = ((asCmdLine[nLen-1] == L'"') && (asCmdLine[nLen-2] == L'"'));
			}
			if (!bDeQu && (asCmdLine[nLen-1] == L'"'))
			{
				pszSP = wcschr(asCmdLine+1, L' ');
				pszQE = wcschr(asCmdLine+1, L'"');
				if (pszSP && pszQE && (pszSP < pszQE)
					&& ((pszSP - asCmdLine) < MAX_PATH))
				{
					CmdArg lsTmp;
					lsTmp.Set(asCmdLine+1, pszSP-asCmdLine-1);
					bDeQu = (IsFilePath(lsTmp, true) && IsExecutable(lsTmp));
				}
			}
		}
	}
	if (!bDeQu)
		return false;

	// Don't dequote?
	pszQE = wcsrchr(asCmdLine+2, L'"');
	if (!pszQE)
		return false;

#if 0
	LPCWSTR pszQ1 = wcschr(asCmdLine+2, L'"');
	if (!pszQ1)
		return false;
	LPCWSTR pszQE = wcsrchr(pszQ1, L'"');
	// Only TWO quotes in asCmdLine?
	if (pszQE == pszQ1)
	{
		// Doesn't contains special symbols?
		if (!wcspbrk(asCmdLine+1, L"&<>()@^|"))
		{
			// Must contains spaces (doubt?)
			if (wcschr(asCmdLine+1, L' '))
			{
				// Cmd also checks this for executable file name. Skip this check?
				return false;
			}
		}
	}
#endif

	// Well, we get here
	_ASSERTE(asCmdLine[0]==L'"' && pszQE && *pszQE==L'"' && !wcschr(pszQE+1,L'"'));
	// Dequote it!
	if (rsEndQuote)
		*rsEndQuote = pszQE;
	return true;
}