Ejemplo n.º 1
0
Archivo: Lib.cpp Proyecto: cromo/hxcpp
int __hxcpp_unload_all_libraries()
{
   int unloaded = 0;
   while(sgOrderedModules.size())
   {
      Module module = sgOrderedModules.back();
      sgOrderedModules.pop_back();
      hxFreeLibrary(module);
      unloaded++;
   }
   return unloaded;
}
Ejemplo n.º 2
0
void C2Builder::generateOptionalIR() {
    if (options.checkOnly) return;
    if (!options.generateIR && !recipe.generateIR) return;

    bool single_module = false;
    for (unsigned i=0; i<recipe.genConfigs.size(); i++) {
        const std::string& conf = recipe.genConfigs[i];
        // TODO just pass struct with bools?
        if (conf == "single-module") single_module = true;
        else {
            fprintf(stderr, ANSI_RED"invalid code generation argument '%s'" ANSI_NORMAL"\n", conf.c_str());
        }
    }

    std::string outdir = OUTPUT_DIR + recipe.name + BUILD_DIR;

    // TODO move all this to some generic Codegen class
    // Q: use single context or one-per-module?
    llvm::LLVMContext context;

    const ModuleList& mods = mainComponent->getModules();
    if (single_module) {
        uint64_t t1 = Utils::getCurrentTime();
        std::string filename = recipe.name;
        if (options.verbose) log(COL_VERBOSE, "generating IR for single module %s", filename.c_str());
        CodeGenModule cgm(filename, true, mods, context);
        cgm.generate();
        uint64_t t2 = Utils::getCurrentTime();
        if (options.printTiming) log(COL_TIME, "IR generation took %" PRIu64" usec", t2 - t1);
        if (options.printIR) cgm.dump();
        bool ok = cgm.verify();
        if (ok) cgm.write(outdir, filename);
    } else {
        for (unsigned m=0; m<mods.size(); m++) {
            Module* M = mods[m];
            uint64_t t1 = Utils::getCurrentTime();
            if (M->isPlainC()) continue;
            if (M->getName() == "c2") continue;

            if (options.verbose) log(COL_VERBOSE, "generating IR for module %s", M->getName().c_str());
            ModuleList single;
            single.push_back(M);
            CodeGenModule cgm(M->getName(), false, single, context);
            cgm.generate();
            uint64_t t2 = Utils::getCurrentTime();
            if (options.printTiming) log(COL_TIME, "IR generation took %" PRIu64" usec", t2 - t1);
            if (options.printIR) cgm.dump();
            bool ok = cgm.verify();
            if (ok) cgm.write(outdir, M->getName());
        }
    }
}
Ejemplo n.º 3
0
// Assume that dyld is in memory at ADDR and try to parse it's load commands
bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(
    lldb::addr_t addr) {
  std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
  DataExtractor data; // Load command data
  static ConstString g_dyld_all_image_infos("dyld_all_image_infos");
  if (ReadMachHeader(addr, &m_dyld.header, &data)) {
    if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {
      m_dyld.address = addr;
      ModuleSP dyld_module_sp;
      if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {
        if (m_dyld.file_spec) {
          UpdateDYLDImageInfoFromNewImageInfo(m_dyld);
        }
      }
      dyld_module_sp = GetDYLDModule();

      Target &target = m_process->GetTarget();

      if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&
          dyld_module_sp.get()) {
        const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(
            g_dyld_all_image_infos, eSymbolTypeData);
        if (symbol)
          m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);
      }

      // Update all image infos
      InitializeFromAllImageInfos();

      // If we didn't have an executable before, but now we do, then the dyld
      // module shared pointer might be unique and we may need to add it again
      // (since Target::SetExecutableModule() will clear the images). So append
      // the dyld module back to the list if it is
      /// unique!
      if (dyld_module_sp) {
        target.GetImages().AppendIfNeeded(dyld_module_sp);

        // At this point we should have read in dyld's module, and so we should
        // set breakpoints in it:
        ModuleList modules;
        modules.Append(dyld_module_sp);
        target.ModulesDidLoad(modules);
        SetDYLDModule(dyld_module_sp);
      }

      return true;
    }
  }
  return false;
}
Ejemplo n.º 4
0
void
ModuleManager::_FindBuiltInModules(const char *prefix, const char *suffix,
	module_name_list *list)
{
	uint32 count = fModules.CountModules();
	uint32 prefixLength = strlen(prefix);

	for (uint32 i = 0; i < count; i++) {
		Module *module = fModules.ModuleAt(i);
		if (!strncmp(module->Info()->name, prefix, prefixLength)
			&& _MatchSuffix(module->Info()->name, suffix))
			list->names.insert(module->Info()->name);
	}
}
Ejemplo n.º 5
0
size_t
ModuleList::FindModules (const ModuleSpec &module_spec, ModuleList& matching_module_list) const
{
    size_t existing_matches = matching_module_list.GetSize();

    Mutex::Locker locker(m_modules_mutex);
    collection::const_iterator pos, end = m_modules.end();
    for (pos = m_modules.begin(); pos != end; ++pos)
    {
        ModuleSP module_sp(*pos);
        if (module_sp->MatchesModuleSpec (module_spec))
            matching_module_list.Append(module_sp);
    }
    return matching_module_list.GetSize() - existing_matches;
}
Ejemplo n.º 6
0
File EnabledModuleList::findDefaultModulesFolder (Project& project)
{
    ModuleList available;
    available.scanAllKnownFolders  (project);

    for (int i = available.modules.size(); --i >= 0;)
    {
        File f (available.modules.getUnchecked(i)->getFolder());

        if (f.isDirectory())
            return f.getParentDirectory();
    }

    return File::getCurrentWorkingDirectory();
}
Ejemplo n.º 7
0
status_t
ModuleManager::AddBuiltInModule(module_info *info)
{
	BAutolock _lock(fModules);

	TRACE(("add module %p, \"%s\"\n", info, info->name));
	return fModules.AddModule(new Module(NULL, info)) ? B_OK : B_ERROR;
}
Ejemplo n.º 8
0
bool CSecurityCache::GetEigenvalue(ModuleList& mlist)
{
    mlist.clear();
    for(int i = 0; i < SECURE_BUCKET_SIZE; i++)
    {
        for(list<SecCachStruct*>::iterator ite = m_secuBucket[i].begin(); ite != m_secuBucket[i].end(); ite ++)
        {
            if(((*ite)->tag == 1) || (*ite)->tag == 3 || (*ite)->tag == 4)//有效数据
            {
                ModuleItem item;
                memcpy(item.md,(void*)(*ite)->chkdata,SECURE_SIZE);
                mlist.push_back(item);
            }
        }
    }
    return true;
}
Ejemplo n.º 9
0
void CGenerator::generate() {
    std::string outdir = options.outputDir + targetName + options.buildDir;

    MakefileGenerator makeGen(outdir, targetName, targetType);
    if (options.single_module) {
        makeGen.add(targetName);
        CCodeGenerator gen(targetName, CCodeGenerator::SINGLE_FILE, moduleMap, mods, includeNamer);
        gen.generate(options.printC, outdir);
    } else {
        for (unsigned m=0; m<mods.size(); m++) {
            Module* M = mods[m];
            makeGen.add(M->getName());
            ModuleList single;
            single.push_back(M);
            CCodeGenerator gen(M->getName(), CCodeGenerator::MULTI_FILE, moduleMap, single, includeNamer);
            gen.generate(options.printC, outdir);
        }
    }
    for (StringListConstIter iter=libs.begin(); iter!=libs.end(); ++iter) {
        makeGen.addLinkerLib(*iter);
    }
    makeGen.write();

    // generate exports.version
    if (targetType == GenUtils::SHARED_LIB) {
        StringBuilder expmap;
        expmap << "LIB_1.0 {\n";
        expmap << "\tglobal:\n";
        for (unsigned m=0; m<mods.size(); m++) {
            const Module* M = mods[m];
            const Module::Symbols& syms = M->getSymbols();
            for (Module::SymbolsConstIter iter = syms.begin(); iter != syms.end(); ++iter) {
                const Decl* D = iter->second;
                if (!D->isExported()) continue;
                if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) continue;
                expmap << "\t\t";
                GenUtils::addName(M->getName(), iter->first, expmap);
                expmap << ";\n";
            }
        }
        expmap << "\tlocal:\n\t\t*;\n";
        expmap << "};\n";
        std::string outfile = outdir + "exports.version";
        FileUtils::writeFile(outdir.c_str(), outfile.c_str(), expmap);
    }
}
Ejemplo n.º 10
0
void Project::warnAboutOldProjucerVersion()
{
    ModuleList available;
    available.scanAllKnownFolders (*this);

    if (isAnyModuleNewerThanProjucer (available.modules))
    {
        if (ProjucerApplication::getApp().isRunningCommandLine)
            std::cout <<  "WARNING! This version of the Projucer is out-of-date!" << std::endl;
        else
            AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
                                              "Projucer",
                                              "This version of the Projucer is out-of-date!"
                                              "\n\n"
                                              "Always make sure that you're running the very latest version, "
                                              "preferably compiled directly from the JUCE repository that you're working with!");
    }
}
Ejemplo n.º 11
0
void
AppleObjCRuntime::ReadObjCLibraryIfNeeded (const ModuleList &module_list)
{
    if (!HasReadObjCLibrary ())
    {
        Mutex::Locker locker (module_list.GetMutex ());

        size_t num_modules = module_list.GetSize();
        for (size_t i = 0; i < num_modules; i++)
        {
            auto mod = module_list.GetModuleAtIndex (i);
            if (IsModuleObjCLibrary (mod))
            {
                ReadObjCLibrary (mod);
                break;
            }
        }
    }
}
Ejemplo n.º 12
0
File EnabledModuleList::findDefaultModulesFolder (Project& project)
{
    auto globalPath = findGlobalModulesFolder();

    if (globalPath != File())
        return globalPath;

    ModuleList available;
    available.scanProjectExporterModulePaths (project);

    for (int i = available.modules.size(); --i >= 0;)
    {
        File f (available.modules.getUnchecked(i)->getFolder());

        if (f.isDirectory())
            return f.getParentDirectory();
    }

    return File::getCurrentWorkingDirectory();
}
Ejemplo n.º 13
0
// PutModule
status_t
ModuleManager::PutModule(const char *path)
{
	if (path == NULL)
		return B_BAD_VALUE;

	BAutolock _lock(fModules);

	if (Module *module = fModules.FindModule(path)) {
		if (module->Put()) {
			ModuleAddOn *addon = module->AddOn();
			fModules.RemoveModule(module);
			delete module;
			_PutAddOn(addon);
		}
	} else
		return B_BAD_VALUE;

	return B_OK;
}
Ejemplo n.º 14
0
	void Host::ScanInvalidModuleFiles()
	{
		ScopedLock lock(&moduleMutex);

		this->autoScan = false; // Do not recursively scan
		ModuleList modulesLoaded; // Track loaded modules

		std::vector<std::string>::iterator iter;
		iter = this->invalid_module_files.begin();
		while (iter != this->invalid_module_files.end())
		{
			std::string path = *iter;
			ModuleProvider *provider = FindModuleProvider(path);
			if (provider != NULL)
			{
				SharedPtr<Module> m = this->LoadModule(path, provider);

				// Module was loaded successfully
				if (!m.isNull())
					modulesLoaded.push_back(m);

				// Erase path, even on failure
				iter = invalid_module_files.erase(iter);
			}
			else
			{
				iter++;
			}
		}

		if (modulesLoaded.size() > 0)
		{
			this->StartModules(modulesLoaded);

			/* If any of the invalid module files added
			 * a ModuleProvider, let them load their modules */
			this->ScanInvalidModuleFiles();
		}

		this->autoScan = true;
	}
