/** * Returns the .git-path (if .git is a file, read the repository path and return it) * adminDir always ends with "\" */ bool GitAdminDir::GetAdminDirPath(const CString& projectTopDir, CString& adminDir, bool* isWorktree) { CString wtAdminDir; if (!GetWorktreeAdminDirPath(projectTopDir, wtAdminDir)) return false; CString pathToCommonDir = wtAdminDir + L"commondir"; if (!PathFileExists(pathToCommonDir)) { adminDir = wtAdminDir; if (isWorktree) *isWorktree = false; return true; } CAutoFILE pFile = _wfsopen(pathToCommonDir, L"rb", SH_DENYWR); if (!pFile) return false; int size = 65536; CStringA commonDirA; int length = (int)fread(commonDirA.GetBufferSetLength(size), sizeof(char), size, pFile); commonDirA.ReleaseBuffer(length); CString commonDir = CUnicodeUtils::GetUnicode(commonDirA); commonDir.TrimRight(L"\r\n"); commonDir.Replace(L'/', L'\\'); if (PathIsRelative(commonDir)) adminDir = CPathUtils::BuildPathWithPathDelimiter(wtAdminDir + commonDir); else adminDir = CPathUtils::BuildPathWithPathDelimiter(commonDir); if (isWorktree) *isWorktree = true; return true; }
void File::Open(const String &sFilename, OpenType ot) { if (IsOpen()) { // The file should be closed, before we // try to open it again... throw std::logic_error(Formatter::FormatAsAnsi("The file {0} is already open.", sFilename)); } std::wstring open_mode; switch (ot) { case OTReadOnly: open_mode = _T("rb"); break; case OTCreate: open_mode = _T("wb"); break; case OTAppend: open_mode = _T("ab"); break; } file_ = _wfsopen(sFilename.c_str(), open_mode.c_str(), _SH_DENYNO); if (file_ == nullptr) { ThrowRuntimeError_(Formatter::FormatAsAnsi("Unable to open the file {0}.", sFilename)); } name_ = sFilename; }
VDLog* VDLog::get(TCHAR* path) { if (_log || !path) { return _log; } DWORD size = 0; HANDLE file = CreateFile(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (file != INVALID_HANDLE_VALUE) { size = GetFileSize(file, NULL); CloseHandle(file); } if (size != INVALID_FILE_SIZE && size > LOG_ROLL_SIZE) { TCHAR roll_path[MAX_PATH]; _sntprintf(roll_path, MAX_PATH, TEXT("%s.1"), path); if (!MoveFileEx(path, roll_path, MOVEFILE_REPLACE_EXISTING)) { return NULL; } } FILE* handle = _wfsopen(path, L"a+", _SH_DENYNO); if (!handle) { return NULL; } _log = new VDLog(handle); return _log; }
CString GitAdminDir::ReadGitLink(const CString& topDir, const CString& dotGitPath) { CAutoFILE pFile = _wfsopen(dotGitPath, L"r", SH_DENYWR); if (!pFile) return L""; int size = 65536; auto buffer = std::make_unique<char[]>(size); int length = (int)fread(buffer.get(), sizeof(char), size, pFile); CStringA gitPathA(buffer.get(), length); if (length < 8 || !CStringUtils::StartsWith(gitPathA, "gitdir: ")) return L""; CString gitPath = CUnicodeUtils::GetUnicode(gitPathA); // trim after converting to UTF-16, because CStringA trim does not work when having UTF-8 chars gitPath = gitPath.Trim().Mid((int)wcslen(L"gitdir: ")); gitPath.Replace('/', '\\'); if (!gitPath.IsEmpty() && gitPath[0] == L'.') { gitPath = CPathUtils::BuildPathWithPathDelimiter(topDir) + gitPath; CString adminDir; PathCanonicalize(CStrBuf(adminDir, MAX_PATH), gitPath); return adminDir; } CPathUtils::TrimTrailingPathDelimiter(gitPath); return gitPath; }
FILE* SharedUtil::File::Fopen(const char* szFilename, const char* szMode) { #ifdef WIN32 return _wfsopen(FromUTF8(szFilename), FromUTF8(szMode), _SH_DENYNO); #else return fopen(szFilename, szMode); #endif }
FILE *ff_arch_misc_open_log_file_utf8(const wchar_t *filename) { FILE *stream; stream = _wfsopen(filename, L"at, ccs=UTF-8", _SH_DENYWR); ff_winapi_fatal_error_check(stream != NULL, L"cannot open the log file [%ls], errno=%d.", filename, errno); return stream; }
std::FILE *fopen(const char *path, const char *mode) { #ifdef _WIN32 try { return _wfsopen(u8string(path).to_wide(true).c_str(), u8string(mode).to_wide(true).c_str(), _SH_DENYNO); } catch(unicode_conversion_error) { errno = EINVAL; return nullptr; } #else return std::fopen(path, mode); #endif }
bool CLog::Init(const char* path) { CSingleLock waitLock(critSec); if (!m_file) { // g_settings.m_logFolder is initialized in the CSettings constructor // and changed in CApplication::Create() #ifdef _WIN32 CStdStringW pathW; g_charsetConverter.utf8ToW(path, pathW, false); CStdStringW strLogFile, strLogFileOld; strLogFile.Format(L"%sxbmc.log", pathW); strLogFileOld.Format(L"%sxbmc.old.log", pathW); struct __stat64 info; if (_wstat64(strLogFileOld.c_str(),&info) == 0 && !::DeleteFileW(strLogFileOld.c_str())) return false; if (_wstat64(strLogFile.c_str(),&info) == 0 && !::MoveFileW(strLogFile.c_str(),strLogFileOld.c_str())) return false; m_file = _wfsopen(strLogFile.c_str(),L"wb", _SH_DENYWR); #else CStdString strLogFile, strLogFileOld; strLogFile.Format("%sxbmc.log", path); strLogFileOld.Format("%sxbmc.old.log", path); struct stat64 info; if (stat64(strLogFileOld.c_str(),&info) == 0 && remove(strLogFileOld.c_str()) != 0) return false; if (stat64(strLogFile.c_str(),&info) == 0 && rename(strLogFile.c_str(),strLogFileOld.c_str()) != 0) return false; m_file = fopen(strLogFile.c_str(),"wb"); #endif } if (m_file) { unsigned char BOM[3] = {0xEF, 0xBB, 0xBF}; fwrite(BOM, sizeof(BOM), 1, m_file); } if (!m_repeatLine) m_repeatLine = new CStdString; return m_file != NULL; }
FILE * _Xfsopen(_In_z_ const wchar_t *filename, _In_ int mode, _In_ int prot) { static const wchar_t * const mods[] = { // fopen mode strings corresponding to valid[i] L"r", L"w", L"w", L"a", L"rb", L"wb", L"wb", L"ab", L"r+", L"w+", L"a+", L"r+b", L"w+b", L"a+b", 0}; return _wfsopen(filename, mods[mode], prot); }
bool FileStream::Open(const char* szFileName, const char* szMode, bool sharedHandle) { // must not already have a handle open ASSERT(fs_pfh == nullptr); #if WINDOWS // open file on Windows FILE* pfh = nullptr; #ifndef SCRATCH_NO_UTF8 size_t sizeFileName = strlen(szFileName) + 1; wchar_t* wszFileName = (wchar_t*)malloc(sizeof(wchar_t) * sizeFileName); mbstowcs(wszFileName, szFileName, sizeFileName); size_t sizeMode = strlen(szMode) + 1; wchar_t* wszMode = (wchar_t*)malloc(sizeof(wchar_t) * sizeMode); mbstowcs(wszMode, szMode, sizeMode); #endif if (sharedHandle) { #ifdef SCRATCH_NO_UTF8 pfh = _fsopen(szFileName, szMode, _SH_DENYWR); #else pfh = _wfsopen(wszFileName, wszMode, _SH_DENYWR); #endif } else { #ifdef SCRATCH_NO_UTF8 fopen_s(&pfh, szFileName, szMode); #else _wfopen_s(&pfh, wszFileName, wszMode); #endif } #ifndef SCRATCH_NO_UTF8 free(wszFileName); free(wszMode); #endif #else // open file on linux FILE* pfh = fopen(szFileName, szMode); #endif // it might not exist if (pfh == nullptr) { return false; } // remember info fs_strFileName = szFileName; fs_pfh = pfh; // success return true; }
void Debug::LogFileOpen() { Debug::MakeLogFile(); Debug::LogFileClose(999); pLogFile = _wfsopen(Debug::LogFileTempName.c_str(), L"w", _SH_DENYWR); if(!pLogFile) { wchar_t msg[100] = L"\0"; wsprintfW(msg, L"Log file failed to open. Error code = %X", errno); MessageBoxW(Game::hWnd, Debug::LogFileTempName.c_str(), msg, MB_OK | MB_ICONEXCLAMATION); ExitProcess(1); } }
bool AL_CALLTYPE alFileStd_wfsopen(alFileStd* _this, const wchar_t *filename, const wchar_t *mode, int shflag ) { alFileStdi* _data = (alFileStdi*)_this; if (_data->handle != NULL) alFileStd_Close(_this); _data->handle = _wfsopen(filename, mode, shflag); if (_data->handle == NULL) return false; return true; }
static FILE *LocalOpenLogFile(UnicodeString LogFileName, TDateTime Started, TSessionData *SessionData, bool Append, UnicodeString &ANewFileName) { UnicodeString NewFileName = StripPathQuotes(GetExpandedLogFileName(LogFileName, Started, SessionData)); FILE *Result = _wfsopen(ApiPath(NewFileName).c_str(), Append ? L"ab" : L"wb", SH_DENYWR); if (Result != nullptr) { setvbuf(Result, nullptr, _IONBF, BUFSIZ); ANewFileName = NewFileName; } else { throw ECRTExtException(FMTLOAD(LOG_OPENERROR, NewFileName)); } return Result; }
/** * Open file path given in the current encoding, using desired shared access. * * @param path file path * @param mode string specifying file opening mode * @param exclusive non-zero to prohibit write access to the file * @return file descriptor on success, NULL on error */ FILE* win_fopen_ex(const char* path, const char* mode, int exclusive) { FILE* fd = 0; int i; wchar_t* wmode = utf8_to_wchar(mode); assert(wmode != NULL); /* try two code pages */ for(i = 0; i < 2; i++) { wchar_t* wpath = c2w(path, i); if(wpath == NULL) continue; fd = _wfsopen(wpath, wmode, (exclusive ? _SH_DENYWR : _SH_DENYNO)); free(wpath); if(fd || errno != ENOENT) break; } free(wmode); return fd; }
FILE *aa_fopen(const char *name, const char *mode) { wchar_t *wname, *wmode; FILE *fp; if (strcmp(name, "-") == 0) { fp = (mode[0] == 'r') ? stdin : stdout; _setmode(_fileno(fp), _O_BINARY); } else { int share = _SH_DENYRW; if (strchr(mode, 'r') && !strchr(mode, '+')) share = _SH_DENYWR; codepage_decode_wchar(CP_UTF8, name, &wname); codepage_decode_wchar(CP_UTF8, mode, &wmode); fp = _wfsopen(wname, wmode, share); free(wname); free(wmode); } return fp; }
bool testUnicode(char *filename) { char a,b; FILE *test=NULL; try { test= _wfsopen(T2W(filename),T2W("rb"), _SH_DENYNO); if(test==NULL ){ logger(Error,"Failed to open input file %s to inspect unicode status. Error code %d. Assuming non unicode. Problem with log file access?",filename, errno); return false; } a=getc(test); //NOT getwc! b=getc(test); // Empty file produces -1 and -1 (EOF twice) if ((a==-1)&(b==-2)) { //actually 0xFF 0xFE //is unicode fclose(test); test=0; DEBUGAPPLPARSE(Informational,"Log file %s is in unicode format.",filename); return true; } else { fclose(test); test=0; DEBUGAPPLPARSE(Informational,"Log file %s is not unicode format.",filename); return false; } } catch(SE_Exception e) { logger(Error,"SEH Exception in testUnicode for log file %s. Assuming non unicode log file. Error code %u.",filename,e.getSeNumber()); } catch(...) { CreateMiniDump(NULL); logger(Error, "Exception when detecting unicode status on log file %s. Dump file written.",filename); if (test!=NULL) fclose(test); } return false; }
static void setup_log_stream(FILE **p_stream, const char *stream_path) { if(stream_path) { #ifdef _WIN32 if( !(*p_stream = _wfsopen((wchar_t*)stream_path, L"w", _SH_DENYNO)) ) { stream_path = w2c((wchar_t*)stream_path); #else if( !(*p_stream = fopen(stream_path, "w")) ) { #endif log_error(_("%s: %s\n"), stream_path, strerror(errno)); rsh_exit(2); } } } /** * Initialize pointers to output functions. */ void setup_output(void) { rhash_data.out = stdout; rhash_data.log = stderr; if(opt.flags & OPT_PERCENTS) { /* we don't use _fileno() cause it is not in ISO C90, and so * is incompatible with the GCC -ansi option */ if(rhash_data.log == stderr && isatty(2)) { percents_output = &p_perc; /* one-line percents */ } else { percents_output = &dots_perc; /* print percents as dots */ } } else { percents_output = &dummy_perc; /* no percents */ } setup_log_stream(&rhash_data.out, opt.output); setup_log_stream(&rhash_data.log, opt.log); }
BOOL CFileBase::GetHandle(const SYSTEMTIME &Time, FILE** Handle) { USING_TIME_INFO; FileBackup(Time); m_sLastTime = Time; if (NULL != m_pFileHandle) { *Handle = m_pFileHandle; return TRUE; } CString strFileName; if (!GetFileName(Time, strFileName)) return FALSE; SetFileName(strFileName); m_pFileHandle = _wfsopen(strFileName, _T("ab"), _SH_DENYNO); if (NULL == m_pFileHandle) { CString strError; strError.Format(_T("Create file[%s] error:%s!!!"), strFileName, AtlGetErrorDescription(GetLastError())); LOGGER_WRITE(strError.GetBuffer()); LogEvent(strError); return FALSE; } fseek(m_pFileHandle, 0, SEEK_END); m_iFileSize = ftell(m_pFileHandle); *Handle = m_pFileHandle; return TRUE; }
/*---------------------------------------------------------------------- | NPT_fsopen_utf8 +---------------------------------------------------------------------*/ FILE* NPT_fsopen_utf8(const char* path, const char* mode, int sh_flags) { NPT_WIN32_USE_CHAR_CONVERSION; return _wfsopen(NPT_WIN32_A2W(path), NPT_WIN32_A2W(mode), sh_flags); }
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, _u("{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 _itow_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; } char16 fileName[_MAX_PATH]; char16 moduleName[_MAX_PATH]; GetModuleFileName(0, moduleName, _MAX_PATH); _wsplitpath_s(moduleName, nullptr, 0, nullptr, 0, fileName, _MAX_PATH, nullptr, 0); if (_wcsicmp(fileName, _u("WWAHost")) == 0 || _wcsicmp(fileName, _u("ByteCodeGenerator")) == 0 || _wcsicmp(fileName, _u("spartan")) == 0 || _wcsicmp(fileName, _u("spartan_edge")) == 0 || _wcsicmp(fileName, _u("MicrosoftEdge")) == 0 || _wcsicmp(fileName, _u("MicrosoftEdgeCP")) == 0) { // we need to output to %temp% directory in wwa. we don't have permission otherwise. if (GetEnvironmentVariable(_u("temp"), fileName, _MAX_PATH) != 0) { wcscat_s(fileName, _MAX_PATH, _u("\\")); const char16 * fileNameOnly = wcsrchr(outputFile, _u('\\')); // 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; }
void os_init() { __pfnDliNotifyHook2 = delayHook; __cpuid(cpuinfo, 1); #define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { ::MessageBoxA(NULL, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); exit(0); } OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize = sizeof(ovi); GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi)); bIsWin7 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 7100)); bIsVistaSP1 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 6001)); unsigned int currentControl = 0; _controlfp_s(¤tControl, _DN_FLUSH, _MCW_DN); SetHeapOptions(); mumble_speex_init(); #ifdef QT_NO_DEBUG QString console = g.qdBasePath.filePath(QLatin1String("Console.txt")); fConsole = _wfsopen(console.toStdWString().c_str(), L"a+", _SH_DENYWR); if (fConsole) qInstallMsgHandler(mumbleMessageOutput); QString hash; QFile f(qApp->applicationFilePath()); if (! f.open(QIODevice::ReadOnly)) { qWarning("VersionCheck: Failed to open binary"); } else { QByteArray a = f.readAll(); if (a.size() > 0) { QCryptographicHash qch(QCryptographicHash::Sha1); qch.addData(a); hash = QLatin1String(qch.result().toHex()); } } QString comment = QString::fromLatin1("%1\n%2\n%3").arg(QString::fromLatin1(MUMBLE_RELEASE), QString::fromLatin1(MUMTEXT(MUMBLE_VERSION_STRING)), hash); wcscpy_s(wcComment, PATH_MAX, comment.toStdWString().c_str()); musComment.Type = CommentStreamW; musComment.Buffer = wcComment; musComment.BufferSize = wcslen(wcComment) * sizeof(wchar_t); QString dump = g.qdBasePath.filePath(QLatin1String("mumble.dmp")); QFileInfo fi(dump); QDir::root().mkpath(fi.absolutePath()); if (wcscpy_s(wcCrashDumpPath, PATH_MAX, dump.toStdWString().c_str()) == 0) SetUnhandledExceptionFilter(MumbleUnhandledExceptionFilter); // Increase our priority class to live alongside games. if (!SetPriorityClass(GetCurrentProcess(),HIGH_PRIORITY_CLASS)) qWarning("Application: Failed to set priority!"); #endif g.qdBasePath.mkpath(QLatin1String("Snapshots")); if (bIsWin7) SetCurrentProcessExplicitAppUserModelID(L"net.sourceforge.mumble.Mumble"); }
void os_init() { __cpuid(cpuinfo, 1); #define MMXSSE 0x02800000 if ((cpuinfo[3] & MMXSSE) != MMXSSE) { ::MessageBoxA(NULL, "Mumble requires a SSE capable processor (Pentium 3 / Ahtlon-XP)", "Mumble", MB_OK | MB_ICONERROR); exit(0); } OSVERSIONINFOEXW ovi; memset(&ovi, 0, sizeof(ovi)); ovi.dwOSVersionInfoSize = sizeof(ovi); GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi)); bIsWin7 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 7100)); bIsVistaSP1 = (ovi.dwMajorVersion >= 7) || ((ovi.dwMajorVersion == 6) &&(ovi.dwBuildNumber >= 6001)); #if _MSC_VER == 1800 && defined(_M_X64) // Disable MSVC 2013's FMA-optimized math routines on Windows // versions earlier than Windows 8 (6.2). // There are various issues on OSes that do not support the newer // instructions. // See issue mumble-voip/mumble#1615. if (ovi.dwMajorVersion < 5 || (ovi.dwMajorVersion == 6 && ovi.dwMinorVersion <= 1)) { _set_FMA3_enable(0); } #endif unsigned int currentControl = 0; _controlfp_s(¤tControl, _DN_FLUSH, _MCW_DN); SetHeapOptions(); enableCrashOnCrashes(); mumble_speex_init(); #ifdef QT_NO_DEBUG QString console = g.qdBasePath.filePath(QLatin1String("Console.txt")); fConsole = _wfsopen(console.toStdWString().c_str(), L"a+", _SH_DENYWR); if (fConsole) { #if QT_VERSION >= 0x050000 qInstallMessageHandler(mumbleMessageOutputWithContext); #else qInstallMsgHandler(mumbleMessageOutput); #endif } QString hash; QFile f(qApp->applicationFilePath()); if (! f.open(QIODevice::ReadOnly)) { qWarning("VersionCheck: Failed to open binary"); } else { QByteArray a = f.readAll(); if (a.size() > 0) { QCryptographicHash qch(QCryptographicHash::Sha1); qch.addData(a); hash = QLatin1String(qch.result().toHex()); } } QString comment = QString::fromLatin1("%1\n%2\n%3").arg(QString::fromLatin1(MUMBLE_RELEASE), QString::fromLatin1(MUMTEXT(MUMBLE_VERSION_STRING)), hash); wcscpy_s(wcComment, PATH_MAX, comment.toStdWString().c_str()); musComment.Type = CommentStreamW; musComment.Buffer = wcComment; musComment.BufferSize = static_cast<ULONG>(wcslen(wcComment) * sizeof(wchar_t)); QString dump = g.qdBasePath.filePath(QLatin1String("mumble.dmp")); QFileInfo fi(dump); QDir::root().mkpath(fi.absolutePath()); if (wcscpy_s(wcCrashDumpPath, PATH_MAX, dump.toStdWString().c_str()) == 0) SetUnhandledExceptionFilter(MumbleUnhandledExceptionFilter); #endif g.qdBasePath.mkpath(QLatin1String("Snapshots")); if (bIsWin7) SetCurrentProcessExplicitAppUserModelID(L"net.sourceforge.mumble.Mumble"); }
/*---------------------------------------------------------------------- | NPT_fsopen_utf8 +---------------------------------------------------------------------*/ FILE* NPT_fsopen_utf8(const char* path, const char* mode, int sh_flags) { NPT_WIN32_USE_CHAR_CONVERSION; return _wfsopen(NPT_WIN32_A2W(path), NPT_WIN32_A2W(mode + NPT_String(", ccs=UNICODE")), sh_flags); }
void LaunchGame(LPCSTR lpCmdLine) { //Get FF8.exe path _TCHAR exe_path[MAX_PATH]; memset(&exe_path, 0, sizeof(_TCHAR)*MAX_PATH); _TCHAR dir_path[MAX_PATH]; DWORD dir_path_size = MAX_PATH*sizeof(_TCHAR); memset(&dir_path, 0, dir_path_size); int lpCmdLineF_size = (int)strlen(lpCmdLine)+1; _TCHAR *lpCmdLineF = new _TCHAR[lpCmdLineF_size]; #ifdef _UNICODE MultiByteToWideChar(CP_UTF8, 0, lpCmdLine, -1, lpCmdLineF, lpCmdLineF_size); #else _sntprintf_s(lpCmdLineF, lpCmdLineF_size, lpCmdLineF_size, _T("%s"), lpCmdLine); #endif FILE *fs; if(lpCmdLineF_size > 1 && ((fs = _wfsopen(lpCmdLineF, _T("r"), _SH_DENYNO)) != NULL)) { //From file fclose(fs); _sntprintf_s((_TCHAR *)&dir_path, MAX_PATH, MAX_PATH, _T("%s"), lpCmdLineF); for(int i = MAX_PATH-1; i >= 0; i--) { if(dir_path[i] == _T('\\')) { dir_path[i] = _T('\0'); break; } } _sntprintf_s((_TCHAR *)&exe_path, MAX_PATH, MAX_PATH, _T("%s"), lpCmdLineF); } else { //From registry HKEY hFF8_key = NULL; if(ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Square Soft, Inc\\FINAL FANTASY VIII\\1.00"), 0, KEY_QUERY_VALUE, &hFF8_key)) { if(ERROR_SUCCESS == RegQueryValueEx(hFF8_key, _T("AppPath"), NULL, NULL, (LPBYTE)&dir_path, &dir_path_size)) { _sntprintf_s((_TCHAR *)&exe_path, MAX_PATH, MAX_PATH, _T("%s\\FF8.exe"), dir_path); } } } if(_tcslen((_TCHAR *)&exe_path) <= 0) { MessageBox(NULL, _T("FF8.exe path missing from both command line and registry.\n\nCorrect Usage:\nc:\\games\\ff8_loader.exe c:\\games\\ff8.exe"), _T("Final Fantasy VIII Launcher"), MB_OK | MB_ICONERROR); } else { //Inject our library into the target process //installCOMHook(); STARTUPINFO si; PROCESS_INFORMATION pi; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); //Launch ff8.exe if(!CreateProcess(NULL, (LPWSTR)&exe_path, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL /*(LPCWSTR)&dir_path*/, &si, &pi)) { _TCHAR mbuffer[255]; _sntprintf_s((_TCHAR *)&mbuffer, 150, 150, _T("CreateProcess(FF8.exe) returned an error...\n\nERROR CODE: %d\n"), GetLastError()); MessageBox(NULL, (_TCHAR *)&mbuffer, _T("Final Fantasy VIII Launcher"), MB_OK | MB_ICONERROR); } HANDLE hThread; _TCHAR currdirPath[MAX_PATH], libPath[MAX_PATH]; void* pLibRemote; DWORD hLibModule; HMODULE hKernel32 = GetModuleHandle(_T("Kernel32")); if(GetCurrentDirectory(MAX_PATH, currdirPath)) { //Error } _sntprintf_s(libPath, MAX_PATH, MAX_PATH, _T("%s\\dx_hook.dll"), currdirPath); pLibRemote = VirtualAllocEx(pi.hProcess, NULL, sizeof(libPath), MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(pi.hProcess, pLibRemote, (void*)libPath, sizeof(libPath), NULL ); hThread = ::CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(hKernel32, "LoadLibraryW"), pLibRemote, 0, NULL); WaitForSingleObject(hThread, INFINITE); GetExitCodeThread(hThread, &hLibModule); CloseHandle(hThread); VirtualFreeEx(pi.hProcess, pLibRemote, sizeof(libPath), MEM_RELEASE); // now start running the application ResumeThread(pi.hThread); //Destroy the application window and wait for the FF8.exe process to return before therminating the launcher process DestroyWindow(g_hwndMain); WaitForSingleObject(pi.hProcess, INFINITE); //Unload DLL hThread = ::CreateRemoteThread(pi.hProcess, NULL, 0, (LPTHREAD_START_ROUTINE) GetProcAddress(hKernel32, "FreeLibraryW"), (LPVOID)hLibModule, 0, NULL); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); //Release COM-hook and cleanup //removeCOMHook(); } delete lpCmdLineF; lpCmdLineF = NULL; }
int write_ogg_tag(const string fname, struct fennec_audiotag *wtag) { vcedit_state *state; vorbis_comment *vc; param_t *param; FILE *tfile; FILE *of; string outname; struct fennec_audiotag_item *ct; if(!fname || !wtag)return -3; setlocale(LC_ALL, ""); /* initialize the cmdline interface */ param = new_param(); tfile = _wfsopen(fname, uni("r+b"), _SH_DENYRW); if(!tfile) { MessageBox(0, uni("Access denied, please stop playback and try again (you don't need to close this window)."), uni("Tag Editing"), MB_ICONINFORMATION); return -1; } state = vcedit_new_state(); if(vcedit_open(state, tfile) < 0) { fclose(tfile); free_param(param); vcedit_clear(state); return -2; } vc = vcedit_comments(state); ct = &wtag->tag_title; if(ct->tsize)local_addcomment(vc, "TITLE", ct->tdata); else local_addcomment(vc, "TITLE", uni("") ); ct = &wtag->tag_album; if(ct->tsize)local_addcomment(vc, "ALBUM", ct->tdata); else local_addcomment(vc, "ALBUM", uni("") ); ct = &wtag->tag_artist; if(ct->tsize)local_addcomment(vc, "ARTIST", ct->tdata); else local_addcomment(vc, "ARTIST", uni("") ); ct = &wtag->tag_origartist; if(ct->tsize)local_addcomment(vc, "ORIGINALARTIST", ct->tdata); else local_addcomment(vc, "ORIGINALARTIST", uni("") ); ct = &wtag->tag_composer; if(ct->tsize)local_addcomment(vc, "COMPOSER", ct->tdata); else local_addcomment(vc, "COMPOSER", uni("") ); ct = &wtag->tag_lyricist; if(ct->tsize)local_addcomment(vc, "LYRICIST", ct->tdata); else local_addcomment(vc, "LYRICIST", uni("") ); ct = &wtag->tag_band; if(ct->tsize)local_addcomment(vc, "BANDNAME", ct->tdata); else local_addcomment(vc, "BANDNAME", uni("") ); ct = &wtag->tag_copyright; if(ct->tsize)local_addcomment(vc, "COPYRIGHT", ct->tdata); else local_addcomment(vc, "COPYRIGHT", uni("") ); ct = &wtag->tag_publish; if(ct->tsize)local_addcomment(vc, "PUBLISHER", ct->tdata); else local_addcomment(vc, "PUBLISHER", uni("") ); ct = &wtag->tag_encodedby; if(ct->tsize)local_addcomment(vc, "ENCODEDBY", ct->tdata); else local_addcomment(vc, "ENCODEDBY", uni("") ); ct = &wtag->tag_genre; if(ct->tsize)local_addcomment(vc, "GENRE", ct->tdata); else local_addcomment(vc, "GENRE", uni("") ); ct = &wtag->tag_year; if(ct->tsize)local_addcomment(vc, "YEAR", ct->tdata); else local_addcomment(vc, "YEAR", uni("") ); ct = &wtag->tag_url; if(ct->tsize)local_addcomment(vc, "URL", ct->tdata); else local_addcomment(vc, "URL", uni("") ); ct = &wtag->tag_offiartisturl; if(ct->tsize)local_addcomment(vc, "OFFICIALARTISTURL", ct->tdata); else local_addcomment(vc, "OFFICIALARTISTURL", uni("") ); ct = &wtag->tag_comments; if(ct->tsize)local_addcomment(vc, "COMMENT", ct->tdata); else local_addcomment(vc, "COMMENT", uni("") ); ct = &wtag->tag_lyric; if(ct->tsize)local_addcomment(vc, "LYRIC", ct->tdata); else local_addcomment(vc, "LYRIC", uni("") ); ct = &wtag->tag_bpm; if(ct->tsize)local_addcomment(vc, "BPM", ct->tdata); else local_addcomment(vc, "BPM", uni("") ); ct = &wtag->tag_tracknum; if(ct->tsize)local_addcomment(vc, "TRACKNUMBER", ct->tdata); else local_addcomment(vc, "TRACKNUMBER", uni("") ); outname = (string) malloc(str_size(fname) + (5 * sizeof(letter))); str_cpy(outname, fname); str_cat(outname, uni(".tmp")); of = _wfopen(outname, uni("wb")); if(vcedit_write(state, of) < 0) { fclose(of); fclose(tfile); free_param(param); vcedit_clear(state); free(outname); return 1; } fclose(of); /* done */ vcedit_clear(state); fclose(tfile); free_param(param); _wremove(fname); sys_sleep(0); _wrename(outname, fname); free(outname); return 0; }
__declspec(noreturn) LONG CALLBACK Debug::ExceptionHandler(PEXCEPTION_POINTERS pExs) { Debug::FreeMouse(); Debug::Log("Exception handler fired!\n"); Debug::Log("Exception %X at %p\n", pExs->ExceptionRecord->ExceptionCode, pExs->ExceptionRecord->ExceptionAddress); SetWindowTextW(Game::hWnd, L"Fatal Error - Yuri's Revenge"); // if (IsDebuggerAttached()) return EXCEPTION_CONTINUE_SEARCH; switch(pExs->ExceptionRecord->ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: case EXCEPTION_BREAKPOINT: case EXCEPTION_DATATYPE_MISALIGNMENT: case EXCEPTION_FLT_DENORMAL_OPERAND: case EXCEPTION_FLT_DIVIDE_BY_ZERO: case EXCEPTION_FLT_INEXACT_RESULT: case EXCEPTION_FLT_INVALID_OPERATION: case EXCEPTION_FLT_OVERFLOW: case EXCEPTION_FLT_STACK_CHECK: case EXCEPTION_FLT_UNDERFLOW: case EXCEPTION_ILLEGAL_INSTRUCTION: case EXCEPTION_IN_PAGE_ERROR: case EXCEPTION_INT_DIVIDE_BY_ZERO: case EXCEPTION_INT_OVERFLOW: case EXCEPTION_INVALID_DISPOSITION: case EXCEPTION_NONCONTINUABLE_EXCEPTION: case EXCEPTION_PRIV_INSTRUCTION: case EXCEPTION_SINGLE_STEP: case EXCEPTION_STACK_OVERFLOW: case 0xE06D7363: // exception thrown and not caught { std::wstring path; Debug::PrepareSnapshotDirectory(path); Debug::Flush(); if(Debug::bLog) { std::wstring logCopy = path + L"\\debug.log"; CopyFileW(Debug::LogFileTempName.c_str(), logCopy.c_str(), FALSE); } std::wstring except_file = path + L"\\except.txt"; if(FILE *except = _wfsopen(except_file.c_str(), L"w", _SH_DENYNO)) { #define DELIM "---------------------\n" fprintf(except, "Internal Error encountered!\n"); fprintf(except, DELIM); fprintf(except, VERSION_STRVER); fprintf(except, "\n" DELIM); fprintf(except, "Exception code: %08X at %08p\n", pExs->ExceptionRecord->ExceptionCode, pExs->ExceptionRecord->ExceptionAddress); fprintf(except, "Registers:\n"); PCONTEXT pCtxt = pExs->ContextRecord; fprintf(except, "EIP: %08X\tESP: %08X\tEBP: %08X\n", pCtxt->Eip, pCtxt->Esp, pCtxt->Ebp); fprintf(except, "EAX: %08X\tEBX: %08X\tECX: %08X\n", pCtxt->Eax, pCtxt->Ebx, pCtxt->Ecx); fprintf(except, "EDX: %08X\tESI: %08X\tEDI: %08X\n", pCtxt->Edx, pCtxt->Esi, pCtxt->Edi); fprintf(except, "\nStack dump:\n"); DWORD *ptr = (DWORD *)(pCtxt->Esp); for(int i = 0; i < 0x100; ++i) { fprintf(except, "%08p: %08X\n", ptr, *ptr); ++ptr; } fclose(except); Debug::Log("Exception data has been saved to file:\n%ls\n", except_file.c_str()); } if(MessageBoxW(Game::hWnd, L"Yuri's Revenge has encountered a fatal error!\nWould you like to create a full crash report for the developers?", L"Fatal Error!", MB_YESNO | MB_ICONERROR) == IDYES) { HCURSOR loadCursor = LoadCursor(nullptr, IDC_WAIT); SetClassLong(Game::hWnd, GCL_HCURSOR, (LONG)loadCursor); SetCursor(loadCursor); Debug::Log("Making a memory dump\n"); MINIDUMP_EXCEPTION_INFORMATION expParam; expParam.ThreadId = GetCurrentThreadId(); expParam.ExceptionPointers = pExs; expParam.ClientPointers = FALSE; Debug::FullDump(&expParam, &path); loadCursor = LoadCursor(nullptr, IDC_ARROW); SetClassLong(Game::hWnd, GCL_HCURSOR, (LONG)loadCursor); SetCursor(loadCursor); Debug::FatalError("The cause of this error could not be determined.\r\n" "%s" "A crash dump should have been created in your game's \\debug subfolder.\r\n" "You can submit that to the developers (along with debug.txt and syringe.log)." , Debug::bParserErrorDetected ? "(One or more parser errors have been detected that might be responsible. Check the debug logs.)\r\n" : "" ); } break; } case ERROR_MOD_NOT_FOUND: case ERROR_PROC_NOT_FOUND: Debug::Log("Massive failure: Procedure or module not found!\n"); break; default: Debug::Log("Massive failure: reason unknown, have fun figuring it out\n"); Debug::DumpObj((byte *)pExs->ExceptionRecord, sizeof(*(pExs->ExceptionRecord))); // return EXCEPTION_CONTINUE_SEARCH; break; } Debug::Exit(pExs->ExceptionRecord->ExceptionCode); };
HRESULT CLTDMFileStream::Open(WCHAR * lpFileName,unsigned long dwDesiredAccess) { #ifdef USE_DSTREAM Close(); // make sure file name is not null if (lpFileName == NULL) { return E_FAIL; } // convert file name to regular characters char sFileName[MAX_PATH]; wcstombs( sFileName, lpFileName, MAX_PATH ); // create an item in the OpenQueueMgr m_pOpenQueueItem = g_LTDMDStreamOpenQueueMgr.Create(sFileName); if (m_pOpenQueueItem == NULL) { return E_FAIL; } // open the file if (m_pOpenQueueItem->Open() != LT_OK) { LTDMConOutWarning("LTDirectMusic loader failed to open file %s\n", sFileName); // destroy the OpenQueue item g_LTDMDStreamOpenQueueMgr.Destroy(m_pOpenQueueItem); m_pOpenQueueItem = NULL; return E_FAIL; } // make sure we are at the start of the file // there is no reason to do this since we just opened the file LTDMConOutMsg(5, "CLTDMFileStream::Open FileName=%s\n", sFileName); // we succeed return S_OK; #endif #ifdef USE_REZMGR // convert the file name to regular characters from wide char sFileName[MAX_PATH]; wcstombs( sFileName, lpFileName, MAX_PATH ); // if the loader doesn't exist fail if (m_pLoader == NULL) { LTDMConOutWarning("LTDirectMusic loader failed to open file %s because no directmusic loader exists\n", sFileName); return E_FAIL; } m_pLoader->EnterRezMgrCriticalSection(); // if the rezmgr is not open then fail if (!m_pLoader->GetRezMgr()->IsOpen()) { LTDMConOutWarning("LTDirectMusic loader failed to open file %s because rez file was not open\n", sFileName); m_pLoader->LeaveRezMgrCriticalSection(); return E_FAIL; } // we don't support write access so fail if it was requested if( dwDesiredAccess == GENERIC_WRITE ) { LTDMConOutWarning("LTDirectMusic loader failed to open file %s for writing because writing is not supported\n", sFileName); m_pLoader->LeaveRezMgrCriticalSection(); return DMUS_E_LOADER_FAILEDOPEN; } // get the rez item m_pRezItem = m_pLoader->GetRezMgr()->GetRezFromDosPath(sFileName); // if the item was not found we fail if (m_pRezItem == NULL) { LTDMConOutWarning("LTDirectMusic loader failed to open file %s\n", sFileName); m_pLoader->LeaveRezMgrCriticalSection(); return DMUS_E_LOADER_FAILEDOPEN; } // seek to start of item // m_pRezItem->Seek(0); m_nCurPos = 0; LTDMConOutMsg(5, "CLTDMFileStream::Open FileName=%s\n", sFileName); // we succeed m_pLoader->LeaveRezMgrCriticalSection(); return S_OK; #endif #ifdef USE_FILE Close(); if( dwDesiredAccess == GENERIC_READ ) { if (g_fIsUnicode) { m_pFile = _wfsopen( lpFileName, L"rb", _SH_DENYWR ); } else { char path[MAX_PATH]; wcstombs( path, lpFileName, MAX_PATH ); m_pFile = _fsopen( path, "rb", _SH_DENYWR ); } } else if( dwDesiredAccess == GENERIC_WRITE ) { if (g_fIsUnicode) { m_pFile = _wfsopen( lpFileName, L"wb", _SH_DENYNO ); } else { char path[MAX_PATH]; wcstombs( path, lpFileName, MAX_PATH ); m_pFile = _fsopen( path, "wb", _SH_DENYNO ); } } if (m_pFile == NULL) { return DMUS_E_LOADER_FAILEDOPEN; } return S_OK; #endif }
// Open a file result_t CFile::Open(const CAnyString& pszFileName, uint32_t flags) { Close(); // If create or open mode specified, select depending on file existance if ((flags & ffCreate) && (flags & ffOpen)) { if (DoesFileExist(pszFileName)) flags &= ~ffCreate; else flags &= ~ffOpen; } // Work out fopen flags const wchar_t* pszFlags=NULL; switch (flags & 0x000F) { case ffWrite|ffCreate: pszFlags=L"wb"; break; case ffRead|ffOpen: pszFlags=L"rb"; break; case ffRead|ffWrite|ffCreate: pszFlags=L"wb+"; break; case ffRead|ffWrite|ffOpen: pszFlags=L"rb+"; break; default: return e_invalidarg; } #ifdef _MSC_VER // Work out sharing flags int shareflag=_SH_DENYRW; switch (flags & (ffShareRead|ffShareWrite)) { case ffShareRead|ffShareWrite: shareflag=_SH_DENYNO; break; case ffShareRead: shareflag=_SH_DENYWR; break; case ffShareWrite: shareflag=_SH_DENYRD; break; } // Open file m_pFile=_wfsopen(pszFileName, pszFlags, shareflag); if (!m_pFile) return ResultFromErrno(errno); #else m_pFile=fopen64(pszFileName, w2a(pszFlags)); if (!m_pFile) return ResultFromErrno(errno); #endif // Append? if ((flags & ffAppend) && (flags & ffOpen)) { fseek(m_pFile, 0, SEEK_END); } // Done return s_ok; }
/*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; }
/*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) { char item_path[GF_MAX_PATH]; 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]; #else char path[GF_MAX_PATH], *file; #endif #ifdef WIN32 WIN32_FIND_DATA 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) switch (dir[strlen(dir) - 1]) { case '/': case '\\': sprintf(path, "%s*", dir); break; default: sprintf(path, "%s%c*", dir, GF_PATH_SEPARATOR); break; } #else strcpy(path, dir); if (path[strlen(path)-1] != '/') strcat(path, "/"); #endif #ifdef WIN32 SearchH= FindFirstFile(path, &FindData); if (SearchH == INVALID_HANDLE_VALUE) return GF_IO_ERR; #if defined (_WIN32_WCE) _path[strlen(_path)-1] = 0; #else path[strlen(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 (!strcmp(FindData.cFileName, ".")) goto next; if (!strcmp(FindData.cFileName, "..")) 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) char ext[30]; char *sep = strrchr(FindData.cFileName, '.'); if (!sep) goto next; strcpy(ext, sep+1); strlwr(ext); if (!strstr(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) strcpy(item_path, path); strcat(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 if (enum_dir_fct(cbck, file, item_path, &file_info)) { #ifdef WIN32 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)); } #endif break; } next: #ifdef WIN32 if (!FindNextFile(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) /* 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) /* 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) Bool is_create; is_create = (strchr(mode, 'w') == NULL) ? GF_FALSE : GF_TRUE; if (!is_create) { if (strchr(mode, 'a')) { res = fopen(file_name, "rb"); if (res) { fclose(res); res = fopen(file_name, mode); } } else { res = fopen(file_name, mode); } } if (!res) { const char *str_src; wchar_t *wname; wchar_t *wmode; size_t len; size_t len_res; if (!is_create) { GF_LOG(GF_LOG_INFO, GF_LOG_CORE, ("[Core] Could not open file %s mode %s in UTF-8 mode, trying UTF-16\n", file_name, mode)); } len = (strlen(file_name) + 1)*sizeof(wchar_t); wname = (wchar_t *)gf_malloc(len); str_src = file_name; len_res = gf_utf8_mbstowcs(wname, len, &str_src); if (len_res == -1) { return NULL; } len = (strlen(mode) + 1)*sizeof(wchar_t); wmode = (wchar_t *)gf_malloc(len); str_src = mode; len_res = gf_utf8_mbstowcs(wmode, len, &str_src); if (len_res == -1) { 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; }