bool CNifCopyDlg::CreateFile (CCsvRow* pRow) { CSString* pFilename; CString Buffer; bool Result; /* Get the output filename */ pFilename = pRow->GetAt(m_FilenameColIndex); ExtractPath(Buffer, (const TCHAR *)m_InputNif); Buffer += (const TCHAR *)*pFilename; /* Ignore if the output file exists and we cannot overwrite */ if (!m_OverWriteFiles && FileExists(Buffer)) return (true); /* Update the NIF file textures */ UpdateTextures(pRow); /* Attempt to save the new NIF file */ Result = m_NifFile.Write(Buffer); if (!Result) { ResetInputNif(); return (false); } /* Reset the NIF data */ ResetInputNif(); m_CreatedFiles++; return (true); }
string vmsHttpHelper::ExtractFileName(LPCSTR pszUrl) { string strPath = ExtractPath (pszUrl); LPCSTR psz = strrchr (strPath.c_str (), '/'); assert (psz != NULL); if (!psz) return ""; return psz+1; }
void CURI::Parse(const std::string& uri) { _uri = uri; _scheme = ExtractScheme(); _directories = ExtractDirectories(); _file = ExtractFile(); _extension = ExtractExtension(); _path = ExtractPath(); //_query = ExtractQuery(); }
string vmsHttpHelper::ExtractPathWithoutFileName(LPCSTR pszUrl) { string strPath = ExtractPath (pszUrl); LPSTR psz = const_cast<LPSTR>(strrchr (strPath.c_str (), '/')); assert (psz != NULL); if (!psz) return ""; strPath [psz-strPath.c_str ()] = 0; return strPath; }
//! Create a Text block from a plain text tag. virtual BlockControl* CreateFromTag(const std::string& tag, const RichText::TAG_PARAMS& params, const std::string& content, const boost::shared_ptr<Font>& font, const Clr& color, Flags<TextFormat> format) { // Get the path from the parameters. std::string path = ExtractPath(params); // Create a new image block, basing the path on the root path. return new ImageBlock((m_root_path / FileDlg::StringToPath(path)).string(), X0, Y0, X1, Flags<WndFlag>()); }
//--- Public Interface -------------------------------------------------------------~ static inline url ParseHttpUrl(std::string &in) { url ret; ret.port = -1; ret.protocol = ExtractProtocol(in); ret.search = ExtractSearch(in); ret.path = ExtractPath(in); std::string userpass = ExtractUserpass(in); ret.password = ExtractPassword(userpass); ret.user = userpass; ret.port = ExtractPort(in); ret.host = in; return ret; }
bool EnviroGUI::SaveStructures(bool bAskFilename) { VTLOG1("EnviroGUI::SaveStructures\n"); vtStructureLayer *st_layer = GetCurrentTerrain()->GetStructureLayer(); vtString fname = st_layer->GetFilename(); if (bAskFilename) { // save current directory wxString path = wxGetCwd(); wxString default_file(StartOfFilename(fname), wxConvUTF8); wxString default_dir(ExtractPath(fname, false), wxConvUTF8); EnableContinuousRendering(false); wxFileDialog saveFile(NULL, _("Save Built Structures Data"), default_dir, default_file, FSTRING_VTST, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); bool bResult = (saveFile.ShowModal() == wxID_OK); EnableContinuousRendering(true); if (!bResult) { wxSetWorkingDirectory(path); // restore return false; } wxString str = saveFile.GetPath(); fname = str.mb_str(wxConvUTF8); st_layer->SetFilename(fname); } bool success = false; try { success = st_layer->WriteXML(fname); } catch (xh_io_exception &e) { string str = e.getFormattedMessage(); VTLOG(" Error: %s\n", str.c_str()); wxMessageBox(wxString(str.c_str(), wxConvUTF8), _("Error")); } if (success) st_layer->SetModified(false); return success; }
int MrRipper::SetDirectory(const char *Dir,int OpMode) { char * temp; if (*Dir=='\\' && *(++Dir)==0) { //strcpy(CurDir, "\\"); lstrcpy(FarCurDir, ""); return TRUE; } if (lstrcmp(Dir,"..")==0) { temp = ExtractPath(FarCurDir); lstrcpy(FarCurDir, temp); my_free(temp); return TRUE; } else{ if (lstrlen(FarCurDir)!=0) lstrcat(FarCurDir, "\\"); lstrcat(FarCurDir, Dir); return TRUE; } return FALSE; }
bool EnviroGUI::SaveVegetation(bool bAskFilename) { VTLOG1("EnviroGUI::SaveVegetation\n"); vtTerrain *pTerr = GetCurrentTerrain(); vtVegLayer *vlay = pTerr->GetVegLayer(); if (!vlay) return false; vtString fname = vlay->GetFilename(); if (bAskFilename) { // save current directory wxString path = wxGetCwd(); wxString default_file(StartOfFilename(fname), wxConvUTF8); wxString default_dir(ExtractPath(fname, false), wxConvUTF8); EnableContinuousRendering(false); wxFileDialog saveFile(NULL, _("Save Vegetation Data"), default_dir, default_file, FSTRING_VF, wxFD_SAVE); bool bResult = (saveFile.ShowModal() == wxID_OK); EnableContinuousRendering(true); if (!bResult) { wxSetWorkingDirectory(path); // restore return false; } wxString str = saveFile.GetPath(); fname = str.mb_str(wxConvUTF8); vlay->SetFilename(fname); } bool success = vlay->WriteVF(fname); if (success) vlay->SetModified(false); return true; }
void LocationDlg::OnSave( wxCommandEvent &event ) { wxString default_file, default_dir; // If the locations were previously saved/loaded from a file, use that // file as the default in the Save dialog. vtString previous = m_pSaver->GetFilename(); if (previous != "") { default_file = wxString(StartOfFilename(previous), wxConvUTF8); default_dir = wxString(ExtractPath(previous, false), wxConvUTF8); } wxFileDialog saveFile(NULL, _("Save Locations"), default_dir, default_file, FSTRING_LOC, wxFD_SAVE); bool bResult = (saveFile.ShowModal() == wxID_OK); if (!bResult) return; wxString path = saveFile.GetPath(); vtString upath = (const char *) path.mb_str(wxConvUTF8); if (!m_pSaver->Write(upath)) return; // couldn't write }
//Helper bool SaveAbstractLayer(vtAbstractLayer *alay, bool bAskFilename) { vtFeatureSet *fset = alay->GetFeatureSet(); vtString fname = fset->GetFilename(); if (bAskFilename) { // save current directory wxString path = wxGetCwd(); wxString default_file(StartOfFilename(fname), wxConvUTF8); wxString default_dir(ExtractPath(fname, false), wxConvUTF8); EnableContinuousRendering(false); wxFileDialog saveFile(NULL, _("Save Abstract Data"), default_dir, default_file, FSTRING_SHP, wxFD_SAVE); bool bResult = (saveFile.ShowModal() == wxID_OK); EnableContinuousRendering(true); if (!bResult) { wxSetWorkingDirectory(path); // restore return false; } wxString str = saveFile.GetPath(); fname = str.mb_str(wxConvUTF8); fset->SetFilename(fname); } bool success = fset->SaveToSHP(fname); if (success) alay->SetModified(false); else wxMessageBox(_("Couldn't save layer.")); return success; }
// C:\Program Files SString SharedUtil::GetLaunchPath( void ) { return ExtractPath( GetLaunchPathFilename() ); }
int MrRipper::GetFiles(struct PluginPanelItem *PanelItem, int ItemsNumber, int Move, char *DestPath, int OpMode) { TSaveScreen SS; DWORD StartTime=GetTickCount(); BOOL WaitMessage=FALSE; double Progress1, Progress2; long FullSize,CurSize, ProcessedBytes; int Owervrite = 0; char MyDestPath[MAX_PATH]; char MyDestFile[MAX_PATH]; if (!OpMode & OPM_SILENT){ if (!DestDirPrompt(DestPath)) return -2; } if ((strlen(DestPath)==3)&& (DestPath[1]==':')&& (DestPath[2]=='\\')) DestPath[2] = 0; GetCurrentDirectory(MAX_PATH, MyDestPath); if (!SetCurrentDirectory(DestPath)) return FALSE; SetCurrentDirectory(MyDestPath); FormatFinder FF(PluginPath); for (int i = 0; i<FF.GetFormatCount(); i++) for (int j = 0; j<FF.GetnKnownFormats(i); j++) FF.SetActiveOpt(i, j, GetRegKey(HKEY_CURRENT_USER,"",FF.GetRegPath(i, j), 1)); MakeCopyList(PanelItem, ItemsNumber); int f1, f2; int readed, pos, endpos, getret; if (!bPluginManager){ FullSize = 0; for (int I = 0; I < copyfiles.size(); I++) FullSize += copyfiles[I].FileSize; ProcessedBytes = 0; for (I = 0; I < copyfiles.size(); I++){ if (copyfiles[I].FileName[strlen(copyfiles[I].FileName)-1]=='\\'){ char *c = my_substr(copyfiles[I].FileName, 0, strlen(copyfiles[I].FileName)-1); FSF.sprintf(MyDestPath, "%s\\%s", DestPath, c); my_free(c); CreateDirectory(MyDestPath, NULL); } else { char *d = ExtractPath(copyfiles[I].FileName); if (strlen(d)>0) FSF.sprintf(MyDestPath, "%s\\%s", DestPath, d); else strcpy(MyDestPath, DestPath); my_free(d); d = ExtractName(copyfiles[I].FileName); FSF.sprintf(MyDestFile, "%s", d); my_free(d); char c[MAX_PATH]; FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile); f2 = _open(c, _O_RDONLY|_O_BINARY); if (f2!=-1) { _close(f2); if (Owervrite==3) continue; if (Owervrite == 0||Owervrite == 1) if (!OpMode & OPM_SILENT) Owervrite = OverwritePrompt(MyDestFile); if (Owervrite==-1) break; if (Owervrite==3||Owervrite==1) continue; } if (copyfiles[I].Fmt != FMT_DUMMY) if (FF.GetCanGetFile(copyfiles[I].Fmt, copyfiles[I].Plugin)&&ConvView){ getret = FF.GetFile(copyfiles[I].Plugin, copyfiles[I].Fmt, RipFileName, MyDestFile, MyDestPath, copyfiles[I].StartOffset, copyfiles[I].FileSize, copyfiles[I].UnpSize, OpMode & OPM_SILENT, copyfiles[I].UserData.Data); if (getret == 1){ ProcessedBytes += copyfiles[I].FileSize; WaitMessage=FALSE; if (!OpMode & OPM_SILENT){ if (GetTickCount()-StartTime>500){ if (CheckForKey(VK_ESCAPE)) break; Progress1 = 100.0; Progress2 = ProcessedBytes; Progress2 *= 100; Progress2 /= FullSize; char FileMsg[100], ProgressMsg1[100], ProgressMsg2[100]; FSF.sprintf(FileMsg,GetMsg(MExtracting), MyDestFile); FSF.sprintf(ProgressMsg1,GetMsg(MExtr1), Progress1); FSF.sprintf(ProgressMsg2,GetMsg(MExtr2), Progress2); const char *MsgItems[]={GetMsg(MExtraction),FileMsg, ProgressMsg1, ProgressMsg2}; Info.Message(Info.ModuleNumber,WaitMessage ? FMSG_LEFTALIGN|FMSG_KEEPBACKGROUND:FMSG_LEFTALIGN,NULL,MsgItems,sizeof(MsgItems)/sizeof(MsgItems[0]),0); WaitMessage=TRUE; } } continue; } if (getret == 2){ if (CheckForKey(VK_ESCAPE)) break; continue; } } FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile); f1 = _open(RipFileName, _O_RDONLY|_O_BINARY); _lseek(f1,copyfiles[I].StartOffset,SEEK_SET); f2 = _open(c, _O_CREAT|_O_WRONLY|_O_BINARY); endpos = copyfiles[I].StartOffset+copyfiles[I].FileSize; CurSize = copyfiles[I].FileSize; pos = _tell(f1); while (pos<endpos){ if (!OpMode & OPM_SILENT){ if (GetTickCount()-StartTime>500){ if (CheckForKey(VK_ESCAPE)) break; Progress1 = (pos-copyfiles[I].StartOffset); Progress1 *= 100; Progress1 /= copyfiles[I].FileSize; Progress2 = ProcessedBytes; Progress2 *= 100; Progress2 /= FullSize; char FileMsg[100], ProgressMsg1[100], ProgressMsg2[100]; FSF.sprintf(FileMsg,GetMsg(MExtracting), MyDestFile); FSF.sprintf(ProgressMsg1,GetMsg(MExtr1), Progress1); FSF.sprintf(ProgressMsg2,GetMsg(MExtr2), Progress2); const char *MsgItems[]={GetMsg(MExtraction),FileMsg, ProgressMsg1, ProgressMsg2}; Info.Message(Info.ModuleNumber,WaitMessage ? FMSG_LEFTALIGN|FMSG_KEEPBACKGROUND:FMSG_LEFTALIGN,NULL,MsgItems,sizeof(MsgItems)/sizeof(MsgItems[0]),0); WaitMessage=TRUE; } } readed = _read(f1, buf, BUF_SIZE); pos = _tell(f1); if (pos > endpos) readed = readed - (pos - endpos); _write(f2, buf, readed); ProcessedBytes += readed; pos = _tell(f1); WaitMessage=FALSE; } _close(f2); _close(f1); SetFileAttributes(c, FILE_ATTRIBUTE_ARCHIVE); if (!OpMode & OPM_SILENT) if (CheckForKey(VK_ESCAPE)) break; } } Free_copyfiles(); return TRUE; } else { //For plugin manager ADDPLUGININFO *PI; for (int I = 0; I < copyfiles.size(); I++){ if (copyfiles[I].FileName[strlen(copyfiles[I].FileName)-1]=='\\'){ char *c = my_substr(copyfiles[I].FileName, 0, strlen(copyfiles[I].FileName)-1); FSF.sprintf(MyDestPath, "%s\\%s", DestPath, c); my_free(c); CreateDirectory(MyDestPath, NULL); } else { char *d = ExtractPath(copyfiles[I].FileName); if (strlen(d)>0) FSF.sprintf(MyDestPath, "%s\\%s", DestPath, d); else strcpy(MyDestPath, DestPath); my_free(d); d = ExtractName(copyfiles[I].FileName); FSF.sprintf(MyDestFile, "%s", d); my_free(d); char c[MAX_PATH]; FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile); f2 = _open(c, _O_RDONLY|_O_BINARY); if (f2!=-1) { _close(f2); if (Owervrite==3) continue; if (Owervrite == 0||Owervrite == 1) if (!OpMode & OPM_SILENT) Owervrite = OverwritePrompt(MyDestFile); if (Owervrite==-1) break; if (Owervrite==3||Owervrite==1) continue; } FSF.sprintf(c, "%s\\%s", MyDestPath, MyDestFile); f2 = _open(c, _O_CREAT|_O_WRONLY|_O_BINARY); PI = (ADDPLUGININFO*)copyfiles[I].UserData.Data; FSF.sprintf((char*)buf, GetMsg(MInfoOptString), copyfiles[I].FileName); _write(f2, buf, lstrlen((char*)buf)+1); _write(f2, "\xD\xA\xD\xA", 4); FSF.sprintf((char*)buf, GetMsg(MInfoVer), copyfiles[I].Description); _write(f2, buf, lstrlen((char*)buf)+1); _write(f2, "\xD\xA", 2); char v[30]; Ver2Char(PI->RipVer, v); FSF.sprintf((char*)buf, GetMsg(MInfoRipVer), v); _write(f2, buf, lstrlen((char*)buf)+1); _write(f2, "\xD\xA\xD\xA", 4); FSF.sprintf((char*)buf, GetMsg(MInfoCopyright), PI->Copy); _write(f2, buf, lstrlen((char*)buf)+1); _write(f2, "\xD\xA", 2); FSF.sprintf((char*)buf, GetMsg(MInfoPath), PI->FilePath); _write(f2, buf, lstrlen((char*)buf)+1); _write(f2, "\xD\xA", 2); char *types[8] = {GetMsg(MInfoTypeGraph), GetMsg(MInfoTypeVideo), GetMsg(MInfoTypeSound), GetMsg(MInfoTypePack), GetMsg(MInfoTypeOther), GetMsg(MInfoTypeMusic), GetMsg(MInfoTypeText), GetMsg(MInfoTypeExe)}; FSF.sprintf((char*)buf, GetMsg(MInfoType), types[PI->Type]); _write(f2, buf, lstrlen((char*)buf)+1); _close(f2); SetFileAttributes(c, FILE_ATTRIBUTE_ARCHIVE); if (!OpMode & OPM_SILENT) if (CheckForKey(VK_ESCAPE)) break; } } Free_copyfiles(); //This for refuse reset selection if (!OpMode&OPM_SILENT) return -1; else return TRUE; } Free_copyfiles(); return TRUE; }
HANDLE MrRipper::OpenPlugin(int OpenFrom,int Item) { BOOL Silent=FALSE; bPluginManager = FALSE; if (OpenFrom == OPEN_FINDLIST) Silent=TRUE; if (OpenFrom == OPEN_PLUGINSMENU&&Item==0){ if (!Silent&&Opt.ShowScanDialog){ if (!ScanDialog()) return INVALID_HANDLE_VALUE; } else { FullScan = Opt.FullScan; DelDup = Opt.DelDup; UseSomeOffset = Opt.UseSomeOffset; UseStartScan= Opt.UseStartScan; SkipPack = Opt.SkipPack; EnableGraph = Opt.EnableGraph; EnableVideo = Opt.EnableVideo; EnableSound = Opt.EnableSound; EnableMusic = Opt.EnableMusic; EnableText = Opt.EnableText; EnableExe = Opt.EnableExe; EnablePack = Opt.EnablePack; EnableOther = Opt.EnableOther; } PanelInfo PInfo; Info.Control(INVALID_HANDLE_VALUE,FCTL_GETPANELINFO,&PInfo); if (PInfo.PanelItems[PInfo.CurrentItem].FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) return INVALID_HANDLE_VALUE; FSF.sprintf(RipFileName, "%s\\%s", PInfo.CurDir, PInfo.PanelItems[PInfo.CurrentItem].FindData.cFileName); } if (OpenFrom == OPEN_COMMANDLINE){ char * path = ExtractPath((char*)Item); if (strcmp(path, "")==0){ PanelInfo PInfo; Info.Control(INVALID_HANDLE_VALUE,FCTL_GETPANELINFO,&PInfo); if (PInfo.PanelItems[PInfo.CurrentItem].FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { my_free(path); return INVALID_HANDLE_VALUE; } FSF.sprintf(RipFileName, "%s\\%s", PInfo.CurDir, (char*)Item); } else { FSF.sprintf(RipFileName, "%s", (char*)Item); } my_free(path); } if (OpenFrom == OPEN_PLUGINSMENU&&Item==1) { EnableGraph = Opt.EnableGraph; EnableVideo = Opt.EnableVideo; EnableSound = Opt.EnableSound; EnableMusic = Opt.EnableMusic; EnableText = Opt.EnableText; EnableExe = Opt.EnableExe; EnablePack = Opt.EnablePack; EnableOther = Opt.EnableOther; PanelInfo PInfo; Info.Control(INVALID_HANDLE_VALUE,FCTL_GETPANELINFO,&PInfo); FSF.sprintf(RipFileName, "%s\\%s", PInfo.CurDir, PInfo.PanelItems[PInfo.CurrentItem].FindData.cFileName); bPluginManager = TRUE; } return this; }
/* * struct fs32_opencreate_parms { * PTR16 pfgenflag; * PTR16 pEABuf; * unsigned short attr; * PTR16 pAction; * unsigned short openflag; * unsigned long openmode; * PTR16 psffsd; * PTR16 psffsi; * unsigned short iCurDirEnd; * PTR16 pName; * PTR16 pcdfsd; * PTR16 pcdfsi; * }; */ int FS32ENTRY fs32_opencreate(struct fs32_opencreate_parms *parms) { char *pName; struct cdfsi32 *pcdfsi; union cdfsd32 *pcdfsd; struct sffsi32 *psffsi; union sffsd32 *psffsd; unsigned short *pAction; int rc; struct super_block *sb; struct file *p_file, *dir; UINT32 openmode, DOSmode; UINT32 accessmode; UINT16 newflag, existflag; char component[CCHMAXPATH]; char parent[CCHMAXPATH]; struct inode *inode; struct inode *inode_parent; struct inode *base; char *tmp; ino_t ino_no; psffsi = VDHQueryLin(parms->psffsi); psffsd = VDHQueryLin(parms->psffsd); if (parms->pcdfsi.seg) pcdfsi = VDHQueryLin(parms->pcdfsi); else pcdfsi = 0; if (parms->pcdfsd.seg) pcdfsd = VDHQueryLin(parms->pcdfsd); else pcdfsd = 0; pName = VDHQueryLin(parms->pName); pAction = VDHQueryLin(parms->pAction); if (trace_FS_OPENCREATE) { kernel_printf("FS_OPENCREATE(%s)", pName); } #ifdef FS_TRACE if (parms->ulOpenMode & OPEN_FLAGS_DASD) { fs_log("OPEN_FLAGS_DASD"); } if (parms->ulOpenMode & OPEN_FLAGS_WRITE_THROUGH) { fs_log("OPEN_FLAGS_WRITE_THROUGH"); } if (parms->ulOpenMode & OPEN_FLAGS_FAIL_ON_ERROR) { fs_log("OPEN_FLAGS_FAIL_ON_ERROR"); } if (parms->ulOpenMode & OPEN_FLAGS_NO_CACHE) { fs_log("OPEN_FLAGS_NO_CACHE"); } if (parms->ulOpenMode & OPEN_FLAGS_NOINHERIT) { fs_log("OPEN_FLAGS_NO_INHERIT"); } #endif accessmode = parms->ulOpenMode & OPEN_ACCESS_MASK; if (accessmode == OPEN_ACCESS_READONLY) { #ifdef FS_TRACE fs_log("OPEN_ACCESS_READONLY"); #endif openmode = OPENMODE_READONLY; } if (accessmode == OPEN_ACCESS_WRITEONLY) { #ifdef FS_TRACE fs_log("OPEN_ACCESS_WRITEONLY"); #endif openmode = OPENMODE_WRITEONLY; } if (accessmode == OPEN_ACCESS_READWRITE) { #ifdef FS_TRACE fs_log("OPEN_ACCESS_READWRITE"); #endif openmode = OPENMODE_READWRITE; } #ifdef FS_TRACE if (accessmode == OPEN_ACCESS_EXECUTE) { fs_log("OPEN_ACCESS_EXECUTE"); } #endif newflag = parms->openflag & OPEN_ACTION_NEW_MASK; #ifdef FS_TRACE if (newflag == OPEN_ACTION_FAIL_IF_NEW) { fs_log("OPEN_ACTION_FAIL_IF_NEW"); } if (newflag == OPEN_ACTION_CREATE_IF_NEW) { fs_log("OPEN_ACTION_CREATE_IF_NEW"); } #endif existflag = parms->openflag & OPEN_ACTION_EXIST_MASK; #ifdef FS_TRACE if (existflag == OPEN_ACTION_OPEN_IF_EXISTS) { fs_log("OPEN_ACTION_OPEN_IF_EXISTS"); } if (existflag == OPEN_ACTION_FAIL_IF_EXISTS) { fs_log("OPEN_ACTION_FAIL_IF_EXISTS"); } if (existflag == OPEN_ACTION_REPLACE_IF_EXISTS) { fs_log("OPEN_ACTION_REPLACE_IF_EXISTS"); } #endif if ((!Read_Write) && ((accessmode == OPEN_ACCESS_READWRITE) || (accessmode == OPEN_ACCESS_WRITEONLY))) { fs_log("FS_OPENCREATE() - Write access not enabled"); return ERROR_WRITE_PROTECT; } // // Direct access open of the whole device // if (parms->ulOpenMode & OPEN_FLAGS_DASD) { sb = getvolume(psffsi->sfi_hVPB); kernel_printf("OPEN_FLAGS_DASD"); if ((p_file = _open_by_inode(sb, INODE_DASD, openmode)) == 0) { kernel_printf("FS_OPENCREATE() - couldn't DASD open %s", pName); return ERROR_OPEN_FAILED; } psffsd->f = p_file; psffsi->sfi_tstamp = ST_SCREAT | ST_PCREAT; psffsi->sfi_size = p_file->f_inode->i_size; psffsi->sfi_position = p_file->f_pos; date_unix2dos(p_file->f_inode->i_ctime, &(psffsi->sfi_ctime), &(psffsi->sfi_cdate)); date_unix2dos(p_file->f_inode->i_atime, &(psffsi->sfi_atime), &(psffsi->sfi_adate)); date_unix2dos(p_file->f_inode->i_mtime, &(psffsi->sfi_mtime), &(psffsi->sfi_mdate)); return NO_ERROR; } // // Now that we treated the OPEN_FLAGS_DASD special case, lets treat the general case : // Try to open the file readonly // Success : the file exists // if !S_ISDIR && !S_ISREG => error // if OPEN_ACTION_FAIL_IF_EXISTS set => error // if OPEN_ACTION_OPEN_IF_EXISTS set // <test file attrs> // change the open mode and return OK // if OPEN_ACTION_REPLACE_IF_EXISTS set // OPEN_ACCESS_READONLY or OPEN_ACCESS_EXECUTE set => error // OPEN_ACCESS_READWRITE or OPEN_ACCESS_WRITEONLY set // truncate // change openmode and return // Failure : the file does not exist // OPEN_ACCESS_READONLY or OPEN_ACCESS_EXECUTE set => error // OPEN_ACCESS_READWRITE or OPEN_ACCESS_WRITEONLY set // if OPEN_ACTION_CREATE_IF_NEW set // try to create the file // open the file and return // if OPEN_ACTION_FAIL_IF_NEW set => error rc = ERROR_INVALID_PARAMETER; if (parms->iCurDirEnd != CURDIREND_INVALID) { tmp = pName + parms->iCurDirEnd; if ((pcdfsd->u.p_file) && (pcdfsd->u.p_file->f_magic == FILE_MAGIC)) { base = pcdfsd->u.p_file->f_inode; if (base) { sb = base->i_sb; rc = NO_ERROR; } } } else { sb = getvolume(psffsi->sfi_hVPB); if ((sb) && (sb->s_magic_internal == SUPER_MAGIC)) { tmp = skip_drive(pName); base = sb->s_mounted; if (base) { rc = NO_ERROR; } } } if (rc != NO_ERROR) { return rc; } p_file = open_by_name(base, tmp, openmode); if (p_file) { // The file exists // // If it's not a regular file or a directory we cannot open // if (!S_ISREG(p_file->f_inode->i_mode)) { // kernel_printf("Can't FS_OPENCREATE - %s is not a regular file", pName); if ((rc = vfs_close(p_file)) != NO_ERROR) { fs_err(FUNC_FS_OPENCREATE, FUNC_CLOSE, rc, FILE_TEST_C, __LINE__); return rc; } return ERROR_ACCESS_DENIED; } // // if OPEN_ACTION_FAIL_IF_EXISTS set => error // if (existflag == OPEN_ACTION_FAIL_IF_EXISTS) { #ifdef FS_TRACE fs_log("Can't FS_OPENCREATE() - File exists & OPEN_ACTION_FAIL_IF_EXISTS"); #endif if ((rc = vfs_close(p_file)) != NO_ERROR) { fs_err(FUNC_FS_OPENCREATE, FUNC_CLOSE, rc, FILE_TEST_C, __LINE__); return rc; } return ERROR_FILE_EXISTS; } // // if OPEN_ACTION_OPEN_IF_EXISTS : OK // if (existflag == OPEN_ACTION_OPEN_IF_EXISTS) { *pAction = FILE_EXISTED; } // // if OPEN_ACTION_REPLACE_IF_EXISTS : truncate // if (existflag == OPEN_ACTION_REPLACE_IF_EXISTS) { p_file->f_inode->i_size = psffsi->sfi_size; p_file->f_inode->i_op->truncate(p_file->f_inode); p_file->f_inode->i_dirt = 1; p_file->f_flags = O_TRUNC; *pAction = FILE_TRUNCATED; #if 0 psffsi->sfi_tstamp = ST_PWRITE | ST_SWRITE; #else /* * Time stamping is done by inode routines - Only propagate value. */ psffsi->sfi_tstamp = ST_PWRITE; #endif } } else { // The file doesn't exist ExtractPath(pName, __StackToFlat(parent)); ExtractName(pName, __StackToFlat(component)); // // We try to open the parent dir // if ((dir = open_by_name(sb->s_mounted, Skip_drive(__StackToFlat(parent)), OPENMODE_READONLY)) == 0) { // kernel_printf("FS_OPENCREATE() - The parent directory %s doesn't seem to exist", parent); return ERROR_PATH_NOT_FOUND; } // // The parent dir exists // // // If the file is open for execution : error (it doesn't even exist) // if (accessmode == OPEN_ACCESS_EXECUTE) { #ifdef FS_TRACE fs_log("Can't FS_OPENCREATE() - File doesn't exist & OPEN_ACCESS_EXECUTE"); #endif if ((rc = vfs_close(dir)) != NO_ERROR) { fs_err(FUNC_FS_OPENCREATE, FUNC_CLOSE, rc, FILE_TEST_C, __LINE__); return rc; } return ERROR_FILE_NOT_FOUND; } // // If the file is open for writing or readwrite ... // if ((accessmode == OPEN_ACCESS_READONLY) || (accessmode == OPEN_ACCESS_READWRITE) || (accessmode == OPEN_ACCESS_WRITEONLY)) { if (newflag == OPEN_ACTION_FAIL_IF_NEW) { #ifdef FS_TRACE fs_log("Can't FS_OPENCREATE() - File doesn't exist & OPEN_ACTION_FAIL_IF_NEW"); #endif if ((rc = vfs_close(dir)) != NO_ERROR) { fs_err(FUNC_FS_OPENCREATE, FUNC_CLOSE, rc, FILE_TEST_C, __LINE__); return rc; } return ERROR_OPEN_FAILED; } if (newflag == OPEN_ACTION_CREATE_IF_NEW) { // ino_no = dir->f_inode->i_ino; inode_parent = dir->f_inode; inode_parent->i_count++; if ((rc = vfs_close(dir)) != NO_ERROR) { fs_err(FUNC_FS_OPENCREATE, FUNC_CLOSE, rc, THISFILE, __LINE__); return rc; } // inode_parent = iget(sb, ino_no); inode_parent->i_count++; down(&inode_parent->i_sem); rc = inode_parent->i_op->create(inode_parent, __StackToFlat(component), strlen(component), S_IRWXU | S_IFREG, __StackToFlat(&inode)); up(&inode_parent->i_sem); if (rc) { kernel_printf("Couldn't create %s", pName); iput(inode_parent); return rc; } ino_no = inode->i_ino; iput(inode_parent); iput(inode); if ((p_file = _open_by_inode(sb, ino_no, openmode)) == 0) { kernel_printf("open_by_inode(%lu) failed in FS_OPENCREATE", ino_no); return ERROR_OPEN_FAILED; } p_file->f_inode->i_size = psffsi->sfi_size; p_file->f_inode->i_dirt = 1; p_file->f_flags = O_CREAT; *pAction = FILE_CREATED; #if 0 psffsi->sfi_tstamp = ST_SCREAT | ST_PCREAT | ST_PWRITE | ST_SWRITE; #else /* * Time stamping is done by inode routines - Only propagate value. */ psffsi->sfi_tstamp = ST_PCREAT | ST_PWRITE; #endif } } } psffsd->f = p_file; /* * Time stamping is done by inode routines - Only propagate value. */ #if 0 psffsi->sfi_tstamp |= ST_PREAD | ST_SREAD; #else /* * Time stamping is done by inode routines - Only propagate value. */ psffsi->sfi_tstamp |= ST_PREAD; #endif psffsi->sfi_size = p_file->f_inode->i_size; psffsi->sfi_position = p_file->f_pos; // kernel_printf("date = %u/%u/%u", (pCommon->dateCreate) & 31, (pCommon->dateCreate >> 5) & 15 , (pCommon->dateCreate) >> 9); date_unix2dos(p_file->f_inode->i_ctime, &(psffsi->sfi_ctime), &(psffsi->sfi_cdate)); date_unix2dos(p_file->f_inode->i_atime, &(psffsi->sfi_atime), &(psffsi->sfi_adate)); date_unix2dos(p_file->f_inode->i_mtime, &(psffsi->sfi_mtime), &(psffsi->sfi_mdate)); psffsi->sfi_DOSattr = (unsigned char)Linux_To_DOS_Attrs(p_file->f_inode, __StackToFlat(component)); if (write_through_support) { if ((parms->ulOpenMode & OPEN_FLAGS_WRITE_THROUGH) || (parms->ulOpenMode & OPEN_FLAGS_NO_CACHE)) { p_file->f_flags |= O_SYNC; p_file->f_inode->i_flags |= MS_SYNCHRONOUS; } } return NO_ERROR; }
void FindPath(void *data, unsigned long a, unsigned long b) { if (isInitialSearch) { startX = (int)((stateEstimationUpdate.Easting - costmapXMin) / costmapXUnit); startY = (int)((stateEstimationUpdate.Northing - costmapYMin) / costmapYUnit); //startX = 1940; //startY = 1093; //goalX = 1850; //goalY = 2150; InitialSearch(); } else { #ifdef DEBUGMAP static bool searched = false; if (searched == true) return; searched = true; vector<int> cellsUpdatedXs, cellsUpdatedYs; for (int i = 11; i < 20; ++i) for (int j = 7; j < 17; ++j) { cellsUpdatedXs.push_back(i); cellsUpdatedYs.push_back(j); costmap->set(i, j, 3000, 0); } //for (int i = 2; i < 9; ++i) // for (int j = 5; j < 9; ++j) { // cellsUpdatedXs.push_back(i); // cellsUpdatedYs.push_back(j); // costmap->set(i, j, 3000, 2); // } for (size_t i = 0; i < cellsUpdatedXs.size(); ++i) { int x = cellsUpdatedXs[i]; int y = cellsUpdatedYs[i]; for (int j = 0; j < lattice.update_n; ++j) { //for each corner of updated cell int m = x + lattice.update_dx[j]; int n = y + lattice.update_dy[j]; if (!isInMap(m, n)) return; Node *s = GetOrCreateNode(m, n); if (s != startNode) UpdateRHSandBptr(s); UpdateState(s); } //update itself if (!isInMap(x, y)) return; Node *s = GetOrCreateNode(x, y); if (s != startNode) UpdateRHSandBptr(s); UpdateState(s); } #else if (goalX == -1 || goalY == -1) return; //no new waypoints if (receivedWaypoints) { InitialSearch(); receivedWaypoints = false; return; } if(!receivedNew || !receivedCostMap || !receivedStateEstimation ) return; receivedNew = false; LARGE_INTEGER frequency, start, finish; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); int oldStartX = startX; int oldStartY = startY; startX = (int)((stateEstimationUpdate.Easting - costmapXMin) / costmapXUnit); startY = (int)((stateEstimationUpdate.Northing - costmapYMin) / costmapYUnit); //startX = 1940; //startY = 1093; //spinCounter++; //if (spinCounter >= 20) spinCounter = 0; //if (spinCounter == 0) { // startX = 2000; // startY = 2000; // goalX = 1700; // goalY = 2300; // receivedNew = true; // receivedCostMap = true; // InitialSearch(); // return; //} else if (spinCounter == 10) { // startX = 2000; // startY = 2000; // goalX = 2500; // goalY = 2500; // receivedNew = true; // receivedCostMap = true; // InitialSearch(); // return; //} //Avoid Oscillations int closestX , closestY, closestIndex; int closestDistSquare = LARGE_INT; for (int i = 0; i < 50; ++i) { if (i == prevPath.size()) break; int prevPathX = int((prevPath[i].x - costmapXMin) / costmapXUnit + 0.5f); int prevPathY = int((prevPath[i].y - costmapYMin) / costmapYUnit + 0.5f); int prevDistSquare = (prevPathX - startX) * (prevPathX - startX) + (prevPathY - startY) * (prevPathY - startY); if (prevDistSquare < closestDistSquare) { closestDistSquare = prevDistSquare; closestX = prevPathX; closestY = prevPathY; closestIndex = i; } } if (closestDistSquare < 40) { startX = int((prevPath[max(closestIndex-20, 0)].x - costmapXMin) / costmapXUnit + 0.5f); startY = int((prevPath[max(closestIndex-20, 0)].y - costmapYMin) / costmapYUnit + 0.5f); } // planning failure if we start in an obstacle if ((*costmap)(startX, startY) > 280){ startX = (int)((stateEstimationUpdate.Easting - costmapXMin) / costmapXUnit); startY = (int)((stateEstimationUpdate.Northing - costmapYMin) / costmapYUnit); } if ((*costmap)(startX, startY) > 280 || (*costmap)(goalX, goalY) > 280) { cout << "Planning failed before it began." << endl; return; } if (memory[startX][startY] != 0) { startNode = memory[startX][startY]; } else { startNode = new Node(startX, startY, DOUBLE_INF, DOUBLE_INF); memory[startX][startY] = startNode; usedXs.push_back(startX); usedYs.push_back(startY); } if (memory[oldStartX][oldStartY] != 0 && memory[oldStartX][oldStartY]->used == false) { usedXs.push_back(oldStartX); usedYs.push_back(oldStartY); memory[oldStartX][oldStartY]->used = true; } if (startNode->used == false) { usedXs.push_back(startX); usedYs.push_back(startY); memory[startX][startY]->used = true; } Node::currStart = startNode; #endif //if (Node::epsilon == 1.9) // Node::epsilon = 1.5; //else if (Node::epsilon == 1.5) // Node::epsilon = 1.1; //else if (Node::epsilon == 1.1) // Node::epsilon = 1.05; //else if (Node::epsilon == 1.05) // Node::epsilon = 1.03; //else if (Node::epsilon == 1.03) // Node::epsilon = 1.02; //else if (Node::epsilon == 1.02) // Node::epsilon = 1.01; //else if (Node::epsilon == 1.01) // Node::epsilon = 1.0; //else if (Node::epsilon == 1.0) { // isInitialSearch = true; // //Node::epsilon = 2.5; // return; //} Node::epsilon = 1.0; vector<Node*> oldOpen = open->clear(); for (size_t i = 0; i < oldOpen.size(); ++i ) { oldOpen[i]->recalcKey(); open->add(oldOpen[i]); } for (list<Node*>::iterator it = incons.begin(); it != incons.end(); ++it) { (*it)->inIncons = false; if (!(*it)->inOpen) { (*it)->recalcKey(); open->add(*it); } } incons.clear(); for (list<Node*>::iterator it = closed.begin(); it != closed.end(); ++it) { (*it)->inClosed = false; } closed.clear(); //cout << "Replanning..." << endl; ComputeOrImprovePath(); #ifdef DEBUGMAP print(memory, 0, 0, xMax, yMax); #else QueryPerformanceCounter(&finish); if (planningFailed) { planningFailed = false; cout << "Planning Failed with " << timesExpanded << " times expanded." << endl; double timeelapsed = ((double)(finish.QuadPart - start.QuadPart))/frequency.QuadPart; cout << "Time: " << timeelapsed << "s" << endl; timesExpanded = 0; return; } if (timesExpanded > 0) { cout << timesExpanded << " times expanded, epsilon = " << Node::epsilon << endl; timesExpanded = 0; double timeelapsed = ((double)(finish.QuadPart - start.QuadPart))/frequency.QuadPart; cout << "Time: " << timeelapsed << "s" << endl; } //cout << "Making path..." << endl; ExtractPath(); #endif } }
////////////////////////////////////////////////////////// // // CInstallManager::_ProcessLayoutChecks // // Make sure new reg/dir structure is ok // ////////////////////////////////////////////////////////// SString CInstallManager::_ProcessLayoutChecks ( void ) { // // Validation // // Check data dir exists { if ( !DirectoryExists ( GetMTADataPath () ) ) ShowLayoutError ( "[Data directory not present]" ); // Can't find directory } // Check reg key exists //{ // if ( GetRegistryValue ( "", "Last Install Location" ).empty () ) // ShowLayoutError ( "[Registry key not present]" ); // Can't find reg key //} // Check data dir writable { SString strTestFilePath = PathJoin ( GetMTADataPath (), "testdir", "testfile.txt" ); FileDelete ( strTestFilePath ); RemoveDirectory ( ExtractPath ( strTestFilePath ) ); SString strContent = "test"; if ( !FileSave ( strTestFilePath, strContent ) ) ShowLayoutError ( "[Data directory not writable]" ); // Can't save file FileDelete ( strTestFilePath ); RemoveDirectory ( ExtractPath ( strTestFilePath ) ); } // Check reg key writable { RemoveRegistryKey ( "testkeypath" ); SString strValue = GetTimeString( true, true ); SetRegistryValue ( "testkeypath", "testname", strValue ); SString strValueCheck = GetRegistryValue ( "testkeypath", "testname" ); if ( strValueCheck != strValue ) ShowLayoutError ( "[Registry key not writable]" ); // Can't write reg key RemoveRegistryKey ( "testkeypath" ); } // Check install dir writable { SString strTestFilePath = CalcMTASAPath ( PathJoin ( "mta", "writetest.txt" ) ); FileDelete ( strTestFilePath ); SString strContent = "test"; if ( !FileSave ( strTestFilePath, strContent ) ) ShowLayoutError ( "[Install directory not writable]" ); // Can't save file FileDelete ( strTestFilePath ); } // // Migration // // If news/temp/upcache folder doesn't exist in new, but does in old place, move it { const char* folders[] = { "news", "temp", "upcache" }; for ( uint i = 0 ; i < NUMELMS( folders ) ; i++ ) { SString strSrc = PathJoin ( GetSystemLocalAppDataPath (), "MTA San Andreas " + GetMajorVersionString (), folders[i] ); SString strDest = PathJoin ( GetMTADataPath (), folders[i] ); if ( !DirectoryExists ( strDest ) && DirectoryExists ( strSrc ) ) MoveFile ( strSrc, strDest ); } } // If aero option reg entry doesn't exist in new, but does in old place, move it { if ( GetApplicationSetting ( "aero-enabled" ).empty () ) { SString strLegacyValue = GetVersionRegistryValueLegacy ( GetMajorVersionString (), PathJoin ( "Settings", "general" ), "aero-enabled" ); if ( !strLegacyValue.empty () ) SetApplicationSettingInt ( "aero-enabled", atoi ( strLegacyValue ) ); else SetApplicationSettingInt ( "aero-enabled", 1 ); } } return "ok"; }
/** * @brief TranslateStackTrace * @param stacktrace These are the lines and addresses produced by backtrace_symbols() * Translates the module and address information from backtrace symbols into a vector of StackFrame objects, * each with its own set of entries representing the function call and any inlined functions for that call. */ static void TranslateStackTrace(bool* aiCrash, StackTrace& stacktrace, const int logLevel) { // Extract important data from backtrace_symbols' output bool containsDriverSo = false; // OpenGL lib -> graphic problem bool containsAIInterfaceSo = false; bool containsSkirmishAISo = false; LOG_L(L_DEBUG, "TranslateStackTrace[1]"); for (auto it = stacktrace.begin(); it != stacktrace.end(); ++it) { // prepare for addr2line() const std::string path = ExtractPath(it->symbol); const std::string absPath = CreateAbsolutePath(path); it->path = absPath; it->addr = ExtractAddr(*it); LOG_L(L_DEBUG, "symbol = \"%s\", path = \"%s\", absPath = \"%s\", addr = 0x%lx", it->symbol.c_str(), path.c_str(), absPath.c_str(), it->addr); // check if there are known sources of fail on the stack containsDriverSo = (containsDriverSo || (path.find("libGLcore.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("psb_dri.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("i965_dri.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("fglrx_dri.so") != std::string::npos)); if (!containsAIInterfaceSo && (absPath.find("Interfaces") != std::string::npos)) { containsAIInterfaceSo = true; } if (!containsSkirmishAISo && (absPath.find("Skirmish") != std::string::npos)) { containsSkirmishAISo = true; } } LOG_L(L_DEBUG, "TranslateStackTrace[2]"); // Linux Graphic drivers are known to fail with moderate OpenGL usage if (containsDriverSo) { LOG_I(logLevel, "This stack trace indicates a problem with your graphic card driver. " "Please try upgrading or downgrading it. " "Specifically recommended is the latest driver, and one that is as old as your graphic card. " "Also try lower graphic details and disabling Lua widgets in spring-settings.\n"); } // if stack trace contains AI and AI Interface frames, // it is very likely that the problem lies in the AI only if (containsSkirmishAISo) { containsAIInterfaceSo = false; } if (containsAIInterfaceSo) { LOG_I(logLevel, "This stack trace indicates a problem with an AI Interface library."); if (aiCrash) *aiCrash = true; } if (containsSkirmishAISo) { LOG_I(logLevel, "This stack trace indicates a problem with a Skirmish AI library."); if (aiCrash) *aiCrash = true; } LOG_L(L_DEBUG, "TranslateStackTrace[3]"); // Check if addr2line is available static int addr2line_found = -1; if (addr2line_found < 0) { FILE* cmdOut = popen(ADDR2LINE " --help", "r"); if (cmdOut == NULL) { addr2line_found = false; } else { addr2line_found = true; pclose(cmdOut); } } if (!addr2line_found) { LOG_L(L_WARNING, " addr2line not found!"); return; } LOG_L(L_DEBUG, "TranslateStackTrace[4]"); // Detect BaseMemoryAddresses of all Lib's found in the stacktrace std::map<std::string,uintptr_t> binPath_baseMemAddr; for (auto it = stacktrace.cbegin(); it != stacktrace.cend(); it++) { binPath_baseMemAddr[it->path] = 0; } FindBaseMemoryAddresses(binPath_baseMemAddr); LOG_L(L_DEBUG, "TranslateStackTrace[5]"); // Finally translate it: // This is nested so that the outer loop covers all the entries for one library -- this means fewer addr2line calls. for (auto it = binPath_baseMemAddr.cbegin(); it != binPath_baseMemAddr.cend(); it++) { const std::string& modulePath = it->first; //const uintptr_t& moduleAddr = it->second; const std::string symbolFile = LocateSymbolFile(modulePath); LOG_L(L_DEBUG, "modulePath: %s, symbolFile: %s", modulePath.c_str(), symbolFile.c_str()); std::ostringstream buf; buf << ADDR2LINE << " -i -a -f -C --exe=\"" << symbolFile << "\""; // insert requested addresses that should be translated by addr2line std::queue<size_t> indices; int i=0; for (auto fit = stacktrace.cbegin(); fit != stacktrace.cend(); fit++) { if (fit->path == modulePath) { buf << " " << std::hex << fit->addr; indices.push(i); } i++; } // execute command addr2line, read stdout and write to log-file buf << " 2>/dev/null"; // hide error output from spring's pipe LOG_L(L_DEBUG, "> %s", buf.str().c_str()); FILE* cmdOut = popen(buf.str().c_str(), "r"); if (cmdOut != NULL) { const size_t maxLength = 2048; char line[maxLength]; char* res = fgets_addr2line(line, maxLength, cmdOut); while (res != NULL) { i = indices.front(); indices.pop(); // First scan the address and ensure that it matches the one we were expecting uintptr_t parsedAddr = 0; int matched = sscanf(line, "0x%lx", &parsedAddr); if (matched != 1 || parsedAddr != stacktrace[i].addr) { LOG_L(L_WARNING, "Mismatched address received from addr2line: 0x%lx != 0x%lx", parsedAddr, stacktrace[i].addr); break; } res = fgets_addr2line(line, maxLength, cmdOut); while (res != NULL) { if (line[0] == '0' && line[1] == 'x') { break; // This is the start of a new address } StackFunction entry; entry.inLine = true; // marked false later if the last entry std::string funcname = std::string(line); entry.funcname = funcname.substr(0, funcname.rfind(" (discriminator")); if (fgets_addr2line(line, maxLength, cmdOut) == nullptr) { break; } entry.fileline = std::string(line); stacktrace[i].entries.push_back(entry); res = fgets_addr2line(line, maxLength, cmdOut); } if (!stacktrace[i].entries.empty()) { // Ensure that the last entry in a sequence of results is marked as "not inlined" stacktrace[i].entries.rbegin()->inLine = false; } } pclose(cmdOut); } } LOG_L(L_DEBUG, "TranslateStackTrace[6]"); return; }
//////////////////////////////////////////////////////////////// // // CEffectTemplateImpl::CreateUnderlyingData // // // //////////////////////////////////////////////////////////////// void CEffectTemplateImpl::CreateUnderlyingData ( const SString& strFilename, const SString& strRootPath, SString& strOutStatus, bool bDebug ) { assert ( !m_pD3DEffect ); // Make defines bool bUsesRAWZ = CGraphics::GetSingleton ().GetRenderItemManager ()->GetDepthBufferFormat () == RFORMAT_RAWZ; std::vector < D3DXMACRO > macroList; macroList.push_back ( D3DXMACRO () ); macroList.back ().Name = "IS_DEPTHBUFFER_RAWZ"; macroList.back ().Definition = bUsesRAWZ ? "1" : "0"; macroList.push_back ( D3DXMACRO () ); macroList.back ().Name = NULL; macroList.back ().Definition = NULL; // Compile effect DWORD dwFlags = 0; // D3DXSHADER_PARTIALPRECISION, D3DXSHADER_DEBUG, D3DXFX_NOT_CLONEABLE; if ( bDebug ) dwFlags |= D3DXSHADER_DEBUG; SString strMetaPath = strFilename.Right ( strFilename.length () - strRootPath.length () ); CIncludeManager IncludeManager ( strRootPath, ExtractPath ( strMetaPath ) ); LPD3DXBUFFER pBufferErrors = NULL; HRESULT hr = D3DXCreateEffectFromFile( m_pDevice, ExtractFilename ( strMetaPath ), ¯oList[0], &IncludeManager, dwFlags, NULL, &m_pD3DEffect, &pBufferErrors ); // Handle compile errors strOutStatus = ""; if( pBufferErrors != NULL ) { strOutStatus = SStringX ( (CHAR*)pBufferErrors->GetBufferPointer() ).TrimEnd ( "\n" ); // Error messages sometimes contain the current directory. Remove that here. SString strCurrentDirectory = GetSystemCurrentDirectory(); strOutStatus = strOutStatus.ReplaceI ( strCurrentDirectory + "\\", "" ); strOutStatus = strOutStatus.ReplaceI ( strCurrentDirectory, "" ); } SAFE_RELEASE( pBufferErrors ); if( !m_pD3DEffect ) { if ( strOutStatus.empty () ) strOutStatus = SString ( "[D3DXCreateEffectFromFile failed (%08x)%s]", hr, *IncludeManager.m_strReport ); return; } // Find first valid technique D3DXHANDLE hTechnique = NULL; D3DXEFFECT_DESC EffectDesc; m_pD3DEffect->GetDesc ( &EffectDesc ); for ( uint uiAttempt = 0 ; true ; uiAttempt++ ) { SString strProblemInfo = ""; for ( uint i = 0 ; i < EffectDesc.Techniques ; i++ ) { SString strErrorExtra; D3DXHANDLE hTemp = m_pD3DEffect->GetTechnique ( i ); HRESULT hr = m_pD3DEffect->ValidateTechnique ( hTemp ); if ( SUCCEEDED( hr ) ) { // Check depth buffer rules if ( ValidateDepthBufferUsage ( hTemp, strErrorExtra ) ) { hTechnique = hTemp; break; } } // Update problem string D3DXTECHNIQUE_DESC TechniqueDesc; m_pD3DEffect->GetTechniqueDesc( hTemp, &TechniqueDesc ); strProblemInfo += SString ( "['%s' (%d/%d) failed (%08x)%s]", TechniqueDesc.Name, i, EffectDesc.Techniques, hr, *strErrorExtra ); } // Found valid technique if ( hTechnique ) break; // Error if can't find a valid technique after 2nd attempt if ( uiAttempt > 0 ) { strOutStatus = SString ( "No valid technique; [Techniques:%d %s]%s", EffectDesc.Techniques, *strProblemInfo, *IncludeManager.m_strReport ); SAFE_RELEASE ( m_pD3DEffect ); return; } // Try resetting samplers if 1st attempt failed LPDIRECT3DDEVICE9 pDevice; m_pD3DEffect->GetDevice ( &pDevice ); for ( uint i = 0 ; i < 16 ; i++ ) { pDevice->SetSamplerState ( i, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); pDevice->SetSamplerState ( i, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); pDevice->SetSamplerState ( i, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR ); } } // Set technique m_pD3DEffect->SetTechnique( hTechnique ); // Inform user of technique name D3DXTECHNIQUE_DESC TechniqueDesc; m_pD3DEffect->GetTechniqueDesc( hTechnique, &TechniqueDesc ); strOutStatus = TechniqueDesc.Name; if ( bDebug ) { // Disassemble effect LPD3DXBUFFER pDisassembly = NULL; if ( SUCCEEDED( D3DXDisassembleEffect( m_pD3DEffect, false, &pDisassembly ) ) && pDisassembly ) { LPVOID pData = pDisassembly->GetBufferPointer(); DWORD Size = pDisassembly->GetBufferSize(); if( pData && Size ) { SString strDisassemblyContents; strDisassemblyContents.assign ( (const char*)pData, Size - 1 ); FileSave ( strFilename + ".dis", strDisassemblyContents ); } SAFE_RELEASE( pDisassembly ); } } // Copy MD5s of all loaded files m_FileMD5Map = IncludeManager.m_FileMD5Map; dassert ( !HaveFilesChanged() ); }
// PURPOSE: Installs the service on the local machine void CNTService::CmdInstallService() { char szPath[_MAX_PATH * 2]; char szErr[256]; ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Installing Service."); // Try to determine the name and path of this application. if ( !GetModuleFileName(NULL, szPath, sizeof(szPath)) ) { ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install GetModuleFileName", GetLastErrorText(szErr, sizeof(szErr))); return; } // Try to open the Service Control Manager SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if ( !schSCManager ) { ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install OpenSCManager", GetLastErrorText(szErr, sizeof(szErr))); return; } // Try to create the service char szInternalName[MAX_PATH]; sprintf(szInternalName, GRAY_TITLE " - %s", g_Serv.GetName()); SC_HANDLE schService = CreateService( schSCManager, // handle of the Service Control Manager szInternalName, // Internal name of the service (used when controlling the service using "net start" or "netsvc") szInternalName, // Display name of the service (displayed in the Control Panel | Services page) SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, // Start automatically when the OS starts SERVICE_ERROR_NORMAL, szPath, // Path and filename of this executable NULL, NULL, NULL, NULL, NULL ); if ( !schService ) { ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install CreateService", GetLastErrorText(szErr, sizeof(szErr))); bailout1: CloseServiceHandle(schSCManager); return; } // Configure service - Service description char szDescription[MAX_PATH]; sprintf(szDescription, "SphereServer Service for %s", g_Serv.GetName()); SERVICE_DESCRIPTION sdDescription; sdDescription.lpDescription = szDescription; if ( !ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription) ) { // not critical, so no need to abort the service creation ReportEvent(EVENTLOG_WARNING_TYPE, 0, "Install SetDescription", GetLastErrorText(szErr, sizeof(szErr))); } // Configure service - Restart options SC_ACTION scAction[3]; scAction[0].Type = SC_ACTION_RESTART; // restart process on failure scAction[0].Delay = 10000; // wait 10 seconds before restarting scAction[1].Type = SC_ACTION_RESTART; scAction[1].Delay = 10000; scAction[2].Type = SC_ACTION_RESTART; // wait 2 minutes before restarting the third time scAction[2].Delay = 120000; SERVICE_FAILURE_ACTIONS sfaFailure; sfaFailure.dwResetPeriod = (1 * 60 * 60); // reset failure count after an hour passes with no fails sfaFailure.lpRebootMsg = NULL; // no reboot message sfaFailure.lpCommand = NULL; // no command executed sfaFailure.cActions = COUNTOF(scAction); // number of actions sfaFailure.lpsaActions = scAction; // if ( !ChangeServiceConfig2(schService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfaFailure) ) { // not critical, so no need to abort the service creation ReportEvent(EVENTLOG_WARNING_TYPE, 0, "Install SetAutoRestart", GetLastErrorText(szErr, sizeof(szErr))); } HKEY hKey; char szKey[MAX_PATH]; // Register the application for event logging DWORD dwData; // Try to create the registry key containing information about this application strcpy(szKey, "System\\CurrentControlSet\\Services\\EventLog\\Application\\" GRAY_FILE "svr"); if (RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey)) ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegCreateKey", GetLastErrorText(szErr, sizeof(szErr))); else { // Try to create the registry key containing the name of the EventMessageFile // Replace the name of the exe with the name of the dll in the szPath variable if (RegSetValueEx(hKey, "EventMessageFile", 0, REG_EXPAND_SZ, (LPBYTE) szPath, strlen(szPath) + 1)) ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr))); else { // Try to create the registry key containing the types of errors this application will generate dwData = EVENTLOG_ERROR_TYPE|EVENTLOG_INFORMATION_TYPE|EVENTLOG_WARNING_TYPE; if ( RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (LPBYTE) &dwData, sizeof(DWORD)) ) ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr))); } RegCloseKey(hKey); } // Set the working path for the application sprintf(szKey, "System\\CurrentControlSet\\Services\\" GRAY_TITLE " - %s\\Parameters", g_Serv.GetName()); if ( RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) ) { ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegCreateKey", GetLastErrorText(szErr, sizeof(szErr))); bailout2: CloseServiceHandle(schService); goto bailout1; } ExtractPath(szPath); if ( RegSetValueEx(hKey, "WorkingPath", 0, REG_SZ, (const unsigned char *) &szPath[0], strlen(szPath)) ) ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr))); ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Install OK", g_Serv.GetName()); goto bailout2; }
///////////////////////////////////////////////////////////////////////////////////// // // FUNCTION: main() // ///////////////////////////////////////////////////////////////////////////////////// int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); TCHAR *argv[32]; argv[0] = NULL; int argc = Str_ParseCmds(lpCmdLine, &argv[1], COUNTOF(argv)-1, " \t") + 1; if ( GRAY_GetOSInfo()->dwPlatformId != VER_PLATFORM_WIN32_NT ) { // We are running Win9x - So we are not an NT service. do_not_nt_service: NTWindow_Init(hInstance, lpCmdLine, nCmdShow); int iRet = Sphere_MainEntryPoint(argc, argv); NTWindow_Exit(); TerminateProcess(GetCurrentProcess(), iRet); return iRet; } // We need to find out what the server name is....look it up in the .ini file if ( !g_Cfg.LoadIni(true) ) { // Try to determine the name and path of this application. char szPath[_MAX_PATH]; GetModuleFileName(NULL, szPath, sizeof(szPath)); if ( !szPath[0] ) return -2; ExtractPath(szPath); g_Cfg.LoadIni(false); } if ( !g_Cfg.m_fUseNTService ) // since there is no way to detect how did we start, use config for that goto do_not_nt_service; g_Service.SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 5000); // process the command line arguments... if (( argc > 1 ) && _IS_SWITCH(*argv[1]) ) { if ( argv[1][1] == 'k' ) // service control { if ( argc < 3 ) { printf("Use \"-k command\" with operation to proceed (install/remove)\n"); } else if ( !strcmp(argv[2], "install") ) { g_Service.CmdInstallService(); } else if ( !strcmp(argv[2], "remove") ) { g_Service.CmdRemoveService(); } return 0; } } // If the argument does not match any of the above parameters, the Service Control Manager (SCM) may // be attempting to start the service, so we must call StartServiceCtrlDispatcher. g_Service.ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Starting Service."); g_Service.CmdMainStart(); g_Service.SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0); return -1; }
void BaseConfig2ASEnvironment (register BaseConfig * config, ASEnvironment ** penv) { register ASEnvironment *env = *penv; if (env == NULL) env = make_default_environment (); ExtractPath (config, &(env->module_path), &(env->sound_path), &(env->icon_path), &(env->pixmap_path), &(env->font_path), &(env->cursor_path), NULL, &(env->gtkrc_path), &(env->gtkrc20_path)); set_string (&(env->IconTheme), mystrdup (config->IconTheme)); set_string (&(env->IconThemePath), mystrdup (config->IconThemePath)); set_string (&(env->IconThemeFallback), mystrdup (config->IconThemeFallback)); if (config->desktop_size.flags & WidthValue) env->desk_pages_h = config->desktop_size.width; else env->desk_pages_h = 0; if (config->desktop_size.flags & HeightValue) env->desk_pages_v = config->desktop_size.height; else env->desk_pages_v = 0; env->desk_scale = config->desktop_scale; switch (config->NoModuleNameCollisions % 3) { case 0: env->module_name_collision = ASE_AllowModuleNameCollision; break; case 1: env->module_name_collision = ASE_KillOldModuleOnNameCollision; break; case 2: env->module_name_collision = ASE_KillNewModuleOnNameCollision; break; } set_environment_tool_from_list (env, ASTool_Term, config->term_command, MAX_TOOL_COMMANDS); set_environment_tool_from_list (env, ASTool_Browser, config->browser_command, MAX_TOOL_COMMANDS); set_environment_tool_from_list (env, ASTool_Editor, config->editor_command, MAX_TOOL_COMMANDS); if (get_flags (config->set_flags, BASE_NO_SHARED_MEMORY)) { if (get_flags (config->flags, BASE_NO_SHARED_MEMORY)) set_flags (env->flags, ASE_NoSharedMemory); else clear_flags (env->flags, ASE_NoSharedMemory); } if (get_flags (config->set_flags, BASE_NO_KDEGLOBALS_THEMING)) { if (get_flags (config->flags, BASE_NO_KDEGLOBALS_THEMING)) set_flags (env->flags, ASE_NoKDEGlobalsTheming); else clear_flags (env->flags, ASE_NoKDEGlobalsTheming); } *penv = env; }
static void Stacktrace(bool* aiCrash, pthread_t* hThread = NULL, const char* threadName = NULL, const int logLevel = LOG_LEVEL_ERROR) { #ifndef DEDICATED Watchdog::ClearTimer(); #endif if (threadName != NULL) { LOG_I(logLevel, "Stacktrace (%s) for Spring %s:", threadName, (SpringVersion::GetFull()).c_str()); } else { LOG_I(logLevel, "Stacktrace for Spring %s:", (SpringVersion::GetFull()).c_str()); } bool containsDriverSo = false; // OpenGL lib -> graphic problem bool containedAIInterfaceSo = false; bool containedSkirmishAISo = false; std::vector<std::string> stacktrace; std::vector< std::pair<std::string,uintptr_t> > symbols; // Get untranslated stacktrace symbols { // process and analyse the raw stack trace std::vector<void*> buffer(MAX_STACKTRACE_DEPTH + 2); int numLines; if (hThread && Threading::GetCurrentThread() != *hThread) { LOG_I(logLevel, " (Note: This stacktrace is not 100%% accurate! It just gives an impression.)"); LOG_CLEANUP(); numLines = thread_backtrace(*hThread, &buffer[0], buffer.size()); // stack pointers } else { numLines = backtrace(&buffer[0], buffer.size()); // stack pointers buffer.erase(buffer.begin()); // pop Stacktrace() buffer.erase(buffer.begin()); // pop HandleSignal() numLines -= 2; } numLines = (numLines > MAX_STACKTRACE_DEPTH) ? MAX_STACKTRACE_DEPTH : numLines; char** lines = backtrace_symbols(&buffer[0], numLines); // give them meaningfull names stacktrace.reserve(numLines); for (int l = 0; l < numLines; l++) { stacktrace.push_back(lines[l]); } free(lines); } if (stacktrace.empty()) { LOG_I(logLevel, " Unable to create stacktrace"); return; } // Extract important data from backtrace_symbols' output { for (std::vector<std::string>::iterator it = stacktrace.begin(); it != stacktrace.end(); ++it) { std::pair<std::string,uintptr_t> data; // prepare for TranslateStackTrace() const std::string path = ExtractPath(*it); const std::string absPath = CreateAbsolutePath(path); data.first = absPath; data.second = ExtractAddr(*it); symbols.push_back(data); // check if there are known sources of fail on the stack containsDriverSo = (containsDriverSo || (path.find("libGLcore.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("psb_dri.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("i965_dri.so") != std::string::npos)); containsDriverSo = (containsDriverSo || (path.find("fglrx_dri.so") != std::string::npos)); if (!containedAIInterfaceSo && (absPath.find("Interfaces") != std::string::npos)) { containedAIInterfaceSo = true; } if (!containedSkirmishAISo && (absPath.find("Skirmish") != std::string::npos)) { containedSkirmishAISo = true; } } // Linux Graphic drivers are known to fail with moderate OpenGL usage if (containsDriverSo) { LOG_I(logLevel, "This stack trace indicates a problem with your graphic card driver. " "Please try upgrading or downgrading it. " "Specifically recommended is the latest driver, and one that is as old as your graphic card. " "Also try lower graphic details and disabling Lua widgets in spring-settings.\n"); } // if stack trace contains AI and AI Interface frames, // it is very likely that the problem lies in the AI only if (containedSkirmishAISo) { containedAIInterfaceSo = false; } if (containedAIInterfaceSo) { LOG_I(logLevel, "This stack trace indicates a problem with an AI Interface library."); if (aiCrash) *aiCrash = true; } if (containedSkirmishAISo) { LOG_I(logLevel, "This stack trace indicates a problem with a Skirmish AI library."); if (aiCrash) *aiCrash = true; } LOG_CLEANUP(); } // Translate it TranslateStackTrace(&stacktrace, symbols); // Print out the translated StackTrace unsigned numLine = 0; for (std::vector<std::string>::iterator it = stacktrace.begin(); it != stacktrace.end(); ++it) { LOG_I(logLevel, " <%u> %s", numLine++, it->c_str()); } }
void InitialSearch() { Node::epsilon = 1.0; #ifdef DEBUGMAP goalX = 1; goalY = 1; startX = 39; startY = 29; xMax = 40; yMax = 40; costmapXUnit = 1.0; costmapYUnit = 1.0; costmapXMin = 0; costmapYMin = 0; costmap = new CostMapInt(xMax+1, yMax+1); /* for testing only */ static bool searched = false; if (searched == true) return; searched = true; #else if (!receivedNew || !receivedCostMap || !receivedStateEstimation || !receivedWaypoints) return; receivedNew = false; receivedWaypoints = false; cout << "Starting search in InitialSearch()" << endl; if (!isInMap(goalX, goalY) || !isInMap(startX, startY)) return; // planning failure if we start in an obstacle if ((*costmap)(startX, startY) > 280 || (*costmap)(goalX, goalY) > 280) { cout << "Planning failed before it began in InitialSearch()" << endl; return; } #endif LARGE_INTEGER frequency, start, finish; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); // Initialize memory (first time only), which holds pointers to all nodes created if (!memory) { memory = new Node**[xMax + 1]; Node **curPtr = new Node* [(xMax+1) * (yMax+1)](); //parenthesis initializes pointers to 0 for( int i = 0; i < xMax+1; i++) { *(memory + i) = curPtr; curPtr += yMax + 1; } } else { vector<int>::iterator itX, itY; for (itX = usedXs.begin(), itY = usedYs.begin(); itX != usedXs.end(); ++itX, ++itY) { memory[*itX][*itY]->reset(); } usedXs.resize(0); usedYs.resize(0); } // Initialize OPEN priority queue if first time if (open != 0) open->clear(); else open = new DStarPriorityQueue(costmap); if (closed.size() != 0) closed.clear(); if (incons.size() != 0) incons.clear(); startNode = new Node(startX, startY, DOUBLE_INF, DOUBLE_INF); Node::currStart = startNode; startNode->oldStart = startNode; goalNode = new Node(goalX, goalY, DOUBLE_INF, 0); usedXs.push_back(startX); usedYs.push_back(startY); usedXs.push_back(goalX); usedYs.push_back(goalY); memory[startX][startY] = startNode; memory[goalX][goalY] = goalNode; open->add(goalNode); QueryPerformanceCounter(&finish); double timeelapsed = ((double)(finish.QuadPart - start.QuadPart))/frequency.QuadPart; cout << "Time (initialization): " << timeelapsed << "s" << endl; QueryPerformanceCounter(&start); ComputeOrImprovePath(); #ifdef DEBUGMAP print(memory, 0, 0, xMax, yMax); #endif if (planningFailed) { planningFailed = false; cout << "Planning Failed with " << timesExpanded << " times expanded." << endl; timeelapsed = ((double)(finish.QuadPart - start.QuadPart))/frequency.QuadPart; cout << "Time: " << timeelapsed << "s" << endl; timesExpanded = 0; return; } ExtractPath(); isInitialSearch = false; PauseDisableType pd; pd.Pause = false; pd.Disable = false; Messages::PauseDisable.publish(&pd); QueryPerformanceCounter(&finish); timeelapsed = ((double)(finish.QuadPart - start.QuadPart))/frequency.QuadPart; cout << "Time (initial search): " << timeelapsed << "s\n"; cout << "Times expanded: " << timesExpanded << " with epsilon = " << Node::epsilon << endl; timesExpanded = 0; }