Ejemplo n.º 15
0
// @copydoc klk::IModuleFactory::getModulesWithoutRegistration
const ModuleList ModuleFactory::getModulesWithoutRegistration()
{
    ModuleList list;
    StringList ids = getModuleIDs();
    for(StringList::iterator id = ids.begin(); id != ids.end(); id++)
    {
        Locker lock(&m_lock);
        IModulePtr module = getModuleUnsafe(*id);
        if (!module)
        {
            // not found here
            // will try to find at the modules description
            module = getLibFactory()->getModule(*id);
        }
        if (module)
        {
            list.push_back(module);
        }
    }
    return list;
}
Ejemplo n.º 16
0
void enumAndLoadModuleSymbols( HANDLE hProcess, DWORD pid )
{
	ModuleList modules;
	ModuleListIter it;
	char *img, *mod;

	// fill in module list
	fillModuleList( modules, pid, hProcess );

	for ( it = modules.begin(); it != modules.end(); ++ it )
	{
		// unfortunately, SymLoadModule() wants writeable strings
		img = new char[(*it).imageName.size() + 1];
		strcpy( img, (*it).imageName.c_str() );
		mod = new char[(*it).moduleName.size() + 1];
		strcpy( mod, (*it).moduleName.c_str() );

		SymLoadModule64( hProcess, 0, img, mod, (*it).baseAddress, (*it).size );

		delete [] img;
		delete [] mod;
	}
}
Ejemplo n.º 17
0
void SearchFilter::SearchInModuleList(Searcher &searcher, ModuleList &modules) {
  SymbolContext empty_sc;

  if (!m_target_sp)
    return;
  empty_sc.target_sp = m_target_sp;

  if (searcher.GetDepth() == lldb::eSearchDepthTarget)
    searcher.SearchCallback(*this, empty_sc, nullptr, false);
  else {
    std::lock_guard<std::recursive_mutex> guard(modules.GetMutex());
    const size_t numModules = modules.GetSize();

    for (size_t i = 0; i < numModules; i++) {
      ModuleSP module_sp(modules.GetModuleAtIndexUnlocked(i));
      if (ModulePasses(module_sp)) {
        if (DoModuleIteration(module_sp, searcher) ==
            Searcher::eCallbackReturnStop)
          return;
      }
    }
  }
}
Ejemplo n.º 18
0
addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list,
                                      const ConstString &name,
                                      SymbolType symbol_type) const {
  SymbolContextList target_symbols;
  Target &target = m_process->GetTarget();

  if (!module_list.FindSymbolsWithNameAndType(name, symbol_type,
                                              target_symbols))
    return LLDB_INVALID_ADDRESS;

  SymbolContext sym_ctx;
  target_symbols.GetContextAtIndex(0, sym_ctx);

  const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress();
  if (!jit_descriptor_addr.IsValid())
    return LLDB_INVALID_ADDRESS;

  const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target);
  return jit_addr;
}
Ejemplo n.º 19
0
// GetNextLoadedModuleName
status_t
ModuleManager::GetNextLoadedModuleName(uint32 *cookie, char *buffer,
	size_t *bufferSize)
{
	status_t error = (cookie && buffer && bufferSize ? B_OK : B_BAD_VALUE);
	if (error == B_OK) {
		BAutolock _lock(fModules);
		if (Module *module = fModules.ModuleAt(*cookie)) {
			module_info *info = module->Info();
			size_t nameLen = strlen(info->name);
			if (nameLen < *bufferSize) {
				strcpy(buffer, info->name);
				*bufferSize = nameLen;
				(*cookie)++;
			} else
				error = B_BAD_VALUE;
		} else
			error = B_ENTRY_NOT_FOUND;
	}
	return error;
}
Ejemplo n.º 20
0
void EnabledModuleList::addModuleInteractive (const String& moduleID)
{
    ModuleList list;

    list.scanGlobalJuceModulePath();
    if (auto* info = list.getModuleWithID (moduleID))
    {
        addModule (info->moduleFolder, areMostModulesCopiedLocally(), areMostModulesUsingGlobalPath());
        return;
    }

    list.scanGlobalUserModulePath();
    if (auto* info = list.getModuleWithID (moduleID))
    {
        addModule (info->moduleFolder, areMostModulesCopiedLocally(), areMostModulesUsingGlobalPath());
        return;
    }

    list.scanProjectExporterModulePaths (project);
    if (auto* info = list.getModuleWithID (moduleID))
        addModule (info->moduleFolder, areMostModulesCopiedLocally(), false);
    else
        addModuleFromUserSelectedFile();
}
Ejemplo n.º 21
0
	//*************************************************************************
	// Method:		fillModuleListPSAPI
	// Description: support function
	//
	//*************************************************************************
	bool StackWalker::fillModuleListPSAPI( ModuleList& modules, DWORD pid, HANDLE hProcess )
	{
		// EnumProcessModules()
		typedef BOOL (__stdcall *tEPM)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
		// GetModuleFileNameEx()
		typedef DWORD (__stdcall *tGMFNE)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
		// GetModuleBaseName() -- redundant, as GMFNE() has the same prototype, but who cares?
		typedef DWORD (__stdcall *tGMBN)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
		// GetModuleInformation()
		typedef BOOL (__stdcall *tGMI)( HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );

		HINSTANCE hPsapi;
		tEPM pEPM;
		tGMFNE pGMFNE;
		tGMBN pGMBN;
		tGMI pGMI;

		int i;
		ModuleEntry e;
		DWORD cbNeeded;
		MODULEINFO mi;
		HMODULE *hMods = 0;
		char *tt = 0;

		hPsapi = LoadLibrary( "psapi.dll" );
		if ( hPsapi == 0 )
			return false;

		modules.clear();

		pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
		pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
		pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
		pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
		if ( pEPM == 0 || pGMFNE == 0 || pGMBN == 0 || pGMI == 0 )
		{
			// yuck. Some API is missing.
			FreeLibrary( hPsapi );
			return false;
		}

		hMods = new HMODULE[TTBUFLEN / sizeof HMODULE];
		tt = new char[TTBUFLEN];
		// not that this is a sample. Which means I can get away with
		// not checking for errors, but you cannot. :)

		if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
		{
			//printf( "EPM failed, GetLastError() = %lu\n", GetLastError() );
			goto cleanup;
		}

		if ( cbNeeded > TTBUFLEN )
		{
			//printf( "More than %lu module handles. Huh?\n", lenof( hMods ) );
			goto cleanup;
		}

		for ( i = 0; i < cbNeeded / sizeof hMods[0]; ++ i )
		{
			// for each module, get:
			// base address, size
			pGMI( hProcess, hMods[i], &mi, sizeof mi );
			e.baseAddress = (DWORD) mi.lpBaseOfDll;
			e.size = mi.SizeOfImage;
			// image file name
			tt[0] = '\0';
			pGMFNE( hProcess, hMods[i], tt, TTBUFLEN );
			e.imageName = tt;
			// module name
			tt[0] = '\0';
			pGMBN( hProcess, hMods[i], tt, TTBUFLEN );
			e.moduleName = tt;
			/*printf( "%08lXh %6lu %-15.15s %s\n", e.baseAddress,
				e.size, e.moduleName.c_str(), e.imageName.c_str() );*/

			modules.push_back( e );
		}

	cleanup:
		if ( hPsapi )
			FreeLibrary( hPsapi );
		delete [] tt;
		delete [] hMods;

		return modules.size() != 0;
	}
