void
debug_memdump()
{
    struct mhdr *h;

    CONSOLE("[M] %s: @@@ memory dump starts\n", timestamp());
    for (h = mem; h; h = h->next) {
#ifdef CCNL_ARDUINO
        sprintf_P(logstr, PSTR("addr %p %5d Bytes, "),
                  (int)((unsigned char *)h + sizeof(struct mhdr)),
                  h->size);
        Serial.print(logstr);
        // remove the "src/../" prefix:
        strcpy_P(logstr, h->fname);
        Serial.print(getBaseName(logstr));
        CONSOLE(":%d @%d.%03d\n", h->lineno,
                int(h->tstamp), int(1000*(h->tstamp - int(h->tstamp))));
#else
        CONSOLE("addr %p %5d Bytes, %s:%d @%s\n",
                (unsigned char *)h + sizeof(struct mhdr),
                h->size, getBaseName(h->fname), h->lineno, h->tstamp);
#endif
    }
    CONSOLE("[M] %s: @@@ memory dump ends\n", timestamp());
}
void InitProgramInfo(char *argv0,
		     char *userdata_subdir, char *userdata_subdir_unix,
		     char *program_title, char *window_title, char *icon_title,
		     char *x11_icon_filename, char *x11_iconmask_filename,
		     char *sdl_icon_filename, char *msdos_cursor_filename,
		     char *cookie_prefix, char *filename_prefix,
		     int program_version)
{
  program.command_basepath = getBasePath(argv0);
  program.command_basename = getBaseName(argv0);

  program.userdata_subdir = userdata_subdir;
  program.userdata_subdir_unix = userdata_subdir_unix;
  program.userdata_path = getUserGameDataDir();

  program.program_title = program_title;
  program.window_title = window_title;
  program.icon_title = icon_title;

  program.x11_icon_filename = x11_icon_filename;
  program.x11_iconmask_filename = x11_iconmask_filename;
  program.sdl_icon_filename = sdl_icon_filename;
  program.msdos_cursor_filename = msdos_cursor_filename;

  program.cookie_prefix = cookie_prefix;
  program.filename_prefix = filename_prefix;

  program.version_major = VERSION_MAJOR(program_version);
  program.version_minor = VERSION_MINOR(program_version);
  program.version_patch = VERSION_PATCH(program_version);

  program.error_filename = getErrorFilename(ERROR_BASENAME);
  program.error_file = stderr;
}
示例#3
0
static HMODULE WINAPI
MyLoadLibraryA(LPCSTR lpLibFileName)
{
    if (VERBOSITY >= 2) {
        debugPrintf("%s(\"%s\")\n", __FUNCTION__, lpLibFileName);
    }

    if (VERBOSITY > 0) {
        const char *szBaseName = getBaseName(lpLibFileName);
        for (unsigned i = 0; i < numReplacements; ++i) {
            if (stricmp(szBaseName, replacements[i].szMatchModule) == 0) {
                debugPrintf("%s(\"%s\")\n", __FUNCTION__, lpLibFileName);
#ifdef __GNUC__
                void *caller = __builtin_return_address (0);

                HMODULE hModule = 0;
                BOOL bRet = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                                              (LPCTSTR)caller,
                                              &hModule);
                assert(bRet);
                char szCaller[256];
                DWORD dwRet = GetModuleFileNameA(hModule, szCaller, sizeof szCaller);
                assert(dwRet);
                debugPrintf("  called from %s\n", szCaller);
#endif
                break;
            }
        }
    }

    return MyLoadLibrary(lpLibFileName);
}
//=====================================================================================================================
std::string logfileName(const std::string& infile)
{
    warn_deprecated("logfileName", "To be removed after Cantera 2.2.");
    std::string logfile = getBaseName(infile);
    logfile += ".log";
    return logfile;
}
示例#5
0
bool CExtUpdate::applySettings(std::string & filename, int mode)
{
	if(!FileHelpers)
		FileHelpers = new CFileHelpers();

	if (mode == MODE_EXPERT)
		imgFilename = (std::string)g_settings.update_dir + "/" + FILESYSTEM_ENCODING_TO_UTF8_STRING(filename);
	else
		imgFilename = FILESYSTEM_ENCODING_TO_UTF8_STRING(filename);

	DBG_TIMER_START()

	std::string oldFilename = imgFilename;
	std::string hostName    = netGetHostname();
	std::string orgPath     = getPathName(imgFilename);
	std::string orgName     = getBaseName(imgFilename);
	orgName                 = getFileName(orgName);
	std::string orgExt      = "." + getFileExt(imgFilename);
	std::string timeStr     = getNowTimeStr("_%Y%m%d_%H%M");
	std::string settingsStr = "+settings";

	if (orgPath != "/tmp") {
		if (g_settings.softupdate_name_mode_apply == CExtUpdate::SOFTUPDATE_NAME_HOSTNAME_TIME)
			imgFilename = orgPath + "/" + hostName + timeStr + settingsStr + orgExt;
		else if (g_settings.softupdate_name_mode_apply == CExtUpdate::SOFTUPDATE_NAME_ORGNAME_TIME)
			imgFilename = orgPath + "/" + orgName + timeStr  + settingsStr + orgExt;
		else
			imgFilename = orgPath + "/" + orgName  + settingsStr + orgExt;
		FileHelpers->copyFile(oldFilename.c_str(), imgFilename.c_str(), 0644);
	}
	else
		imgFilename = oldFilename;
	filename = imgFilename;

	bool ret = applySettings();
	DBG_TIMER_STOP("Image editing")
	if (!ret) {
		if ((mtdRamError != "") && (!flashErrorFlag))
			DisplayErrorMessage(mtdRamError.c_str());

		// error, delete image file
		unlink(imgFilename.c_str());
	}
	else {
		if (mode == MODE_EXPERT) {
			if ((mtdNumber < 3) || (mtdNumber > 4)) {
				const char *err = "invalid mtdNumber\n";
				printf(err);
				DisplayErrorMessage(err);
				WRITE_UPDATE_LOG("ERROR: %s", err);
				return false;
			}
		}
		WRITE_UPDATE_LOG("\n");
		WRITE_UPDATE_LOG("##### Settings taken. #####\n");
		if (mode == MODE_EXPERT)
			CFlashExpert::getInstance()->writemtd(filename, mtdNumber);
	}
	return ret;
}
示例#6
0
void Path::setExtension(const std::string& extension)
{
	_name = getBaseName();
	if (!extension.empty())
	{
		_name.append(".");
		_name.append(extension);
	}
}
示例#7
0
  /*
   *  This is the main routine that reads a ctml file and puts it into
   *  an XML_Node tree
   *
   *  @param node    Root of the tree
   *  @param file    Name of the file
   *  @param debug   Turn on debugging printing
   */
  void get_CTML_Tree(Cantera::XML_Node* rootPtr, const std::string file, const int debug) {

    std::string ff, ext = "";

    // find the input file on the Cantera search path
    std::string inname = findInputFile(file);
#ifdef DEBUG_PATHS
    writelog("Found file: "+inname+"\n");
#endif
    if (debug > 0)
      writelog("Found file: "+inname+"\n");

    if (inname == "") {
      throw CanteraError("get_CTML_Tree", "file "+file+" not found");
    }

    /* 
     * Check whether or not the file is XML. If not, it will be first
     * processed with the preprocessor.
     */
	std::string::size_type idot = inname.rfind('.');
    if (idot != string::npos) {
      ext = inname.substr(idot, inname.size());
    }
    if (ext != ".xml" && ext != ".ctml") {
	try {
          ctml::ct2ctml(inname.c_str(), debug);
        }
        catch (...) {
          writelog("get_CTML_Tree: caught something \n");; 
        }
      string ffull = inname.substr(0,idot) + ".xml";
      ff = "./" + getBaseName(ffull) + ".xml"; 
#ifdef DEBUG_PATHS
      writelogf("ffull name = %s\n", ffull.c_str());
      writelogf("ff name = %s\n", ff.c_str());
#endif
    }
    else {
      ff = inname;
    }
#ifdef DEBUG_PATHS
    writelog("Attempting to parse xml file " + ff + "\n");
#else
    if (debug > 0)
      writelog("Attempting to parse xml file " + ff + "\n");
#endif
    ifstream fin(ff.c_str());
    if (!fin) {
      throw 
	CanteraError("get_CTML_Tree",
		     "XML file " + ff + " not found");
    }
    rootPtr->build(fin);
    fin.close();
  }
示例#8
0
文件: Path.cpp 项目: kutabar/of
Path& Path::makeDirectory()
{
#if defined(POCO_OS_FAMILY_VMS)
	pushDirectory(getBaseName());
#else
	pushDirectory(_name);
#endif
	_name.clear();
	_version.clear();
	return *this;
}
示例#9
0
void ExportDialog::makeExportGroupBox(){
  exportFileGb=new QGroupBox("File");
  baseNLe=new QLineEdit;
  baseNLe->setMinimumWidth(200);
  browseBt=new QPushButton(tr("Browse..."));
  QObject::connect(browseBt,SIGNAL(pressed()),this,SLOT(getBaseName()));
  QLabel *baseNLb=new QLabel(tr("Base Name"));
  QHBoxLayout *hLayout=new QHBoxLayout;
  hLayout->addWidget(baseNLb);
  hLayout->addWidget(baseNLe);
  hLayout->addWidget(browseBt);
  exportFileGb->setLayout(hLayout);
}
示例#10
0
static FARPROC WINAPI
MyGetProcAddress(HMODULE hModule, LPCSTR lpProcName) {

    if (VERBOSITY >= 3) {
        /* XXX this can cause segmentation faults */
        logGetProcAddress(hModule, lpProcName);
    }

    if (!NOOP) {
        char szModule[MAX_PATH];
        DWORD dwRet = GetModuleFileNameA(hModule, szModule, sizeof szModule);
        assert(dwRet);
        const char *szBaseName = getBaseName(szModule);

        ModulesMap::const_iterator modIt;
        modIt = modulesMap.find(szBaseName);
        if (modIt != modulesMap.end()) {
            if (VERBOSITY > 1 && VERBOSITY < 3) {
                logGetProcAddress(hModule, lpProcName);
            }

            if (HIWORD(lpProcName) == 0) {
                debugPrintf("inject: ignoring %s!@%u\n", szBaseName, LOWORD(lpProcName));
                return GetProcAddress(hModule, lpProcName);
            }

            const Module & module = modIt->second;
            const FunctionMap & functionMap = module.functionMap;

            FunctionMap::const_iterator fnIt;
            fnIt = functionMap.find(lpProcName);

            if (fnIt != functionMap.end()) {
                LPVOID pProcAddress = fnIt->second;
                if (VERBOSITY > 0) {
                    debugPrintf("inject: replacing %s!%s\n", szBaseName, lpProcName);
                }
                if (!module.bInternal && pSharedMem) {
                    pSharedMem->bReplaced = TRUE;
                }
                return (FARPROC)pProcAddress;
            } else {
                if (VERBOSITY > 0 && !module.bInternal) {
                    debugPrintf("inject: ignoring %s!%s\n", szBaseName, lpProcName);
                }
            }
        }
    }

    return GetProcAddress(hModule, lpProcName);
}
示例#11
0
static FARPROC WINAPI
MyGetProcAddress(HMODULE hModule, LPCSTR lpProcName) {

    if (VERBOSITY >= 99) {
        /* XXX this can cause segmentation faults */
        debugPrintf("%s(\"%s\")\n", __FUNCTION__, lpProcName);
    }

    assert(hModule != g_hThisModule);
    for (unsigned i = 0; i < numReplacements; ++i) {
        if (hModule == replacements[i].hReplaceModule) {
            if (pSharedMem) {
                pSharedMem->bReplaced = TRUE;
            }
            return GetProcAddress(hModule, lpProcName);
        }
    }

    if (!NOOP) {
        char szModule[256];
        DWORD dwRet = GetModuleFileNameA(hModule, szModule, sizeof szModule);
        assert(dwRet);
        const char *szBaseName = getBaseName(szModule);

        for (unsigned i = 0; i < numReplacements; ++i) {

            if (stricmp(szBaseName, replacements[i].szMatchModule) == 0) {
                if (VERBOSITY > 0) {
                    debugPrintf("  %s(\"%s\", \"%s\")\n", __FUNCTION__, szModule, lpProcName);
                }
                FARPROC pProcAddress = GetProcAddress(replacements[i].hReplaceModule, lpProcName);
                if (pProcAddress) {
                    if (VERBOSITY >= 2) {
                        debugPrintf("      replacing %s!%s\n", szBaseName, lpProcName);
                    }
                    if (pSharedMem) {
                        pSharedMem->bReplaced = TRUE;
                    }
                    return pProcAddress;
                } else {
                    if (VERBOSITY > 0) {
                        debugPrintf("      ignoring %s!%s\n", szBaseName, lpProcName);
                    }
                    break;
                }
            }
        }
    }

    return GetProcAddress(hModule, lpProcName);
}
示例#12
0
 //store a file to the chord network
 void chordService::storeFile(std::string fpath) {
   try {
     std::ifstream is(fpath, std::ifstream::binary);
     if (!is) {
       throw ERRORS::chordFileOpenFail();
     }
     std::string basename = getBaseName(fpath);
     is.seekg(0, is.end);
     int size = is.tellg();
     is.seekg(0, is.beg);
     serviceChordNode->storeKeyValue(basename, is, size);
     is.close();
     printf("file save success!\n");
   } catch (ERRORS::chordFileOpenFail) {
     printf("file does not exist!\n");
   }
 }