Ejemplo n.º 22
0
void
Breakpoint::ModulesChanged (ModuleList &module_list, bool load)
{
    if (load)
    {
        // The logic for handling new modules is:
        // 1) If the filter rejects this module, then skip it.
        // 2) Run through the current location list and if there are any locations
        //    for that module, we mark the module as "seen" and we don't try to re-resolve
        //    breakpoint locations for that module.
        //    However, we do add breakpoint sites to these locations if needed.
        // 3) If we don't see this module in our breakpoint location list, call ResolveInModules.

        ModuleList new_modules;  // We'll stuff the "unseen" modules in this list, and then resolve
                                 // them after the locations pass.  Have to do it this way because
                                 // resolving breakpoints will add new locations potentially.

        const size_t num_locs = m_locations.GetSize();

        for (size_t i = 0; i < module_list.GetSize(); i++)
        {
            bool seen = false;
            ModuleSP module_sp (module_list.GetModuleAtIndex (i));
            if (!m_filter_sp->ModulePasses (module_sp))
                continue;

            for (size_t loc_idx = 0; loc_idx < num_locs; loc_idx++)
            {
                BreakpointLocationSP break_loc = m_locations.GetByIndex(loc_idx);
                if (!break_loc->IsEnabled())
                    continue;
                const Section *section = break_loc->GetAddress().GetSection();
                if (section == NULL || section->GetModule() == module_sp.get())
                {
                    if (!seen)
                        seen = true;

                    if (!break_loc->ResolveBreakpointSite())
                    {
                        LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
                        if (log)
                            log->Printf ("Warning: could not set breakpoint site for breakpoint location %d of breakpoint %d.\n",
                                         break_loc->GetID(), GetID());
                    }
                }
            }

            if (!seen)
                new_modules.AppendIfNeeded (module_sp);

        }
        if (new_modules.GetSize() > 0)
        {
            ResolveBreakpointInModules(new_modules);
        }
    }
    else
    {
        // Go through the currently set locations and if any have breakpoints in
        // the module list, then remove their breakpoint sites.
        // FIXME: Think about this...  Maybe it's better to delete the locations?
        // Are we sure that on load-unload-reload the module pointer will remain
        // the same?  Or do we need to do an equality on modules that is an
        // "equivalence"???

        for (size_t i = 0; i < module_list.GetSize(); i++)
        {
            ModuleSP module_sp (module_list.GetModuleAtIndex (i));
            if (m_filter_sp->ModulePasses (module_sp))
            {
                const size_t num_locs = m_locations.GetSize();
                for (size_t loc_idx = 0; loc_idx < num_locs; ++loc_idx)
                {
                    BreakpointLocationSP break_loc = m_locations.GetByIndex(loc_idx);
                    const Section *section = break_loc->GetAddress().GetSection();
                    if (section && section->GetModule() == module_sp.get())
                    {
                        // Remove this breakpoint since the shared library is 
                        // unloaded, but keep the breakpoint location around
                        // so we always get complete hit count and breakpoint
                        // lifetime info
                        break_loc->ClearBreakpointSite();
                    }
                }
            }
        }
    }
}
Ejemplo n.º 23
0
	//*************************************************************************
	// Method:		fillModuleListTH32
	// Description: support function
	//
	//*************************************************************************
	bool StackWalker::fillModuleListTH32( ModuleList& modules, DWORD pid )
	{
		// CreateToolhelp32Snapshot()
		typedef HANDLE (__stdcall *tCT32S)( DWORD dwFlags, DWORD th32ProcessID );
		// Module32First()
		typedef BOOL (__stdcall *tM32F)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );
		// Module32Next()
		typedef BOOL (__stdcall *tM32N)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );

		// I think the DLL is called tlhelp32.dll on Win9X, so we try both
		const char *dllname[] = { "kernel32.dll", "tlhelp32.dll" };
		HINSTANCE hToolhelp;
		tCT32S pCT32S;
		tM32F pM32F;
		tM32N pM32N;

		HANDLE hSnap;
		MODULEENTRY32 me = { sizeof me };
		bool keepGoing;
		ModuleEntry e;
		int i;

		for ( i = 0; i < lenof( dllname ); ++ i )
		{
			hToolhelp = LoadLibrary( dllname[i] );
			if ( hToolhelp == 0 )
				continue;
			pCT32S = (tCT32S) GetProcAddress( hToolhelp, "CreateToolhelp32Snapshot" );
			pM32F = (tM32F) GetProcAddress( hToolhelp, "Module32First" );
			pM32N = (tM32N) GetProcAddress( hToolhelp, "Module32Next" );
			if ( pCT32S != 0 && pM32F != 0 && pM32N != 0 )
				break; // found the functions!
			FreeLibrary( hToolhelp );
			hToolhelp = 0;
		}

		if ( hToolhelp == 0 ) // nothing found?
			return false;

		hSnap = pCT32S( TH32CS_SNAPMODULE, pid );
		if ( hSnap == (HANDLE) -1 )
			return false;

		keepGoing = !!pM32F( hSnap, &me );
		while ( keepGoing )
		{
			// here, we have a filled-in MODULEENTRY32
			//printf( "%08lXh %6lu %-15.15s %s\n", me.modBaseAddr, me.modBaseSize, me.szModule, me.szExePath );
			e.imageName = me.szExePath;
			e.moduleName = me.szModule;
			e.baseAddress = (DWORD) me.modBaseAddr;
			e.size = me.modBaseSize;
			modules.push_back( e );
			keepGoing = !!pM32N( hSnap, &me );
		}

		CloseHandle( hSnap );

		FreeLibrary( hToolhelp );

		return modules.size() != 0;
	}