示例#13
0
Widget createView (String fileName,
	Widget parent,
	Arg args[],
	int nargs)
{
  Widget result;
  char   widgetName[255];
  Arg    list[32];
  int    err, loop, nlist;
  char   msg[256];

  /* Read in grid to be viewed */
  strcpy(theView.fileName, fileName);
  theView.grid = CreateGMTGrid();
  Trace("Reading grid file...");
  ReadGridFromFile((Grid *)theView.grid, fileName, &err);
  if (err) {
    sprintf(msg, "Unable to read file %s: C error code %d", fileName, err);
    XtError(msg);
  }
  
  /* Create scrolling view widget */
  /* Copy supplied resources */
  for (loop = 0; loop < nargs; loop ++)
    list[loop] = args[loop];
  nlist = nargs;
  XtSetArg(list[nlist], XtNwidth, 640); nlist ++;
  XtSetArg(list[nlist], XtNheight, 480); nlist ++;
  result = XtCreateManagedWidget("view", pannerWidgetClass, parent, list, nlist);

  /* Derive widget name from grid file */
  getBaseName(fileName, widgetName);
  nlist = 0;
  XtSetArg(list[nlist], XtNgrid, theView.grid); nlist ++;
  /* Purists avert eyes...hardcoded dimensions follow */
  XtSetArg(list[nlist], XtNwidth, 640); nlist ++;
  XtSetArg(list[nlist], XtNheight, 480); nlist ++;
  theView.canvas = createTextView(widgetName, result, list, nlist);
  XtSetPannerCanvas(result, theView.canvas);

  /* Register exit action */
  addQuitCallback(saveChanges, &theView);
  
  return result;
}
示例#14
0
std::string H5Group::toString(const unsigned int indentLevel) const
{
    std::ostringstream os;
    std::string indentString = H5Object::getIndentString(indentLevel + 1);
    OpDataCount opdata(false);
    H5Object::count(*this, opdata);

    os << H5Object::getIndentString(indentLevel) << "HDF5 Group" << std::endl
       << indentString << "Filename" << ": " << getFile().getFileName() << std::endl
       << indentString << "Name" << ": " << getBaseName() << std::endl
       << indentString << "Path" << ": " << getCompletePath() << std::endl
       << indentString << "Attributes" << ": [1 x " << getAttributesNumber() << "]" << std::endl
       << indentString << "Groups" << ": [1 x " << opdata.group << "]" << std::endl
       << indentString << "Datasets" << ": [1 x " << opdata.dataset << "]" << std::endl
       << indentString << "Types" << ": [1 x " << opdata.type << "]" << std::endl
       << indentString << "Externals" << ": [1 x " << opdata.external << "]" << std::endl
       << indentString << "Softs" << ": [1 x " << opdata.soft << "]";

    return os.str();
}
示例#15
0
static HMODULE WINAPI
MyLoadLibraryA(LPCSTR lpLibFileName)
{
    HMODULE hModule = LoadLibraryA(lpLibFileName);
    DWORD dwLastError = GetLastError();

    if (VERBOSITY >= 2) {
        debugPrintf("inject: intercepting %s(\"%s\") = 0x%p\n",
                    __FUNCTION__ + 2, lpLibFileName, hModule);
    }

    if (VERBOSITY > 0) {
        const char *szBaseName = getBaseName(lpLibFileName);
        if (isMatchModuleName(szBaseName)) {
            if (VERBOSITY < 2) {
                debugPrintf("inject: intercepting %s(\"%s\")\n", __FUNCTION__, lpLibFileName);
            }
#ifdef __GNUC__
            void *caller = __builtin_return_address (0);

            HMODULE hModule = 0;
            BOOL bRet = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
                                          GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                                          (LPCTSTR)caller,
                                          &hModule);
            assert(bRet);
            char szCaller[MAX_PATH];
            DWORD dwRet = GetModuleFileNameA(hModule, szCaller, sizeof szCaller);
            assert(dwRet);
            debugPrintf("inject: called from %s\n", szCaller);
#endif
        }
    }

    // Hook all new modules (and not just this one, to pick up any dependencies)
    patchAllModules(ACTION_HOOK);

    SetLastError(dwLastError);
    return hModule;
}
示例#16
0
DCirfile *
DCirfile::SetConfigTemplate(const char *sect, const char *setting,
		                        bool link)
{
	DCirfile *bottomIni = SecFile ? SecFile : this;
	bool secfound = false;
	char *startdir =  _getcwd(NewName(1024), 1024);
	char *currdir = startdir;
	char *newdir = NULL;
	int startdrive = _getdrive();
	int currdrive = startdrive;
	int newdrive = 0;

	IniLevel = 0;

	if (!LogEventFunc)
		LastConfigSetting = NewName(setting);

	if (SecFile != NULL) {
		IniFileList.add(SecFile, ++IniLevel);
		IniNameList.add(SecFile->getBaseName(), IniLevel);
		IniChainList.add(SecFile->getFilePath(), IniLevel);
	}
	IniFileList.add(this, ++IniLevel);
	IniNameList.add(getBaseName(), IniLevel);
	IniChainList.add(getFilePath(), IniLevel);

	DCirfile *configTpl = NULL;
	char *configTplName = NULL;

	// SecFile (specific ini) overrides tpl choice in this
	DCirfile *topIni = this;
	secfound = Section(sect);

	if (secfound
	 && Find("Scope"))
		Scope = StrRight();

	if (secfound
	 && !stricmp(setting, "configs")
	 && Find("Document")) {   // insert document chain here
		DCirfile *topdoc = this;
		while (topdoc->Section(sect)) {
			if (!topdoc->Find("Document"))
				break;  // end of chain with no end flag ****
			char *nm = topdoc->StrRight();
			if (!nm)
				break;  // end of chain with no end flag ****
			if (!stricmp(nm, "end")) {
				DeleteName(nm);
				topdoc->ChainEnded = true;
				break;  // end of chain with end flag
			}
			DeleteName(nm);
			if ((configTplName = topdoc->PathRight()) == NULL)
				break;  // end of chain with no end flag ****
			if ((configTpl = new DCirfile(configTplName)) == NULL) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " refers to unopenable ",
					"Document template", " ", NewName(configTplName));
				DeleteName(configTplName);
				configTplName = NULL;
				break;
			}
			if (configTpl->FErr() != fok) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " refers to nonexistent ",
					"Document template", " ", NewName(configTpl->getFilePath()));
				DeleteName(configTplName);
				configTplName = NULL;
				delete configTpl;
				break;  // file not found
			}
			newdir = configTpl->getBasePath();
			if (*(newdir + 1) == ':')
				newdrive = (toupper(*newdir) - 'A') + 1;
			if (newdrive
			 && (currdrive != newdrive))
				_chdrive(currdrive = newdrive);
			if (stricmp(newdir, currdir))
				_chdir(currdir = newdir);

			if (IniNameList(configTpl->getBaseName())) {
				LogEvent(logwarn, 1, topdoc->getFilePath(), " repeats ",
					"Document template", " ", NewName(configTpl->getFilePath()));
				DeleteName(configTplName);
				configTplName = NULL;
				delete configTpl;
				break;  // deja vu, end of the line
			}

			topdoc = configTpl;  // step up
			if (topdoc->Section("Templates")
			 && topdoc->Find("Scope"))
				topdoc->Scope = topdoc->StrRight();
			DeleteName(configTplName);
			configTplName = NULL;
			IniFileList.add(topdoc, ++IniLevel);
			IniNameList.add(topdoc->getBaseName(), IniLevel);
			IniChainList.add(topdoc->getFilePath(), IniLevel);
		}
	}

	if (!secfound
	 || !Find(setting)) {  // check for old setting
		if (!stricmp(setting, "configs")) {
			if (Section("Setup")
			 && Find("ConfigTemplate")) {
				sect = "Setup";
				setting = "ConfigTemplate";
			}
			else if (Section("FDK")
			 && Find("ConfigTemplate")) {
				sect = "FDK";
				setting = "ConfigTemplate";
			}
		}
		else if (!stricmp(setting, "languages")) {
			if (Section("Setup")
			 && Find("LanguageText"))
				sect = "Setup";
				setting = "LanguageText";
		}
		else if (!stricmp(setting, "macros")) {
			if (Section("Macros")
			 && Find("MacroFile")) {
				sect = "Macros";
				setting = "MacroFile";
			}
		}
	}

	while (topIni->Section(sect)) {
		if (!topIni->Find(setting))
			break;  // end of chain with no end flag ****
		char *nm = topIni->StrRight();
		if (!nm)
			break;  // end of chain with no end flag ****
		if (!stricmp(nm, "end")) {
			DeleteName(nm);
			topIni->ChainEnded = true;
			break;  // end of chain with end flag
		}
		DeleteName(nm);
		if ((configTplName = topIni->PathRight()) == NULL)
			break;  // end of chain with no end flag ****
		if ((configTpl = new DCirfile(configTplName)) == NULL) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " refers to unopenable ",
				setting, " ", NewName(configTplName));
			DeleteName(configTplName);
			configTplName = NULL;
			break;  // can't open file
		}
		if (configTpl->FErr() != fok) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " refers to nonexistent ",
				setting, " ", NewName(configTpl->getFilePath()));
			DeleteName(configTplName);
			configTplName = NULL;
			delete configTpl;
			break;  // file not found
		}
		newdir = configTpl->getBasePath();
		if (*(newdir + 1) == ':')
			newdrive = (toupper(*newdir) - 'A') + 1;
		if (newdrive
		 && (currdrive != newdrive))
			_chdrive(currdrive = newdrive);
		if (stricmp(newdir, currdir))
			_chdir(currdir = newdir);

		if (IniNameList(configTpl->getBaseName())) {
			LogEvent(logwarn, 1, topIni->getFilePath(), " repeats ",
				setting, " ", NewName(configTpl->getFilePath()));
			DeleteName(configTplName);
			configTplName = NULL;
			delete configTpl;
			break;  // deja vu, end of the line
		}

		topIni = configTpl;  // step up
		if (topIni->Section("Templates")
		 && topIni->Find("Scope"))
			topIni->Scope = topIni->StrRight();
		DeleteName(configTplName);
		configTplName = NULL;
		IniFileList.add(topIni, ++IniLevel);
		IniNameList.add(topIni->getBaseName(), IniLevel);
		IniChainList.add(topIni->getFilePath(), IniLevel);
	}

	// topIni is now at the top of the chain, and
	// bottomIni is at the bottom, which may be same.
	if (link) {
		DCirfile *ifl = bottomIni;
		DCirfile *ift = NULL;
		for (long ilev = 1; ilev < IniLevel; ilev++) {
			ift = (DCirfile *) IniFileList.find(ilev + 1);
			if (!ift)
				break;
			ift->SetSecFile(ifl);
			ifl = ift;
			//if (ifl == topIni)
			//	break;
		}
	}

	WriteIniChain(setting);

	if (currdrive != startdrive)
		_chdrive(startdrive);
	if (stricmp(startdir, currdir))
		_chdir(startdir);

	if (this != topIni) {
		topIni->IniFileList = IniFileList;
		topIni->IniNameList = IniNameList;
		topIni->IniChainList = IniChainList;
		topIni->IniLevel = IniLevel;
	}

	return topIni;
}
示例#17
0
void
NowBlueprint::visitDumpFeatures(const search::fef::IIndexEnvironment &,
                                search::fef::IDumpFeatureVisitor &visitor) const
{
    visitor.visitDumpFeature(getBaseName());
}
示例#18
0
std::string FileInfo::getBaseName()
{
  return getBaseName(absolutePath);
}
示例#19
0
static void
patchModule(HMODULE hModule,
            const char *szModule,
            Action action)
{
    /* Never patch this module */
    if (hModule == g_hThisModule) {
        return;
    }

    /* Never patch our hook module */
    if (hModule == g_hHookModule) {
        return;
    }

    /* Hook modules only once */
    if (action == ACTION_HOOK) {
        std::pair< std::set<HMODULE>::iterator, bool > ret;
        EnterCriticalSection(&Mutex);
        ret = g_hHookedModules.insert(hModule);
        LeaveCriticalSection(&Mutex);
        if (!ret.second) {
            return;
        }
    }

    const char *szBaseName = getBaseName(szModule);

    /* Don't hook our replacement modules to avoid tracing internal APIs */
    /* XXX: is this really a good idea? */
    if (isMatchModuleName(szBaseName)) {
        return;
    }

    /* Leave these modules alone */
    if (stricmp(szBaseName, "kernel32.dll") == 0 ||
        stricmp(szBaseName, "ConEmuHk.dll") == 0) {
        return;
    }

    if (VERBOSITY > 0) {
        debugPrintf("inject: found module %s\n", szModule);
    }

    PIMAGE_IMPORT_DESCRIPTOR pImportDescriptor = getFirstImportDescriptor(hModule, szModule);
    if (pImportDescriptor) {
        while (pImportDescriptor->FirstThunk) {

            patchDescriptor(hModule, szModule, pImportDescriptor, action);

            ++pImportDescriptor;
        }
    }

    PImgDelayDescr pDelayDescriptor = getDelayImportDescriptor(hModule, szModule);
    if (pDelayDescriptor) {
        while (pDelayDescriptor->rvaDLLName) {
            if (VERBOSITY > 1) {
                const char* szName = getDescriptorName(hModule, pDelayDescriptor);
                debugPrintf("inject: found %sdelay-load import entry for module %s\n",
                            pDelayDescriptor->grAttrs & dlattrRva ? "" : "old-style ",
                            szName);
            }

            patchDescriptor(hModule, szModule, pDelayDescriptor, action);

            ++pDelayDescriptor;
        }
    }
}
示例#20
0
bool FailableMemoryAllocator::isFailedLocation(LocationToFailAlloc* locationFail, const char* allocFile, int allocLine)
{
    SimpleString allocBaseName = getBaseName(allocFile);
    SimpleString failBaseName = getBaseName(locationFail->file);
    return allocBaseName == failBaseName && allocLine == locationFail->line;
}
示例#21
0
EXTERN_C BOOL WINAPI
DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    const char *szNewDllName = NULL;
    const char *szNewDllBaseName;

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        g_hThisModule = hinstDLL;

        /*
         * Calling LoadLibrary inside DllMain is strongly discouraged.  But it
         * works quite well, provided that the loaded DLL does not require or do
         * anything special in its DllMain, which seems to be the general case.
         *
         * See also:
         * - http://stackoverflow.com/questions/4370812/calling-loadlibrary-from-dllmain
         * - http://msdn.microsoft.com/en-us/library/ms682583
         */

        if (!USE_SHARED_MEM) {
            szNewDllName = getenv("INJECT_DLL");
            if (!szNewDllName) {
                debugPrintf("inject: warning: INJECT_DLL not set\n");
                return FALSE;
            }
        } else {
            SharedMem *pSharedMem = OpenSharedMemory(NULL);
            if (!pSharedMem) {
                debugPrintf("inject: error: failed to open shared memory\n");
                return FALSE;
            }

            VERBOSITY = pSharedMem->cVerbosity;

            static char szSharedMemCopy[MAX_PATH];
            strncpy(szSharedMemCopy, pSharedMem->szDllName, _countof(szSharedMemCopy) - 1);
            szSharedMemCopy[_countof(szSharedMemCopy) - 1] = '\0';

            szNewDllName = szSharedMemCopy;
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_ATTACH\n");
        }

        if (VERBOSITY > 0) {
            char szProcess[MAX_PATH];
            GetModuleFileNameA(NULL, szProcess, sizeof szProcess);
            debugPrintf("inject: attached to process %s\n", szProcess);
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: loading %s\n", szNewDllName);
        }

        g_hHookModule = LoadLibraryA(szNewDllName);
        if (!g_hHookModule) {
            debugPrintf("inject: warning: failed to load %s\n", szNewDllName);
            return FALSE;
        }

        // Ensure we use kernel32.dll's CreateProcessAsUserW, and not advapi32.dll's.
        {
            HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
            assert(hKernel32);
            pfnCreateProcessAsUserW = (PFNCREATEPROCESSASUSERW)GetProcAddress(hKernel32, "CreateProcessAsUserW");
            assert(pfnCreateProcessAsUserW);
        }

        /*
         * Hook kernel32.dll functions, and its respective Windows API Set.
         *
         * http://msdn.microsoft.com/en-us/library/dn505783.aspx (Windows 8.1)
         * http://msdn.microsoft.com/en-us/library/hh802935.aspx (Windows 8)
         */

        registerLibraryLoaderHooks("kernel32.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-1.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-2-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-1.dll");

        registerProcessThreadsHooks("kernel32.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-0.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-1.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-2.dll");

        szNewDllBaseName = getBaseName(szNewDllName);
        if (stricmp(szNewDllBaseName, "dxgitrace.dll") == 0) {
            registerModuleHooks("dxgi.dll",    g_hHookModule);
            registerModuleHooks("d3d10.dll",   g_hHookModule);
            registerModuleHooks("d3d10_1.dll", g_hHookModule);
            registerModuleHooks("d3d11.dll",   g_hHookModule);
            registerModuleHooks("d3d9.dll",    g_hHookModule); // for D3DPERF_*
        } else if (stricmp(szNewDllBaseName, "d3d9.dll") == 0) {
            registerModuleHooks("d3d9.dll",    g_hHookModule);
            registerModuleHooks("dxva2.dll",   g_hHookModule);
        } else if (stricmp(szNewDllBaseName, "d2d1trace.dll") == 0) {
            registerModuleHooks("d2d1.dll",    g_hHookModule);
            registerModuleHooks("dwrite.dll",  g_hHookModule);
        } else {
            registerModuleHooks(szNewDllBaseName, g_hHookModule);
        }

        dumpRegisteredHooks();

        patchAllModules(ACTION_HOOK);
        break;

    case DLL_THREAD_ATTACH:
        break;

    case DLL_THREAD_DETACH:
        break;

    case DLL_PROCESS_DETACH:
        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_DETACH\n");
        }

        assert(!lpvReserved);

        patchAllModules(ACTION_UNHOOK);

        if (g_hHookModule) {
            FreeLibrary(g_hHookModule);
        }
        break;
    }
    return TRUE;
}
示例#22
0
U_NAMESPACE_BEGIN

UBool
Locale::isRightToLeft() const {
    return uloc_isRightToLeft(getBaseName());
}
示例#23
0
int
main(int argc, char *argv[])
{
    if (argc < 3) {
        fprintf(stderr,
                "usage:\n"
                "  inject <dllname.dll> <command> [args] ...\n"
                "  inject <dllname.dll> <process-id>\n"
                "  inject <dllname.dll> !<process-name>\n"
        );
        return 1;
    }

    BOOL bAttach = FALSE;
    DWORD dwProcessId = ~0;
    if (isNumber(argv[2])) {
        dwProcessId = atol(argv[2]);
        bAttach = TRUE;
    } else if (argv[2][0] == '!') {
        const char *szProcessName = &argv[2][1];
        if (!getProcessIdByName(szProcessName, &dwProcessId)) {
            fprintf(stderr, "error: failed to find process %s\n", szProcessName);
            return 1;
        }
        bAttach = TRUE;
        fprintf(stderr, "dwProcessId = %lu\n", dwProcessId);
    }

    HANDLE hSemaphore = NULL;
    const char *szDll = argv[1];
    if (!USE_SHARED_MEM) {
        SetEnvironmentVariableA("INJECT_DLL", szDll);
    } else {
        hSemaphore = CreateSemaphore(NULL, 1, 1, "inject_semaphore");
        if (hSemaphore == NULL) {
            fprintf(stderr, "error: failed to create semaphore\n");
            return 1;
        }

        DWORD dwWait = WaitForSingleObject(hSemaphore, 0);
        if (dwWait == WAIT_TIMEOUT) {
            fprintf(stderr, "info: waiting for another inject instance to finish\n");
            dwWait = WaitForSingleObject(hSemaphore, INFINITE);
        }
        if (dwWait != WAIT_OBJECT_0) {
            fprintf(stderr, "error: failed to enter semaphore gate\n");
            return 1;
        }

        SetSharedMem(szDll);
    }

    BOOL bAttachDwm = FALSE;
    PROCESS_INFORMATION processInfo;
    HANDLE hProcess;
    if (bAttach) {
        BOOL bRet;
        HANDLE hToken   = NULL;
        bRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken);
        if (!bRet) {
            fprintf(stderr, "error: OpenProcessToken returned %u\n", (unsigned)bRet);
            return 1;
        }

        LUID Luid;
        bRet = LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Luid);
        if (!bRet) {
            fprintf(stderr, "error: LookupPrivilegeValue returned %u\n", (unsigned)bRet);
            return 1;
        }

        TOKEN_PRIVILEGES tp;
        tp.PrivilegeCount = 1;
        tp.Privileges[0].Luid = Luid;
        tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
        bRet = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof tp, NULL, NULL);
        if (!bRet) {
            fprintf(stderr, "error: AdjustTokenPrivileges returned %u\n", (unsigned)bRet);
            return 1;
        }

        DWORD dwDesiredAccess =
            PROCESS_CREATE_THREAD |
            PROCESS_QUERY_INFORMATION |
            PROCESS_QUERY_LIMITED_INFORMATION |
            PROCESS_VM_OPERATION |
            PROCESS_VM_WRITE |
            PROCESS_VM_READ |
            PROCESS_TERMINATE;
        hProcess = OpenProcess(
            dwDesiredAccess,
            FALSE /* bInheritHandle */,
            dwProcessId);
        if (!hProcess) {
            logLastError("failed to open process");
            return 1;
        }

        char szProcess[MAX_PATH];
        DWORD dwRet = GetModuleFileNameEx(hProcess, 0, szProcess, sizeof szProcess);
        assert(dwRet);
        if (dwRet &&
            stricmp(getBaseName(szProcess), "dwm.exe") == 0) {
            bAttachDwm = TRUE;
        }
    } else {
        std::string commandLine;
        char sep = 0;
        for (int i = 2; i < argc; ++i) {
            const char *arg = argv[i];

            if (sep) {
                commandLine.push_back(sep);
            }

            if (needsQuote(arg)) {
                quoteArg(commandLine, arg);
            } else {
                commandLine.append(arg);
            }

            sep = ' ';
        }

        STARTUPINFO startupInfo;
        memset(&startupInfo, 0, sizeof startupInfo);
        startupInfo.cb = sizeof startupInfo;

        // Create the process in suspended state
        if (!CreateProcessA(
               NULL,
               const_cast<char *>(commandLine.c_str()), // only modified by CreateProcessW
               0, // process attributes
               0, // thread attributes
               TRUE, // inherit handles
               CREATE_SUSPENDED,
               NULL, // environment
               NULL, // current directory
               &startupInfo,
               &processInfo)) {
            DWORD dwLastError = GetLastError();
            fprintf(stderr, "error: failed to execute %s (%lu)\n",
                    commandLine.c_str(), dwLastError);
            if (dwLastError == ERROR_ELEVATION_REQUIRED) {
                fprintf(stderr, "error: target program requires elevated priviledges and must be started from an Administrator Command Prompt, or UAC must be disabled\n");
            }
            return 1;
        }

        hProcess = processInfo.hProcess;
    }

    /*
     * XXX: Mixed architecture don't quite work.  See also
     * http://www.corsix.org/content/dll-injection-and-wow64
     */
    {
        typedef BOOL (WINAPI *PFNISWOW64PROCESS)(HANDLE, PBOOL);
        PFNISWOW64PROCESS pfnIsWow64Process;
        pfnIsWow64Process = (PFNISWOW64PROCESS)
            GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
        if (pfnIsWow64Process) {
            BOOL isParentWow64 = FALSE;
            BOOL isChildWow64 = FALSE;
            if (pfnIsWow64Process(GetCurrentProcess(), &isParentWow64) &&
                pfnIsWow64Process(hProcess, &isChildWow64) &&
                isParentWow64 != isChildWow64) {
                fprintf(stderr, "error: binaries mismatch: you need to use the "
#ifdef _WIN64
                        "32-bits"
#else
                        "64-bits"
#endif
                        " apitrace binaries to trace this application\n");
                TerminateProcess(hProcess, 1);
                return 1;
            }
        }
    }

    if (bAttachDwm && IsWindows8OrGreater()) {
        // Switch to Microsoft Basic Display Driver before injecting, so that
        // we don't trace with it.
        devconDisable(DEVCON_CLASS_DISPLAY);
        Sleep(1000);
    }

    const char *szDllName;
    szDllName = "injectee.dll";

    char szDllPath[MAX_PATH];
    GetModuleFileNameA(NULL, szDllPath, sizeof szDllPath);
    getDirName(szDllPath);
    strncat(szDllPath, szDllName, sizeof szDllPath - strlen(szDllPath) - 1);