Ejemplo n.º 24
0
Archivo: Lib.cpp Proyecto: Gama11/hxcpp
void *__hxcpp_get_proc_address(String inLib, String full_name,bool inNdllProc,bool inQuietFail)
{
   String bin = __hxcpp_get_bin_dir();
   String deviceExt = __hxcpp_get_dll_extension();


   #ifdef HX_ANDROID
   String module_name = HX_CSTRING("lib") + inLib;
   #else
   String module_name = inLib;
   #endif

   #ifdef IPHONE
   gLoadDebug = true;
   setenv("DYLD_PRINT_APIS","1",true);

   #elif !defined(HX_WINRT)
   gLoadDebug = gLoadDebug || getenv("HXCPP_LOAD_DEBUG");
   #endif

   if (!sgLibPathIsInit)
   {
      sgLibPathIsInit = true;

      sgLibPath.push_back("./");
      #ifdef HX_MACOS
      sgLibPath.push_back("@executable_path/");
      #endif
      sgLibPath.push_back("");

      #ifdef HXCPP_TRY_HAXELIB
      String hxcpp = GetEnv("HXCPP");
      if (hxcpp.length==0)
         hxcpp = FindHaxelib( HX_CSTRING("hxcpp") );
      if (hxcpp.length!=0)
         __hxcpp_push_dll_path(hxcpp+HX_CSTRING("/bin/") + bin + HX_CSTRING("/"));
      #endif
   }


   Module module = sgLoadedModule[module_name.__s];

   bool new_module = module==0;

   if (!module && sgRegisteredPrims)
   {
      void *registered = (*sgRegisteredPrims)[full_name.__CStr()];
      // Try with lib name ...
      if (!registered)
      {
         String libString = inLib + HX_CSTRING("_") + full_name;
         registered = (*sgRegisteredPrims)[libString.__CStr()];
      }

      if (registered)
         return registered;
   }

   if (!module && gLoadDebug)
   {
      #ifdef ANDROID
       __android_log_print(ANDROID_LOG_INFO, "loader", "Searching for %s...", module_name.__s);
      #else
      printf("Searching for %s...\n", inLib.__s);
      #endif
   }

   String haxelibPath;

   for(int e=0; module==0 && e<3; e++)
   {
      String extension = e==0 ? deviceExt : e==1 ? HX_CSTRING(".ndll") : HX_CSTRING("");

      for(int path=0;path<sgLibPath.size();path++)
      {
         String testPath = String( sgLibPath[path].c_str() ) +  module_name + extension;
         if (gLoadDebug)
         {
            #ifndef ANDROID
            printf(" try %s...\n", testPath.__s);
            #else
            __android_log_print(ANDROID_LOG_INFO, "loader", "Try %s", testPath.__s);
            #endif
         }
         module = hxLoadLibrary(testPath);
         if (module)
         {
            if (gLoadDebug)
            {
               #ifndef ANDROID
               printf("Found %s\n", testPath.__s);
               #else
               __android_log_print(ANDROID_LOG_INFO, "loader", "Found %s", testPath.__s);
               #endif
            }
            break;
         }
      }

      #ifdef HXCPP_TRY_HAXELIB
      if (!module)
      {
         if (e==0)
            haxelibPath = FindHaxelib(inLib);

         if (haxelibPath.length!=0)
         {
            String testPath  = haxelibPath + HX_CSTRING("/ndll/") + bin + HX_CSTRING("/") + inLib + extension;
            if (gLoadDebug)
               printf(" try %s...\n", testPath.__s);
            module = hxLoadLibrary(testPath);
            if (module && gLoadDebug)
            {
               printf("Found %s\n", testPath.__s);
            }
         }
      }
      #endif
   }

   if (!module)
   {
      hx::Throw(HX_CSTRING("Could not load module ") + inLib + HX_CSTRING("@") + full_name);
   }


   if (new_module)
   {
      sgLoadedModule[module_name.__s] = module;

      sgOrderedModules.push_back(module);

      SetLoaderProcFunc set_loader = (SetLoaderProcFunc)hxFindSymbol(module,"hx_set_loader");
      if (set_loader)
         set_loader(hx_cffi);

      GetNekoEntryFunc func = (GetNekoEntryFunc)hxFindSymbol(module,"__neko_entry_point");
      if (func)
      {
         NekoEntryFunc entry = (NekoEntryFunc)func();
         if (entry)
            entry();
      }
   }

   FundFunc proc_query = (FundFunc)hxFindSymbol(module,full_name.__CStr());
   if (!proc_query)
       proc_query = (FundFunc)hxFindSymbol(module, (inLib + HX_CSTRING("_") + full_name).__CStr());

   if (!proc_query && !inQuietFail)
   {
      #ifdef ANDROID
       __android_log_print(ANDROID_LOG_ERROR, "loader", "Could not find primitive %s in %p",
        full_name.__CStr(), module);
      #else
      fprintf(stderr,"Could not find primitive %s.\n", full_name.__CStr());
      #endif
      return 0;
   }

   if (!inNdllProc)
      return (void *)proc_query;

   void *proc = proc_query();
   if (!proc && !inQuietFail)
   {
      #ifdef ANDROID
      __android_log_print(ANDROID_LOG_ERROR, "loader", "Could not identify primitive %s in %s",
        full_name.__CStr(), inLib.__CStr() );
      #else
      fprintf(stderr,"Could not identify primitive %s in %s\n", full_name.__CStr(),inLib.__CStr());
      #endif
   }

   return proc;
}
Ejemplo n.º 25
0
void Breakpoint::ModulesChanged(ModuleList &module_list, bool load,
                                bool delete_locations) {
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
  if (log)
    log->Printf("Breakpoint::ModulesChanged: num_modules: %zu load: %i "
                "delete_locations: %i\n",
                module_list.GetSize(), load, delete_locations);

  std::lock_guard<std::recursive_mutex> guard(module_list.GetMutex());
  if (load) {
    // The logic for handling new modules is:
    // 1) If the filter rejects this module, then skip it.
    // 2) Run through the current location list and if there are any locations
    //    for that module, we mark the module as "seen" and we don't try to
    //    re-resolve
    //    breakpoint locations for that module.
    //    However, we do add breakpoint sites to these locations if needed.
    // 3) If we don't see this module in our breakpoint location list, call
    // ResolveInModules.

    ModuleList new_modules; // We'll stuff the "unseen" modules in this list,
                            // and then resolve
    // them after the locations pass.  Have to do it this way because
    // resolving breakpoints will add new locations potentially.

    for (ModuleSP module_sp : module_list.ModulesNoLocking()) {
      bool seen = false;
      if (!m_filter_sp->ModulePasses(module_sp))
        continue;

      for (BreakpointLocationSP break_loc_sp :
           m_locations.BreakpointLocations()) {
        if (!break_loc_sp->IsEnabled())
          continue;
        SectionSP section_sp(break_loc_sp->GetAddress().GetSection());
        if (!section_sp || section_sp->GetModule() == module_sp) {
          if (!seen)
            seen = true;

          if (!break_loc_sp->ResolveBreakpointSite()) {
            if (log)
              log->Printf("Warning: could not set breakpoint site for "
                          "breakpoint location %d of breakpoint %d.\n",
                          break_loc_sp->GetID(), GetID());
          }
        }
      }

      if (!seen)
        new_modules.AppendIfNeeded(module_sp);
    }

    if (new_modules.GetSize() > 0) {
      ResolveBreakpointInModules(new_modules);
    }
  } else {
    // Go through the currently set locations and if any have breakpoints in
    // the module list, then remove their breakpoint sites, and their locations
    // if asked to.

    BreakpointEventData *removed_locations_event;
    if (!IsInternal())
      removed_locations_event = new BreakpointEventData(
          eBreakpointEventTypeLocationsRemoved, shared_from_this());
    else
      removed_locations_event = nullptr;

    size_t num_modules = module_list.GetSize();
    for (size_t i = 0; i < num_modules; i++) {
      ModuleSP module_sp(module_list.GetModuleAtIndexUnlocked(i));
      if (m_filter_sp->ModulePasses(module_sp)) {
        size_t loc_idx = 0;
        size_t num_locations = m_locations.GetSize();
        BreakpointLocationCollection locations_to_remove;
        for (loc_idx = 0; loc_idx < num_locations; loc_idx++) {
          BreakpointLocationSP break_loc_sp(m_locations.GetByIndex(loc_idx));
          SectionSP section_sp(break_loc_sp->GetAddress().GetSection());
          if (section_sp && section_sp->GetModule() == module_sp) {
            // Remove this breakpoint since the shared library is
            // unloaded, but keep the breakpoint location around
            // so we always get complete hit count and breakpoint
            // lifetime info
            break_loc_sp->ClearBreakpointSite();
            if (removed_locations_event) {
              removed_locations_event->GetBreakpointLocationCollection().Add(
                  break_loc_sp);
            }
            if (delete_locations)
              locations_to_remove.Add(break_loc_sp);
          }
        }

        if (delete_locations) {
          size_t num_locations_to_remove = locations_to_remove.GetSize();
          for (loc_idx = 0; loc_idx < num_locations_to_remove; loc_idx++)
            m_locations.RemoveLocation(locations_to_remove.GetByIndex(loc_idx));
        }
      }
    }
    SendBreakpointChangedEvent(removed_locations_event);
  }
}
Ejemplo n.º 26
0
void
JITLoaderMono::ProcessEntry (uint32_t type, const addr_t addr, int64_t size)
{
	ModuleSP module_sp;

    Target &target = m_process->GetTarget();
    ModuleList &module_list = target.GetImages();

    Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER));

	switch (type) {
	case ENTRY_CODE_REGION:
		//
		// This entry defines a code region in the JIT.
		// We represent it using an lldb module.
		// The entry starts with a magic string so ReadModuleFromMemory ()
		// will create an ObjectFileMono object for it.
		//
		char jit_name[64];
		snprintf(jit_name, 64, "Mono");
		module_sp = m_process->ReadModuleFromMemory(
													FileSpec(jit_name, false), addr, size);

		if (module_sp && module_sp->GetObjectFile()) {
			bool changed;
			ObjectFileMono *ofile = (ObjectFileMono*)module_sp->GetObjectFile ();

			module_sp->GetObjectFile()->GetSymtab();

			module_list.AppendIfNeeded(module_sp);

			module_sp->SetLoadAddress(target, 0, true, changed);

			ModuleList mlist;
			mlist.Append(module_sp);
			target.ModulesDidLoad(mlist);

			m_regions [ofile->GetId ()] = ofile;
		} else {
			if (log)
				log->Printf("JITLoaderMono::%s failed to load module for "
							"JIT entry at 0x%" PRIx64,
							__FUNCTION__, addr);
		}
		break;
	case ENTRY_UNLOAD_CODE_REGION: {
		uint8_t *buf = new uint8_t [size];
		Error error;
		UnloadCodeRegionEntry *entry = (UnloadCodeRegionEntry*)buf;

		m_process->ReadMemory (addr, buf, size, error);
		assert (!error.Fail ());

		auto iter = m_regions.find (entry->id);
		assert (iter != m_regions.end ());
		ObjectFileMono *ofile = (ObjectFileMono*)iter->second;

		ModuleList mlist;
		mlist.Append(ofile->GetModule ());
		target.ModulesDidUnload(mlist, true);
		break;
	}
	case ENTRY_METHOD: {
		uint8_t *buf = new uint8_t [size];
		Error error;

		m_process->ReadMemory (addr, buf, size, error);
		assert (!error.Fail ());

		int region_id = ObjectFileMono::GetMethodEntryRegion(buf, size);

		auto iter = m_regions.find (region_id);
		assert (iter != m_regions.end ());
		ObjectFileMono *ofile = (ObjectFileMono*)iter->second;

		ofile->AddMethod (buf, size);

		// This is needed so breakpoints can be resolved
		ModuleList mlist;
		mlist.Append (ofile->GetModule ());
		target.ModulesDidLoad (mlist);
		break;
	}
	case ENTRY_TRAMPOLINE: {
		uint8_t *buf = new uint8_t [size];
		Error error;

		m_process->ReadMemory (addr, buf, size, error);
		assert (!error.Fail ());

		int region_id = ObjectFileMono::GetTrampolineEntryRegion(buf, size);

		auto iter = m_regions.find (region_id);
		assert (iter != m_regions.end ());
		ObjectFileMono *ofile = (ObjectFileMono*)iter->second;

		ofile->AddTrampoline (buf, size);
		break;
	}
	default:
		if (log)
			log->Printf("JITLoaderMono::%s unknown entry type %d", __FUNCTION__, type);
		break;
	}
}
Ejemplo n.º 27
0
void ProjectExporter::createPropertyEditors (PropertyListBuilder& props)
{
    props.add (new TextPropertyComponent (getTargetLocationValue(), "Target Project Folder", 1024, false),
               "The location of the folder in which the " + name + " project will be created. "
               "This path can be absolute, but it's much more sensible to make it relative to the jucer project directory.");

    props.add (new TextPropertyComponent (getJuceFolderValue(), "Local JUCE folder", 1024, false),
               "The location of the Juce library folder that the " + name + " project will use to when compiling. "
               "This can be an absolute path, or relative to the jucer project folder, but it must be valid on the "
               "filesystem of the machine you use to actually do the compiling.");

    OwnedArray<LibraryModule> modules;
    ModuleList moduleList;
    moduleList.rescan (ModuleList::getDefaultModulesFolder (&project));
    project.createRequiredModules (moduleList, modules);
    for (int i = 0; i < modules.size(); ++i)
        modules.getUnchecked(i)->createPropertyEditors (*this, props);

    props.add (new TextPropertyComponent (getExporterPreprocessorDefs(), "Extra Preprocessor Definitions", 32768, true),
               "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace, commas, "
               "or new-lines to separate the items - to include a space or comma in a definition, precede it with a backslash.");

    props.add (new TextPropertyComponent (getExtraCompilerFlags(), "Extra compiler flags", 2048, true),
               "Extra command-line flags to be passed to the compiler. This string can contain references to preprocessor definitions in the "
               "form ${NAME_OF_DEFINITION}, which will be replaced with their values.");

    props.add (new TextPropertyComponent (getExtraLinkerFlags(), "Extra linker flags", 2048, true),
               "Extra command-line flags to be passed to the linker. You might want to use this for adding additional libraries. "
               "This string can contain references to preprocessor definitions in the form ${NAME_OF_VALUE}, which will be replaced with their values.");

    props.add (new TextPropertyComponent (getExternalLibraries(), "External libraries to link", 2048, true),
               "Additional libraries to link (one per line). You should not add any platform specific decoration to these names. "
               "This string can contain references to preprocessor definitions in the form ${NAME_OF_VALUE}, which will be replaced with their values.");

    {
        OwnedArray<Project::Item> images;
        project.findAllImageItems (images);

        StringArray choices;
        Array<var> ids;

        choices.add ("<None>");
        ids.add (var::null);
        choices.add (String::empty);
        ids.add (var::null);

        for (int i = 0; i < images.size(); ++i)
        {
            choices.add (images.getUnchecked(i)->getName());
            ids.add (images.getUnchecked(i)->getID());
        }

        props.add (new ChoicePropertyComponent (getSmallIconImageItemID(), "Icon (small)", choices, ids),
                   "Sets an icon to use for the executable.");

        props.add (new ChoicePropertyComponent (getBigIconImageItemID(), "Icon (large)", choices, ids),
                   "Sets an icon to use for the executable.");
    }

    createExporterProperties (props);

    props.add (new TextPropertyComponent (getUserNotes(), "Notes", 32768, true),
               "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts.");
}
Ejemplo n.º 28
0
bool fillModuleListPSAPI( ModuleList& modules, DWORD pid, HANDLE hProcess )
{
	// EnumProcessModules()
	typedef BOOL (__stdcall *tEPM)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
	// GetModuleFileNameEx()
	typedef DWORD (__stdcall *tGMFNE)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
	// GetModuleBaseName() -- redundant, as GMFNE() has the same prototype, but who cares?
	typedef DWORD (__stdcall *tGMBN)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
	// GetModuleInformation()
	typedef BOOL (__stdcall *tGMI)( HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );

	HINSTANCE hPsapi;
	tEPM pEPM;
	tGMFNE pGMFNE;
	tGMBN pGMBN;
	tGMI pGMI;

	DWORD i;
	ModuleEntry e;
	DWORD cbNeeded;
	MODULEINFO mi;
	HMODULE *hMods = 0;
	char *tt = 0;
	GString g("psapi.dll");
	hPsapi = LoadLibrary( g );
	if ( hPsapi == 0 )
		return false;

	modules.clear();

	pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
	pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
	pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
	pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
	if ( pEPM == 0 || pGMFNE == 0 || pGMBN == 0 || pGMI == 0 )
	{
		FreeLibrary( hPsapi );
		return false;
	}

	hMods = new HMODULE[TTBUFLEN / sizeof(HMODULE)];
	tt = new char[TTBUFLEN];

	// check for errors and cleanup
	if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
	{
		goto cleanup;
	}

	if ( cbNeeded > TTBUFLEN )
	{
		goto cleanup;
	}

	for ( i = 0; i < cbNeeded / sizeof hMods[0]; ++ i )
	{
		// for each module, get:
		// base address, size
		pGMI( hProcess, hMods[i], &mi, sizeof mi );
		e.baseAddress = (DWORD) mi.lpBaseOfDll;
		e.size = mi.SizeOfImage;
		// image file name
		tt[0] = '\0';
		pGMFNE( hProcess, hMods[i], tt, TTBUFLEN );
		e.imageName = tt;
		// module name
		tt[0] = '\0';
		pGMBN( hProcess, hMods[i], tt, TTBUFLEN );
		e.moduleName = tt;

		modules.push_back( e );
	}

cleanup:
	if ( hPsapi )
		FreeLibrary( hPsapi );
	delete [] tt;
	delete [] hMods;

	return modules.size() != 0;
}
Ejemplo n.º 29
0
int main(int argc, char** argv) {

    using namespace Sirikata;

    DynamicLibrary::Initialize();

    InitOptions();
    Trace::Trace::InitOptions();
    SpaceTrace::InitOptions();
    InitSpaceOptions();
    ParseOptions(argc, argv, OPT_CONFIG_FILE, AllowUnregisteredOptions);

    PluginManager plugins;
    plugins.loadList( GetOptionValue<String>(OPT_PLUGINS) );
    plugins.loadList( GetOptionValue<String>(OPT_EXTRA_PLUGINS) );
    plugins.loadList( GetOptionValue<String>(OPT_SPACE_PLUGINS) );
    plugins.loadList( GetOptionValue<String>(OPT_SPACE_EXTRA_PLUGINS) );

    // Fill defaults after plugin loading to ensure plugin-added
    // options get their defaults.
    FillMissingOptionDefaults();
    // Rerun original parse to make sure any newly added options are
    // properly parsed.
    ParseOptions(argc, argv, OPT_CONFIG_FILE);

    DaemonizeAndSetOutputs();
    ReportVersion(); // After options so log goes to the right place

    std::string time_server=GetOptionValue<String>("time-server");
    NTPTimeSync sync;
    if (time_server.size() > 0)
        sync.start(time_server);

    ServerID server_id = GetOptionValue<ServerID>("id");
    String trace_file = GetPerServerFile(STATS_TRACE_FILE, server_id);
    Sirikata::Trace::Trace* gTrace = new Trace::Trace(trace_file);

    // Compute the starting date/time
    String start_time_str = GetOptionValue<String>("wait-until");
    Time start_time = start_time_str.empty() ? Timer::now() : Timer::getSpecifiedDate( start_time_str );
    start_time += GetOptionValue<Duration>("wait-additional");

    Duration duration = GetOptionValue<Duration>("duration");

    Network::IOService* ios = new Network::IOService("Space");
    Network::IOStrand* mainStrand = ios->createStrand("Space Main");

    ODPSST::ConnectionManager* sstConnMgr = new ODPSST::ConnectionManager();
    OHDPSST::ConnectionManager* ohSstConnMgr = new OHDPSST::ConnectionManager();

    SpaceContext* space_context = new SpaceContext("space", server_id, sstConnMgr, ohSstConnMgr, ios, mainStrand, start_time, gTrace, duration);

    String servermap_type = GetOptionValue<String>("servermap");
    String servermap_options = GetOptionValue<String>("servermap-options");
    ServerIDMap * server_id_map =
        ServerIDMapFactory::getSingleton().getConstructor(servermap_type)(space_context, servermap_options);

    space_context->add(space_context);


    String timeseries_type = GetOptionValue<String>(OPT_TRACE_TIMESERIES);
    String timeseries_options = GetOptionValue<String>(OPT_TRACE_TIMESERIES_OPTIONS);
    Trace::TimeSeries* time_series = Trace::TimeSeriesFactory::getSingleton().getConstructor(timeseries_type)(space_context, timeseries_options);

    String commander_type = GetOptionValue<String>(OPT_COMMAND_COMMANDER);
    String commander_options = GetOptionValue<String>(OPT_COMMAND_COMMANDER_OPTIONS);
    Command::Commander* commander = NULL;
    if (!commander_type.empty())
        commander = Command::CommanderFactory::getSingleton().getConstructor(commander_type)(space_context, commander_options);

    Transfer::TransferMediator::getSingleton().registerContext(space_context);


    Sirikata::SpaceNetwork* gNetwork = NULL;
    String network_type = GetOptionValue<String>(NETWORK_TYPE);
    if (network_type == "tcp")
      gNetwork = new TCPSpaceNetwork(space_context);

    BoundingBox3f region = GetOptionValue<BoundingBox3f>("region");
    Vector3ui32 layout = GetOptionValue<Vector3ui32>("layout");

    srand( GetOptionValue<uint32>("rand-seed") );

    ObjectHostSessionManager* oh_sess_mgr = new ObjectHostSessionManager(space_context);
    ObjectSessionManager* obj_sess_mgr = new ObjectSessionManager(space_context);

    String auth_type = GetOptionValue<String>(SPACE_OPT_AUTH);
    String auth_opts = GetOptionValue<String>(SPACE_OPT_AUTH_OPTIONS);
    Authenticator* auth =
        AuthenticatorFactory::getSingleton().getConstructor(auth_type)(space_context, auth_opts);

    gNetwork->setServerIDMap(server_id_map);


    Forwarder* forwarder = new Forwarder(space_context);


    String cseg_type = GetOptionValue<String>(CSEG);
    CoordinateSegmentation* cseg = NULL;
    if (cseg_type == "uniform")
        cseg = new UniformCoordinateSegmentation(space_context, region, layout);
    else if (cseg_type == "client") {
      cseg = new CoordinateSegmentationClient(space_context, region, layout, server_id_map);
    }
    else {
        assert(false);
        exit(-1);
    }


    String loc_update_type = GetOptionValue<String>(LOC_UPDATE);
    String loc_update_opts = GetOptionValue<String>(LOC_UPDATE_OPTIONS);
    LocationUpdatePolicy* loc_update_policy =
        LocationUpdatePolicyFactory::getSingleton().getConstructor(loc_update_type)(space_context, loc_update_opts);

    String loc_service_type = GetOptionValue<String>(LOC);
    String loc_service_opts = GetOptionValue<String>(LOC_OPTIONS);
    LocationService* loc_service =
        LocationServiceFactory::getSingleton().getConstructor(loc_service_type)(space_context, loc_update_policy, loc_service_opts);

    ServerMessageQueue* sq = NULL;
    String server_queue_type = GetOptionValue<String>(SERVER_QUEUE);
    if (server_queue_type == "fair") {
        sq = new FairServerMessageQueue(
            space_context, gNetwork,
            (ServerMessageQueue::Sender*)forwarder);
    }
    else {
        assert(false);
        exit(-1);
    }

    ServerMessageReceiver* server_message_receiver = NULL;
    String server_receiver_type = GetOptionValue<String>(SERVER_RECEIVER);
    if (server_queue_type == "fair")
        server_message_receiver =
                new FairServerMessageReceiver(space_context, gNetwork, (ServerMessageReceiver::Listener*)forwarder);
    else {
        assert(false);
        exit(-1);
    }



    LoadMonitor* loadMonitor = new LoadMonitor(space_context, cseg);


    // OSeg Cache
    OSegCache* oseg_cache = NULL;
    std::string cacheSelector = GetOptionValue<String>(CACHE_SELECTOR);
    uint32 cacheSize = GetOptionValue<uint32>(OSEG_CACHE_SIZE);
    if (cacheSelector == CACHE_TYPE_COMMUNICATION) {
        double cacheCommScaling = GetOptionValue<double>(CACHE_COMM_SCALING);
        oseg_cache = new CommunicationCache(space_context, cacheCommScaling, cseg, cacheSize);
    }
    else if (cacheSelector == CACHE_TYPE_ORIGINAL_LRU) {
        uint32 cacheCleanGroupSize = GetOptionValue<uint32>(OSEG_CACHE_CLEAN_GROUP_SIZE);
        Duration entryLifetime = GetOptionValue<Duration>(OSEG_CACHE_ENTRY_LIFETIME);
        oseg_cache = new CacheLRUOriginal(space_context, cacheSize, cacheCleanGroupSize, entryLifetime);
    }
    else {
        std::cout<<"\n\nUNKNOWN CACHE TYPE SELECTED.  Please re-try.\n\n";
        std::cout.flush();
        assert(false);
    }

    //Create OSeg
    std::string oseg_type = GetOptionValue<String>(OSEG);
    std::string oseg_options = GetOptionValue<String>(OSEG_OPTIONS);
    Network::IOStrand* osegStrand = space_context->ioService->createStrand("OSeg");
    ObjectSegmentation* oseg =
        OSegFactory::getSingleton().getConstructor(oseg_type)(space_context, osegStrand, cseg, oseg_cache, oseg_options);
    //end create oseg


    // We have all the info to initialize the forwarder now
    forwarder->initialize(oseg, sq, server_message_receiver, loc_service);

    String aggmgr_hostname = GetOptionValue<String>(OPT_AGGMGR_HOSTNAME);
    String aggmgr_service = GetOptionValue<String>(OPT_AGGMGR_SERVICE);
    String aggmgr_consumer_key = GetOptionValue<String>(OPT_AGGMGR_CONSUMER_KEY);
    String aggmgr_consumer_secret = GetOptionValue<String>(OPT_AGGMGR_CONSUMER_SECRET);
    String aggmgr_access_key = GetOptionValue<String>(OPT_AGGMGR_ACCESS_KEY);
    String aggmgr_access_secret = GetOptionValue<String>(OPT_AGGMGR_ACCESS_SECRET);
    String aggmgr_username = GetOptionValue<String>(OPT_AGGMGR_USERNAME);
    Transfer::OAuthParamsPtr aggmgr_oauth;
    // Currently you need to explicitly override hostname to enable upload
    if (!aggmgr_hostname.empty()&&
        !aggmgr_consumer_key.empty() && !aggmgr_consumer_secret.empty() &&
        !aggmgr_access_key.empty() && !aggmgr_access_secret.empty()) {
        aggmgr_oauth = Transfer::OAuthParamsPtr(
            new Transfer::OAuthParams(
                aggmgr_hostname, aggmgr_service,
                aggmgr_consumer_key, aggmgr_consumer_secret,
                aggmgr_access_key, aggmgr_access_secret
            )
        );
    }
    std::string aggmgr_type = GetOptionValue<String>(OPT_AGGMGR);
    AggregateManager* aggmgr = AggregateManagerFactory::getSingleton().getConstructor(aggmgr_type)(loc_service, aggmgr_oauth, aggmgr_username);

    std::string prox_type = GetOptionValue<String>(OPT_PROX);
    std::string prox_options = GetOptionValue<String>(OPT_PROX_OPTIONS);
    Proximity* prox = ProximityFactory::getSingleton().getConstructor(prox_type)(space_context, loc_service, cseg, gNetwork, aggmgr, prox_options);

    // We need to do an async lookup, and to finish it the server needs to be
    // running. But we can't create the server until we have the address from
    // this lookup. We isolate as little as possible into this callback --
    // creating the server, finishing prox initialization, and getting them both
    // registered. We pass storage for the Server to the callback so we can
    // handle cleaning it up ourselves.
    using std::tr1::placeholders::_1;
    using std::tr1::placeholders::_2;
    Server* server = NULL;
    ModuleList modules;
    ServerData sd;
    sd.space_context = space_context;
    sd.auth = auth;
    sd.forwarder = forwarder;
    sd.loc_service = loc_service;
    sd.cseg = cseg;
    sd.prox = prox;
    sd.oseg = oseg;
    sd.oh_sess_mgr = oh_sess_mgr;
    sd.obj_sess_mgr = obj_sess_mgr;
    server_id_map->lookupExternal(
        space_context->id(),
        space_context->mainStrand->wrap(
            std::tr1::bind( &createServer, &server, &modules, sd, _1, _2)
        )
    );

    // If we're one of the initial nodes, we'll have to wait until we hit the start time
    {
        Time now_time = Timer::now();
        if (start_time > now_time) {
            Duration sleep_time = start_time - now_time;
            printf("Waiting %f seconds\n", sleep_time.toSeconds() ); fflush(stdout);
            Timer::sleep(sleep_time);
        }
    }

    ///////////Go go go!! start of simulation/////////////////////


    space_context->add(auth);
    space_context->add(gNetwork);
    space_context->add(cseg);
    space_context->add(loc_service);
    space_context->add(oseg);
    space_context->add(loadMonitor);
    space_context->add(sstConnMgr);
    space_context->add(ohSstConnMgr);
    space_context->add(prox);

    space_context->run(3);

    space_context->cleanup();

    if (GetOptionValue<bool>(PROFILE)) {
        space_context->profiler->report();
    }

    gTrace->prepareShutdown();
    Mesh::FilterFactory::destroy();
    ModelsSystemFactory::destroy();
    LocationServiceFactory::destroy();
    LocationUpdatePolicyFactory::destroy();

    for(ModuleList::iterator it = modules.begin(); it != modules.end(); it++)
        delete *it;
    modules.clear();

    delete server;
    delete sq;
    delete server_message_receiver;
    delete prox;
    delete aggmgr;
    delete server_id_map;

    delete loadMonitor;

    delete cseg;
    delete oseg;
    delete oseg_cache;
    delete loc_service;
    delete forwarder;

    delete obj_sess_mgr;
    delete oh_sess_mgr;

    delete gNetwork;
    gNetwork=NULL;

    gTrace->shutdown();
    delete gTrace;
    gTrace = NULL;


    delete commander;

    delete space_context;
    space_context = NULL;

    delete time_series;

    delete mainStrand;
    delete osegStrand;

    delete ios;

    delete sstConnMgr;
    delete ohSstConnMgr;

    Transfer::TransferMediator::destroy();

    sync.stop();

    plugins.gc();

    Sirikata::Logging::finishLog();

    DaemonCleanup();
    return 0;
}
Ejemplo n.º 30
0
namespace lyx {


//global variable: module list
ModuleList theModuleList;


LyXModule::LyXModule(string const & n, string const & i,
	                   string const & d, vector<string> const & p,
	                   vector<string> const & r, vector<string> const & e,
			   string const & c, bool const local):
	name_(n), id_(i), description_(d), package_list_(p),
	required_modules_(r), excluded_modules_(e), category_(c),
	checked_(false), available_(false), local_(local)
{
	filename_ = id_ + ".module";
}


vector<string> LyXModule::prerequisites() const
{
	if (!checked_)
		isAvailable();
	return prerequisites_;
}


bool LyXModule::isAvailable() const
{
	if (package_list_.empty())
		return true;
	if (checked_)
		return available_;
	checked_ = true;
	available_ = true;
	//check whether all of the required packages are available
	vector<string>::const_iterator it  = package_list_.begin();
	vector<string>::const_iterator end = package_list_.end();
	for (; it != end; ++it) {
		if (!LaTeXFeatures::isAvailable(*it)) {
			available_ = false;
			prerequisites_.push_back(*it);
		}
	}
	return available_;
}


bool LyXModule::isCompatible(string const & modname) const
{
	// do we exclude it?
	if (find(excluded_modules_.begin(), excluded_modules_.end(), modname) !=
			excluded_modules_.end())
		return false;

	LyXModule const * const lm = theModuleList[modname];
	if (!lm)
		return true;

	// does it exclude us?
	vector<string> const excmods = lm->getExcludedModules();
	if (find(excmods.begin(), excmods.end(), id_) != excmods.end())
		return false;

	return true;
}


bool LyXModule::areCompatible(string const & mod1, string const & mod2)
{
	LyXModule const * const lm1 = theModuleList[mod1];
	if (lm1)
		return lm1->isCompatible(mod2);
	LyXModule const * const lm2 = theModuleList[mod2];
	if (lm2)
		return lm2->isCompatible(mod1);
	// Can't check it either way.
	return true;
}


// used when sorting the module list.
class ModuleSorter {
public:
	int operator()(LyXModule const & lm1, LyXModule const & lm2) const
	{
		return _(lm1.getName()) < _(lm2.getName());
	}
};


// Much of this is borrowed from LayoutFileList::read()
bool ModuleList::read()
{
	FileName const real_file = libFileSearch("", "lyxmodules.lst");
	LYXERR(Debug::TCLASS, "Reading modules from `" << real_file << '\'');

	if (real_file.empty()) {
		LYXERR0("unable to find modules file `lyxmodules.lst'.\n"
			<< "No modules will be available.");
		return false;
	}

	Lexer lex;
	if (!lex.setFile(real_file)) {
		LYXERR0("lyxlex was not able to set file: "
			<< real_file << ".\nNo modules will be available.");
		return false;
	}

	if (!lex.isOK()) {
		LYXERR0("unable to open modules file  `"
			<< to_utf8(makeDisplayPath(real_file.absFileName(), 1000))
			<< "'\nNo modules will be available.");
		return false;
	}

	bool finished = false;
	// Parse modules files
	LYXERR(Debug::TCLASS, "Starting parsing of lyxmodules.lst");
	while (lex.isOK() && !finished) {
		LYXERR(Debug::TCLASS, "\tline by line");
		switch (lex.lex()) {
		case Lexer::LEX_FEOF:
			finished = true;
			break;
		default:
			string const modname = lex.getString();
			LYXERR(Debug::TCLASS, "Module name: " << modname);
			if (!lex.next())
				break;
			string const fname = lex.getString();
			LYXERR(Debug::TCLASS, "Filename: " << fname);
			if (!lex.next(true))
				break;
			string const desc = lex.getString();
			LYXERR(Debug::TCLASS, "Description: " << desc);
			//FIXME Add packages
			if (!lex.next())
				break;
			string str = lex.getString();
			LYXERR(Debug::TCLASS, "Packages: " << str);
			vector<string> pkgs;
			while (!str.empty()) {
				string p;
				str = split(str, p, ',');
				pkgs.push_back(p);
			}
			if (!lex.next())
				break;
			str = lex.getString();
			LYXERR(Debug::TCLASS, "Required: " << str);
			vector<string> req;
			while (!str.empty()) {
				string p;
				str = split(str, p, '|');
				req.push_back(p);
			}
			if (!lex.next())
				break;
			str = lex.getString();
			LYXERR(Debug::TCLASS, "Excluded: " << str);
			vector<string> exc;
			while (!str.empty()) {
				string p;
				str = split(str, p, '|');
				exc.push_back(p);
			}
			if (!lex.next())
				break;
			string const catgy = lex.getString();
			LYXERR(Debug::TCLASS, "Category: " << catgy);
			if (!lex.next())
				break;
			bool const local = lex.getString() == "true";
			LYXERR(Debug::TCLASS, "Local: " << local);
			// This code is run when we have
			// modName, fname, desc, pkgs, req, exc, catgy, and local
			addLayoutModule(modname, fname, desc, pkgs, req, exc, catgy, local);
		} // end switch
	} //end while

	LYXERR(Debug::TCLASS, "End of parsing of lyxmodules.lst");

	if (!theModuleList.empty())
		sort(theModuleList.begin(), theModuleList.end(), ModuleSorter());
	return true;
}


void ModuleList::addLayoutModule(string const & modname,
	string const & filename, string const & description,
	vector<string> const & pkgs, vector<string> const & req,
	vector<string> const & exc, string const & catgy, bool const local)
{
	LyXModule lm(modname, filename, description, pkgs, req, exc, catgy, local);
	modlist_.push_back(lm);
}


LyXModuleList::const_iterator ModuleList::begin() const
{
	return modlist_.begin();
}


LyXModuleList::iterator ModuleList::begin()
{
	return modlist_.begin();
}


LyXModuleList::const_iterator ModuleList::end() const
{
	return modlist_.end();
}


LyXModuleList::iterator ModuleList::end()
{
	return modlist_.end();
}


LyXModule const * ModuleList::operator[](string const & str) const
{
	LyXModuleList::const_iterator it = modlist_.begin();
	for (; it != modlist_.end(); ++it)
		if (it->getID() == str) {
			LyXModule const & mod = *it;
			return &mod;
		}
	return 0;
}


LyXModule * ModuleList::operator[](string const & str)
{
	LyXModuleList::iterator it = modlist_.begin();
	for (; it != modlist_.end(); ++it)
		if (it->getID() == str) {
			LyXModule & mod = *it;
			return &mod;
		}
	return 0;
}

} // namespace lyx