#if 1
    if (!injectDll(hProcess, szDllPath)) {
        TerminateProcess(hProcess, 1);
        return 1;
    }
#endif

    DWORD exitCode;

    if (bAttach) {
        if (bAttachDwm) {
            restartDwmComposition(hProcess);
        }

        exitCode = 0;
    } else {
        // Start main process thread
        ResumeThread(processInfo.hThread);

        // Wait for it to finish
        WaitForSingleObject(hProcess, INFINITE);

        if (pSharedMem && !pSharedMem->bReplaced) {
            fprintf(stderr, "warning: %s was never used: application probably does not use this API\n", szDll);
        }

        exitCode = ~0;
        GetExitCodeProcess(hProcess, &exitCode);

        CloseHandle(processInfo.hThread);
    }

    CloseHandle(hProcess);

    if (hSemaphore) {
        ReleaseSemaphore(hSemaphore, 1, NULL);
        CloseHandle(hSemaphore);
    }

    return (int)exitCode;
}
bool C_visu_IO::readFiber(string fileNameFib)
{
    //file names
    string headerFile = getBaseName(fileNameFib) + ".fibHDR";
    string sourceFile = getBaseName(fileNameFib) + ".fibSRC";

    //
    fstream fhdr;
    fhdr.open (headerFile.data(), ifstream::in | ifstream::binary ); //
    if(fhdr.is_open())
    {
        //
        unsigned long nbBundlePoints = 0;

        //get number of data = nb_bundle+1
        fhdr.seekg (0, ios::end);
        unsigned long length = fhdr.tellg();
        fhdr.seekg (0, ios::beg);
        unsigned long N = (unsigned long) (length/sizeof(unsigned long));

        unsigned long* hdrData = new unsigned long[N];
        fhdr.read ((char*) hdrData,length);
        if(fhdr.bad())
        {
            fhdr.close();
            delete hdrData;
            return false;
        }else{

            data->Fib = new CtlCtlStruct(hdrData[0]);
            //data->Fib->fibers = new CtlStruct[data->Fib->N];// done in constructor
            for(unsigned long o=1 ; o< hdrData[0]+1 ; o++)
            {
                (data->Fib->fibers)[o-1].allocateArray(hdrData[o]);
                nbBundlePoints += hdrData[o];
            }
        }
        fhdr.close();
        if(nbBundlePoints==0)
        {
            return false;
        }


        //data file
        fstream fsrc;
        fsrc.open (sourceFile.data(), ifstream::in | ifstream::binary ); //
        if(fsrc.is_open())
        {
            //get length of file
            unsigned long lengthB = nbBundlePoints*sizeof(BundlePoint);
            BundlePoint* srcData = new BundlePoint[nbBundlePoints];
            fsrc.read ((char*) srcData,lengthB);
            if(fsrc.bad())
            {
                fsrc.close();
                delete srcData;
                return false;
            }else{
                //for each bundle
                unsigned long offset = 0;
                for(unsigned long o=1 ; o< hdrData[0]+1 ; o++)
                {
                    for(unsigned long g=0 ; g<hdrData[o] ; g++)
                    {
                        (data->Fib->fibers)[o-1].elts[3*g] = srcData[g+offset].x;
                        (data->Fib->fibers)[o-1].elts[3*g+1] = srcData[g+offset].y;
                        (data->Fib->fibers)[o-1].elts[3*g+2] = srcData[g+offset].z;
                        (data->Fib->fibers)[o-1].idx[g] = srcData[g+offset].idx;
                    }
                    offset += hdrData[o];
                }
            }
            delete srcData;
            delete hdrData;
            fsrc.close();


        }else{
            return false;
        }


    }
    else
    {
        return false;
    }
    return true;
}
示例#25
0
文件: man2.c 项目: GnoConsortium/gno
static LC_StringArray_t
buildManList(char *suffix, char *name) {
   static char buffer1[FILENAME_MAX];
   static char buffer2[FILENAME_MAX];
   DIR *directory;
   struct dirent *entry;
   LC_StringArray_t list1, list2;
   size_t len;
   int i, j, k;
   char *p, *fn, *L1, *L2;

   /* initialization */
   list1 = LC_StringArrayNew();
   list2 = LC_StringArrayNew();

#ifdef DEBUG
   /* sanity check on arguments */
   if(MAX(strlen(manstr),strlen(catstr)) + strlen(suffix) >= FILENAME_MAX) {
      fprintf(stderr,"internal error: buffer overflow at line %d of %s\n",
              __LINE__,__FILE__);
   }
#endif

   /*
    * look in man subdirectory
    */
   strcpy(buffer1,manstr);
   strcat(buffer1,suffix);
   if ((directory = opendir(buffer1)) != NULL) {
      while ((entry = readdir(directory)) != (struct dirent *) NULL) {

         /* skip if no match */
         len = strlen(name);
         if (strncasecmp(entry->d_name,name,len) ||
             (entry->d_name[len] != '.')) continue;

         if (strlen(manstr) + strlen(suffix) + strlen(entry->d_name) +
             strlen(suffix) + 1 >= FILENAME_MAX) {
       		errx(1, "internal error: buffer overflow at line %s:%d\n",
                     __FILE__, __LINE__);
         }
         sprintf(buffer1,"%s%s:%s",manstr,suffix,entry->d_name);

         /* look for "links" to aroff files. (what a kludge) */
         if ((buffer1[3] != 'l') &&
             (strcasecmp(".l",&buffer1[strlen(buffer1)-2])==0)) {
            FILE *linkptr;
            char *tp;

            /* dereference the "link" */
            if ((linkptr = fopen(buffer1,"r")) == NULL) {
               fprintf(stderr,"couldn't open %s\n",buffer1);
            } else if (fgets(buffer2,FILENAME_MAX,linkptr)==NULL) {
               fprintf(stderr,"couldn't read %s\n",buffer1);
            } else {

               /* drop trailing space and newline */
               tp = buffer2 + strlen(buffer2) -1;
               while ((tp>=buffer2) && (isspace(*tp) || *tp == '\n')) {
                  *tp = '\0';
                  tp--;
               }
               fclose(linkptr);

               if (access(buffer2,R_OK) == 0) {
		  LC_StringArrayAdd(list1, buffer2);
               }
            }                                   
         } else {
            /* not a .l "link"; a normal file */
	    LC_StringArrayAdd(list1, buffer1);
         }
      }              
      closedir(directory);
   }

   if (!t_flag) {
      /*
       * look in cat subdirectory
       */
      strcpy(buffer1,catstr);
      strcat(buffer1,suffix);
      if ((directory = opendir(buffer1)) != NULL) {
         while ((entry = readdir(directory)) != (struct dirent *) NULL) {

            /* skip if no match */
            len = strlen(name);
            if (strncasecmp(entry->d_name,name,len) ||
                (entry->d_name[len] != '.')) continue;

            if (strlen(catstr) + strlen(suffix) + strlen(entry->d_name) +
                strlen(suffix) + 1 >= FILENAME_MAX) {
               fprintf(stderr,"internal error: buffer overflow at line %d of %s\n",
                       __LINE__,__FILE__);
            }
            sprintf(buffer1,"%s%s:%s",catstr,suffix,entry->d_name);
	    LC_StringArrayAdd(list2, buffer1);
         }              
         closedir(directory);
      }
   }

   /*
    * eliminate files common to both lists
    */
   len = strlen(suffix);
   for(i=0; i< list1->lc_used; i++) {
      L1 = (list1->lc_vec)[i];
      for (j=0; j< list2->lc_used; j++) {
         L2 = (list2->lc_vec)[j];

         getBaseName(buffer1, L1);
         getBaseName(buffer2, L2);

#ifdef DEBUG
         if ((strlen(buffer1) < len + 5) ||
             (strlen(buffer2) < len + 5)) {
		err(1, "internal error at line %d of %s\n", __LINE__, __FILE__);
         }
#endif
         /* match after the respective "manXX/" and "catXX/" */
         if (strcasecmp(&buffer1[len+4],&buffer2[len+4]) == 0 ) {
         
            p = newerFile(L1,L2);
            if (p == L1) {
		LC_StringArrayDelete(list2, L2);
		--j;
            } else if (p == (list2->lc_vec)[j]) {
		LC_StringArrayDelete(list1, L1);
		--i;
		break;
            } else {
	       err(1, "internal error at %s:%d (newerFile failed)",
		   __FILE__, __LINE__);
            }
         }  /* endif */
      }     /* endfor */
   }        /* endfor */

   /*
    * combine the two lists
    */
   j = list2->lc_used;
   for (i=0; i<j; i++) {
	LC_StringArrayAdd(list1, (list2->lc_vec)[i]);
   }
   LC_StringArrayDestroy(list2);
   return list1;
}
示例#26
0
int writeFont(const char* inFilePath, const char* outFilePath, unsigned int fontSize, const char* id, bool fontpreview = false)
{
    Glyph glyphArray[END_INDEX - START_INDEX];
    
    // Initialize freetype library.
    FT_Library library;
    FT_Error error = FT_Init_FreeType(&library);
    if (error)
    {
        LOG(1, "FT_Init_FreeType error: %d \n", error);
        return -1;
    }
    
    // Initialize font face.
    FT_Face face;
    error = FT_New_Face(library, inFilePath, 0, &face);
    if (error)
    {
        LOG(1, "FT_New_Face error: %d \n", error);
        return -1;
    }
    
    // Set the pixel size.
    error = FT_Set_Char_Size(
            face,           // handle to face object.
            0,              // char_width in 1/64th of points.
            fontSize * 64,   // char_height in 1/64th of points.
            0,              // horizontal device resolution (defaults to 72 dpi if resolution (0, 0)).
            0 );            // vertical device resolution.
    
    if (error)
    {
        LOG(1, "FT_Set_Char_Size error: %d \n", error);
        return -1;
    }

    /* 
    error = FT_Set_Pixel_Sizes(face, FONT_SIZE, 0);
    if (error)
    {
        LOG(1, "FT_Set_Pixel_Sizes error : %d \n", error);
        exit(1);
    }
    */

    // Save glyph information (slot contains the actual glyph bitmap).
    FT_GlyphSlot slot = face->glyph;
    
    int actualfontHeight = 0;
    int rowSize = 0; // Stores the total number of rows required to all glyphs.
    
    // Find the width of the image.
    for (unsigned char ascii = START_INDEX; ascii < END_INDEX; ++ascii)
    {
        // Load glyph image into the slot (erase previous one)
        error = FT_Load_Char(face, ascii, FT_LOAD_RENDER);
        if (error)
        {
            LOG(1, "FT_Load_Char error : %d \n", error);
        }
        
        int bitmapRows = slot->bitmap.rows;
        actualfontHeight = (actualfontHeight < bitmapRows) ? bitmapRows : actualfontHeight;
        
        if (slot->bitmap.rows > slot->bitmap_top)
        {
            bitmapRows += (slot->bitmap.rows - slot->bitmap_top);
        }
        rowSize = (rowSize < bitmapRows) ? bitmapRows : rowSize;
    }

    // Include padding in the rowSize.
    rowSize += GLYPH_PADDING;
    
    // Initialize with padding.
    int penX = 0;
    int penY = 0;
    int row = 0;
    
    double powerOf2 = 2;
    unsigned int imageWidth = 0;
    unsigned int imageHeight = 0;
    bool textureSizeFound = false;

    int advance;
    int i;

    while (textureSizeFound == false)
    {
        imageWidth =  (unsigned int)pow(2.0, powerOf2);
        imageHeight = (unsigned int)pow(2.0, powerOf2);
        penX = 0;
        penY = 0;
        row = 0;

        // Find out the squared texture size that would fit all the require font glyphs.
        i = 0;
        for (unsigned char ascii = START_INDEX; ascii < END_INDEX; ++ascii)
        {
            // Load glyph image into the slot (erase the previous one).
            error = FT_Load_Char(face, ascii, FT_LOAD_RENDER);
            if (error)
            {
                LOG(1, "FT_Load_Char error : %d \n", error);
            }

            // Glyph image.
            int glyphWidth = slot->bitmap.pitch;
            int glyphHeight = slot->bitmap.rows;

            advance = glyphWidth + GLYPH_PADDING; //((int)slot->advance.x >> 6) + GLYPH_PADDING;

            // If we reach the end of the image wrap aroud to the next row.
            if ((penX + advance) > (int)imageWidth)
            {
                penX = 0;
                row += 1;
                penY = row * rowSize;
                if (penY + rowSize > (int)imageHeight)
                {
                    powerOf2++;
                    break;
                }
            }

            // penY should include the glyph offsets.
            penY += (actualfontHeight - glyphHeight) + (glyphHeight - slot->bitmap_top);

            // Set the pen position for the next glyph
            penX += advance; // Move X to next glyph position
            // Move Y back to the top of the row.
            penY = row * rowSize;

            if (ascii == (END_INDEX-1))
            {
                textureSizeFound = true;
            }

            i++;
        }
    }

    // Try further to find a tighter texture size.
    powerOf2 = 1;
    for (;;)
    {
        if ((penY + rowSize) >= pow(2.0, powerOf2))
        {
            powerOf2++;
        }
        else
        {
            imageHeight = (int)pow(2.0, powerOf2);
            break;
        }
    }
    
    // Allocate temporary image buffer to draw the glyphs into.
    unsigned char* imageBuffer = (unsigned char *)malloc(imageWidth * imageHeight);
    memset(imageBuffer, 0, imageWidth * imageHeight);
    penX = 0;
    penY = 0;
    row = 0;
    i = 0;
    for (unsigned char ascii = START_INDEX; ascii < END_INDEX; ++ascii)
    {
        // Load glyph image into the slot (erase the previous one).
        error = FT_Load_Char(face, ascii, FT_LOAD_RENDER);
        if (error)
        {
            LOG(1, "FT_Load_Char error : %d \n", error);
        }

        // Glyph image.
        unsigned char* glyphBuffer =  slot->bitmap.buffer;
        int glyphWidth = slot->bitmap.pitch;
        int glyphHeight = slot->bitmap.rows;

        advance = glyphWidth + GLYPH_PADDING;//((int)slot->advance.x >> 6) + GLYPH_PADDING;

        // If we reach the end of the image wrap aroud to the next row.
        if ((penX + advance) > (int)imageWidth)
        {
            penX = 0;
            row += 1;
            penY = row * rowSize;
            if (penY + rowSize > (int)imageHeight)
            {
                free(imageBuffer);
                LOG(1, "Image size exceeded!");
                return -1;
            }
        }
        
        // penY should include the glyph offsets.
        penY += (actualfontHeight - glyphHeight) + (glyphHeight - slot->bitmap_top);

        // Draw the glyph to the bitmap with a one pixel padding.
        drawBitmap(imageBuffer, penX, penY, imageWidth, glyphBuffer, glyphWidth, glyphHeight);
        
        // Move Y back to the top of the row.
        penY = row * rowSize;

        glyphArray[i].index = ascii;
        glyphArray[i].width = advance - GLYPH_PADDING;
        
        // Generate UV coords.
        glyphArray[i].uvCoords[0] = (float)penX / (float)imageWidth;
        glyphArray[i].uvCoords[1] = (float)penY / (float)imageHeight;
        glyphArray[i].uvCoords[2] = (float)(penX + advance - GLYPH_PADDING) / (float)imageWidth;
        glyphArray[i].uvCoords[3] = (float)(penY + rowSize) / (float)imageHeight;

        // Set the pen position for the next glyph
        penX += advance; // Move X to next glyph position
        i++;
    }


    FILE *gpbFp = fopen(outFilePath, "wb");
    
    // File header and version.
    char fileHeader[9]     = {'«', 'G', 'P', 'B', '»', '\r', '\n', '\x1A', '\n'};
    fwrite(fileHeader, sizeof(char), 9, gpbFp);
    fwrite(gameplay::GPB_VERSION, sizeof(char), 2, gpbFp);

    // Write Ref table (for a single font)
    writeUint(gpbFp, 1);                // Ref[] count
    writeString(gpbFp, id);             // Ref id
    writeUint(gpbFp, 128);              // Ref type
    writeUint(gpbFp, ftell(gpbFp) + 4); // Ref offset (current pos + 4 bytes)
    
    // Write Font object.
    
    // Family name.
    writeString(gpbFp, face->family_name);

    // Style.
    // TODO: Switch based on TTF style name and write appropriate font style unsigned int
    // For now just hardcoding to 0.
    //char* style = face->style_name;
    writeUint(gpbFp, 0); // 0 == PLAIN

    // Font size.
    writeUint(gpbFp, rowSize);

    // Character set.
    // TODO: Empty for now
    writeString(gpbFp, "");
    
    // Glyphs.
    unsigned int glyphSetSize = END_INDEX - START_INDEX;
    writeUint(gpbFp, glyphSetSize);
    fwrite(&glyphArray, sizeof(Glyph), glyphSetSize, gpbFp);
    
    // Texture.
    unsigned int textureSize = imageWidth * imageHeight;
    writeUint(gpbFp, imageWidth);
    writeUint(gpbFp, imageHeight);
    writeUint(gpbFp, textureSize);
    fwrite(imageBuffer, sizeof(unsigned char), textureSize, gpbFp);
    
    // Close file.
    fclose(gpbFp);

    LOG(1, "%s.gpb created successfully. \n", getBaseName(outFilePath).c_str());

    if (fontpreview)
    {
        // Write out font map to an image.
        std::string pgmFilePath = getFilenameNoExt(outFilePath);
        pgmFilePath.append(".pgm");
        FILE *imageFp = fopen(pgmFilePath.c_str(), "wb");
        fprintf(imageFp, "P5 %u %u 255\n", imageWidth, imageHeight);
        fwrite((const char *)imageBuffer, sizeof(unsigned char), imageWidth * imageHeight, imageFp);
        fclose(imageFp);
    }

    // Cleanup resources.
    free(imageBuffer);
    
    FT_Done_Face(face);
    FT_Done_FreeType(library);
    return 0;
}
示例#27
0
EXTERN_C BOOL WINAPI
DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    const char *szNewDllName = NULL;
    HMODULE hNewModule = NULL;
    const char *szNewDllBaseName;

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        if (VERBOSITY > 0) {
            debugPrintf("DLL_PROCESS_ATTACH\n");
        }

        g_hThisModule = hinstDLL;

        {
            char szProcess[MAX_PATH];
            GetModuleFileNameA(NULL, szProcess, sizeof szProcess);
            if (VERBOSITY > 0) {
                debugPrintf("  attached to %s\n", szProcess);
            }
        }

        /*
         * Calling LoadLibrary inside DllMain is strongly discouraged.  But it
         * works quite well, provided that the loaded DLL does not require or do
         * anything special in its DllMain, which seems to be the general case.
         *
         * See also:
         * - http://stackoverflow.com/questions/4370812/calling-loadlibrary-from-dllmain
         * - http://msdn.microsoft.com/en-us/library/ms682583
         */

        if (!USE_SHARED_MEM) {
            szNewDllName = getenv("INJECT_DLL");
            if (!szNewDllName) {
                debugPrintf("warning: INJECT_DLL not set\n");
                return FALSE;
            }
        } else {
            static char szSharedMemCopy[MAX_PATH];
            GetSharedMem(szSharedMemCopy, sizeof szSharedMemCopy);
            szNewDllName = szSharedMemCopy;
        }

        if (VERBOSITY > 0) {
            debugPrintf("  injecting %s\n", szNewDllName);
        }

        hNewModule = LoadLibraryA(szNewDllName);
        if (!hNewModule) {
            debugPrintf("warning: failed to load %s\n", szNewDllName);
            return FALSE;
        }

        szNewDllBaseName = getBaseName(szNewDllName);
        if (stricmp(szNewDllBaseName, "dxgitrace.dll") == 0) {
            replacements[numReplacements].szMatchModule = "dxgi.dll";
            replacements[numReplacements].hReplaceModule = hNewModule;
            ++numReplacements;

            replacements[numReplacements].szMatchModule = "d3d10.dll";
            replacements[numReplacements].hReplaceModule = hNewModule;
            ++numReplacements;

            replacements[numReplacements].szMatchModule = "d3d10_1.dll";
            replacements[numReplacements].hReplaceModule = hNewModule;
            ++numReplacements;

            replacements[numReplacements].szMatchModule = "d3d11.dll";
            replacements[numReplacements].hReplaceModule = hNewModule;
            ++numReplacements;
        } else {
            replacements[numReplacements].szMatchModule = szNewDllBaseName;
            replacements[numReplacements].hReplaceModule = hNewModule;
            ++numReplacements;
        }

        hookAllModules();
        break;

    case DLL_THREAD_ATTACH:
        break;

    case DLL_THREAD_DETACH:
        break;

    case DLL_PROCESS_DETACH:
        if (VERBOSITY > 0) {
            debugPrintf("DLL_PROCESS_DETACH\n");
        }
        break;
    }
    return TRUE;
}
示例#28
0
/**
 * Prints a stack backtrace for the current thread to the specified ostream.
 *
 * Does not malloc, does not throw.
 *
 * The format of the backtrace is:
 *
 * ----- BEGIN BACKTRACE -----
 * JSON backtrace
 * Human-readable backtrace
 * -----  END BACKTRACE  -----
 *
 * The JSON backtrace will be a JSON object with a "backtrace" field, and optionally others.
 * The "backtrace" field is an array, whose elements are frame objects.  A frame object has a
 * "b" field, which is the base-address of the library or executable containing the symbol, and
 * an "o" field, which is the offset into said library or executable of the symbol.
 *
 * The JSON backtrace may optionally contain additional information useful to a backtrace
 * analysis tool.  For example, on Linux it contains a subobject named "somap", describing
 * the objects referenced in the "b" fields of the "backtrace" list.
 *
 * @param os    ostream& to receive printed stack backtrace
 */
void printStackTrace(std::ostream& os) {
    static const char unknownFileName[] = "???";
    void* addresses[maxBackTraceFrames];
    Dl_info dlinfoForFrames[maxBackTraceFrames];

    ////////////////////////////////////////////////////////////
    // Get the backtrace addresses.
    ////////////////////////////////////////////////////////////

    const int addressCount = backtrace(addresses, maxBackTraceFrames);
    if (addressCount == 0) {
        const int err = errno;
        os << "Unable to collect backtrace addresses (errno: " << err << ' ' << strerror(err) << ')'
           << std::endl;
        return;
    }

    ////////////////////////////////////////////////////////////
    // Collect symbol information for each backtrace address.
    ////////////////////////////////////////////////////////////

    os << std::hex << std::uppercase;
    for (int i = 0; i < addressCount; ++i) {
        Dl_info& dlinfo(dlinfoForFrames[i]);
        if (!dladdr(addresses[i], &dlinfo)) {
            dlinfo.dli_fname = unknownFileName;
            dlinfo.dli_fbase = NULL;
            dlinfo.dli_sname = NULL;
            dlinfo.dli_saddr = NULL;
        }
        os << ' ' << addresses[i];
    }

    os << "\n----- BEGIN BACKTRACE -----\n";

    ////////////////////////////////////////////////////////////
    // Display the JSON backtrace
    ////////////////////////////////////////////////////////////

    os << "{\"backtrace\":[";
    for (int i = 0; i < addressCount; ++i) {
        const Dl_info& dlinfo = dlinfoForFrames[i];
        const uintptr_t fileOffset = uintptr_t(addresses[i]) - uintptr_t(dlinfo.dli_fbase);
        if (i)
            os << ',';
        os << "{\"b\":\"" << uintptr_t(dlinfo.dli_fbase) << "\",\"o\":\"" << fileOffset;
        if (dlinfo.dli_sname) {
            os << "\",\"s\":\"" << dlinfo.dli_sname;
        }
        os << "\"}";
    }
    os << ']';

    if (soMapJson)
        os << ",\"processInfo\":" << *soMapJson;
    os << "}\n";

    ////////////////////////////////////////////////////////////
    // Display the human-readable trace
    ////////////////////////////////////////////////////////////
    for (int i = 0; i < addressCount; ++i) {
        Dl_info& dlinfo(dlinfoForFrames[i]);
        os << ' ';
        if (dlinfo.dli_fbase) {
            os << getBaseName(dlinfo.dli_fname) << '(';
            if (dlinfo.dli_sname) {
                const uintptr_t offset = uintptr_t(addresses[i]) - uintptr_t(dlinfo.dli_saddr);
                os << dlinfo.dli_sname << "+0x" << offset;
            } else {
                const uintptr_t offset = uintptr_t(addresses[i]) - uintptr_t(dlinfo.dli_fbase);
                os << "+0x" << offset;
            }
            os << ')';
        } else {
            os << unknownFileName;
        }
        os << " [" << addresses[i] << ']' << std::endl;
    }

    os << std::dec << std::nouppercase;
    os << "-----  END BACKTRACE  -----" << std::endl;
}
/**
 * Writes the beginning of a class header file.
 *
 * @param fp		the file to write to
 */
void TemplateDefinitionFile::writeClassHeaderBegin(File &fp) const
{
	const char * name = getTemplateName().c_str();
	std::string bn = getBaseName();
	const char * baseName = bn.c_str();
	const char * baseNamePath = "";
	if (baseName[0] == '\0' && m_templateLocation != LOC_NONE)
	{
		baseNamePath = "sharedObject/";
		baseName = ROOT_TEMPLATE_NAME;
	}
	else if(_stricmp(baseName, "tpfTemplate") == 0)
	{
		baseNamePath = "sharedTemplateDefinition/";
	}
	
	fp.print("//========================================================================\n");
	fp.print("//\n");
	fp.print("// %s.h\n", name);
	fp.print("//\n");
	fp.print("//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be\n");
	fp.print("//overwritten the next time the template definition is compiled. Do not\n");
	fp.print("//make changes to code inside these blocks.\n");
	fp.print("//\n");
	if (getFileComments().size() > 0)
	{
		writeFileComments(fp);
		fp.print("//\n");
	}
	fp.print("// copyright 2001 Sony Online Entertainment\n");
	fp.print("//\n");
	fp.print("//========================================================================\n");
	fp.print("\n");
	fp.print("#ifndef _INCLUDED_%s_H\n", name);
	fp.print("#define _INCLUDED_%s_H\n", name);
	fp.print("\n");
	fp.print("#include \"%s%s.h\"\n", baseNamePath, baseName);
	fp.print("#include \"sharedFoundation/DynamicVariable.h\"\n");
	if (m_writeForCompilerFlag)
		fp.print("#include \"sharedTemplateDefinition/TpfTemplate.h\"\n");
	else
		fp.print("#include \"sharedUtility/TemplateParameter.h\"\n");
	fp.print("\n");
	fp.print("\n");
	fp.print("class Vector;\n");
	fp.print("typedef StructParam<ObjectTemplate> StructParamOT;\n");
	if (!m_writeForCompilerFlag)
	{
		std::map<int, TemplateData *>::const_iterator iter;
		iter = m_templateMap.find(m_highestVersion);
		if (iter != m_templateMap.end())
			(*iter).second->writeHeaderFwdDecls(fp);
	}
	fp.print("\n");
	fp.print("\n");
	fp.print("class %s : public %s\n", name, baseName);
	fp.print("{\n");
	fp.print("public:\n");
	writeTemplateId(fp);
	fp.print("public:\n");
	fp.print("\t         %s(const std::string & filename);\n", name);
	fp.print("\tvirtual ~%s();\n", name);
	fp.print("\n");
	fp.print("\tvirtual Tag getId(void) const;\n");
	fp.print("\tvirtual Tag getTemplateVersion(void) const;\n");
	fp.print("\tvirtual Tag getHighestTemplateVersion(void) const;\n");
	if (m_writeForCompilerFlag)
		fp.print("\tstatic void install(void);\n");
	else
		fp.print("\tstatic void install(bool allowDefaultTemplateParams = true);\n");
	fp.print("\n");
}	// writeClassHeaderBegin
示例#30
0
static void
hookModule(HMODULE hModule,
           const char *szModule)
{
    /* Hook modules only once */
    std::pair< std::set<HMODULE>::iterator, bool > ret;
    EnterCriticalSection(&Mutex);
    ret = g_hHookedModules.insert(hModule);
    LeaveCriticalSection(&Mutex);
    if (!ret.second) {
        return;
    }

    /* Never hook this module */
    if (hModule == g_hThisModule) {
        return;
    }

    /* Don't hook our replacement modules (based on HMODULE) */
    for (unsigned i = 0; i < numReplacements; ++i) {
        if (hModule == replacements[i].hReplaceModule) {
            return;
        }
    }

    const char *szBaseName = getBaseName(szModule);

    /* Don't hook our replacement modules (based on MODULE name) */
    for (unsigned i = 0; i < numReplacements; ++i) {
        if (stricmp(szBaseName, replacements[i].szMatchModule) == 0) {
            return;
        }
    }

    /* Leave these modules alone */
    if (stricmp(szBaseName, "kernel32.dll") == 0 ||
            stricmp(szBaseName, "ConEmuHk.dll") == 0) {
        return;
    }

    /*
     * Hook kernel32.dll functions, and its respective Windows API Set.
     *
     * http://msdn.microsoft.com/en-us/library/dn505783.aspx (Windows 8.1)
     * http://msdn.microsoft.com/en-us/library/hh802935.aspx (Windows 8)
     */

    hookLibraryLoaderFunctions(hModule, szModule, "kernel32.dll");
    hookLibraryLoaderFunctions(hModule, szModule, "api-ms-win-core-libraryloader-l1-1-1.dll");
    hookLibraryLoaderFunctions(hModule, szModule, "api-ms-win-core-libraryloader-l1-2-0.dll");

    hookProcessThreadsFunctions(hModule, szModule, "kernel32.dll");
    hookProcessThreadsFunctions(hModule, szModule, "api-ms-win-core-processthreads-l1-1-1.dll");
    hookProcessThreadsFunctions(hModule, szModule, "api-ms-win-core-processthreads-l1-1-2.dll");

    /* Don't hook internal dependencies */
    if (stricmp(szBaseName, "d3d10core.dll") == 0 ||
            stricmp(szBaseName, "d3d10level9.dll") == 0 ||
            stricmp(szBaseName, "d3d10sdklayers.dll") == 0 ||
            stricmp(szBaseName, "d3d10_1core.dll") == 0 ||
            stricmp(szBaseName, "d3d11sdklayers.dll") == 0 ||
            stricmp(szBaseName, "d3d11_1sdklayers.dll") == 0 ||
            stricmp(szBaseName, "d3d11_2sdklayers.dll") == 0) {
        return;
    }

    for (unsigned i = 0; i < numReplacements; ++i) {
        replaceImport(hModule, szModule, replacements[i].szMatchModule, replacements[i].hReplaceModule);
        replaceImport(hModule, szModule, replacements[i].szMatchModule, replacements[i].hReplaceModule);
        replaceImport(hModule, szModule, replacements[i].szMatchModule, replacements[i].hReplaceModule);
    }
}