int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) { assert(A->getOption().matches(options::OPT_fsanitize_coverage) || A->getOption().matches(options::OPT_fno_sanitize_coverage)); int Features = 0; for (int i = 0, n = A->getNumValues(); i != n; ++i) { const char *Value = A->getValue(i); int F = llvm::StringSwitch<int>(Value) .Case("func", CoverageFunc) .Case("bb", CoverageBB) .Case("edge", CoverageEdge) .Case("indirect-calls", CoverageIndirCall) .Case("trace-bb", CoverageTraceBB) .Case("trace-cmp", CoverageTraceCmp) .Case("8bit-counters", Coverage8bitCounters) .Default(0); if (F == 0) D.Diag(clang::diag::err_drv_unsupported_option_argument) << A->getOption().getName() << Value; Features |= F; } return Features; }
void common_rx_partial_packets(Driver& test, int tx) { uint8_t buffer[100]; uint8_t msg[4] = { 0, 'a', 'b', 0 }; writeToDriver(test, tx, msg, 2); BOOST_REQUIRE_THROW(test.readPacket(buffer, 100, 10), TimeoutError); writeToDriver(test, tx, msg + 2, 2); BOOST_REQUIRE_EQUAL(4, test.readPacket(buffer, 100, 10)); BOOST_REQUIRE_EQUAL(0, test.getStats().tx); BOOST_REQUIRE_EQUAL(4, test.getStats().good_rx); BOOST_REQUIRE_EQUAL(0, test.getStats().bad_rx); BOOST_REQUIRE( !memcmp(msg, buffer, 4) ); writeToDriver(test, tx, msg, 4); BOOST_REQUIRE_EQUAL(4, test.readPacket(buffer, 100, 10)); BOOST_REQUIRE_EQUAL(0, test.getStats().tx); BOOST_REQUIRE_EQUAL(8, test.getStats().good_rx); BOOST_REQUIRE_EQUAL(0, test.getStats().bad_rx); BOOST_REQUIRE( !memcmp(msg, buffer, 4) ); }
void testArbolConVariasCategorias() { Driver d; /** * cat1 * |- cat2 * \- cat3 * \- cat4 */ d.nuevoArbol("cat1"); d.agregarCategoria("cat1","cat2"); d.agregarCategoria("cat1","cat3"); d.agregarCategoria("cat3","cat4"); ASSERT_EQ(d.cantCategoriasHijas("cat1"), 2); ASSERT_EQ(d.cantCategoriasHijas("cat2"), 0); ASSERT_EQ(d.cantCategoriasHijas("cat3"), 1); }
void parseDirectory( Driver& driver, QDir& dir, bool rec, bool parseAllFiles ) { QStringList fileList; if ( parseAllFiles ) fileList = dir.entryList( QDir::Files ); else fileList = dir.entryList( "*.h;*.H;*.hh;*.hxx;*.hpp;*.tlh" ); QStringList::Iterator it = fileList.begin(); while ( it != fileList.end() ) { QString fn = dir.path() + "/" + ( *it ); ++it; driver.parseFile( fn ); } if ( rec ) { QStringList fileList = dir.entryList( QDir::Dirs ); QStringList::Iterator it = fileList.begin(); while ( it != fileList.end() ) { if ( ( *it ).startsWith( "." ) ) { ++it; continue; } QDir subdir( dir.path() + "/" + ( *it ) ); ++it; parseDirectory( driver, subdir, rec, parseAllFiles ); } } }
void test_mover_estudiante_fuera() { Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p2; p2.x = 1; p2.y = 1; Nombre s = "pepe"; campus.ingresarEstudiante(s,p2); campus.moverEstudiante(s, arriba); ASSERT(campus.cantEstudiantes() == 0); }
void commandHandler(const lcm::ReceiveBuffer* iBuf, const std::string& iChannel, const multisense::command_t* iMessage) { std::cout << "command message received" << std::endl; std::cout << " fps: " << iMessage->fps << std::endl; std::cout << " gain: " << iMessage->gain << std::endl; std::cout << " auto exposure: " << (iMessage->agc ? "true" : "false") << std::endl; std::cout << " exposure: " << iMessage->exposure_us << " us" << std::endl; std::cout << " led flash: " << (iMessage->leds_flash ? "true" : "false") << std::endl; std::cout << " led duty cycle: " << iMessage->leds_duty_cycle << std::endl; mLaser->setSpindleSpeed(iMessage->rpm); if (iMessage->fps > 0) mCamera->setFrameRate(iMessage->fps); if (iMessage->gain > 0) mCamera->setGainFactor(iMessage->gain); if (iMessage->agc == 0) mCamera->setAutoExposure(false); if ((iMessage->exposure_us > 0) && (iMessage->agc <= 0)) { mCamera->setExposureTime(iMessage->exposure_us); } if (iMessage->agc > 0) mCamera->setAutoExposure(true); if ((iMessage->leds_flash >= 0) || (iMessage->leds_duty_cycle >= 0)) { mDriver->setLedState(iMessage->leds_flash>0, iMessage->leds_duty_cycle); } }
void test_mover_estudiante() { Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p2; p2.x = 1; p2.y = 1; Nombre s = "pepe"; campus.ingresarEstudiante(s,p2); campus.moverEstudiante(s, abajo); aed2::Posicion p3; p3.x = 1; p3.y = 2; aed2::Posicion p = campus.posEstudianteYHippie(s); ASSERT(p3.x == p.x && p3.y == p.y); }
/** * Ejemplo de caso de test, con llamadas a las rutinas de aserción * definidas en mini_test.h */ void test_agregar_obstaculos() { Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p; p.x = 2; p.y = 3; campus.agregarObstaculo(p); ASSERT(campus.ocupada(p) == true); aed2::Posicion p2; p2.x = 1; p2.y = 1; ASSERT(campus.ocupada(p2) == false); }
Driver* driverFactory(Seq* seq, QString driverName) { Driver* driver = 0; #if 1 // DEBUG: force "no audio" bool useJackFlag = (preferences.useJackAudio || preferences.useJackMidi); bool useAlsaFlag = preferences.useAlsaAudio; bool usePortaudioFlag = preferences.usePortaudioAudio; bool usePulseAudioFlag = preferences.usePulseAudio; if (!driverName.isEmpty()) { driverName = driverName.toLower(); useJackFlag = false; useAlsaFlag = false; usePortaudioFlag = false; usePulseAudioFlag = false; if (driverName == "jack") useJackFlag = true; else if (driverName == "alsa") useAlsaFlag = true; else if (driverName == "pulse") usePulseAudioFlag = true; else if (driverName == "portaudio") usePortaudioFlag = true; } useALSA = false; useJACK = false; usePortaudio = false; usePulseAudio = false; #ifdef USE_PULSEAUDIO if (usePulseAudioFlag) { driver = getPulseAudioDriver(seq); if (!driver->init()) { qDebug("init PulseAudio failed"); delete driver; driver = 0; } else usePulseAudio = true; } #else (void)usePulseAudioFlag; // avoid compiler warning #endif #ifdef USE_PORTAUDIO if (usePortaudioFlag) { driver = new Portaudio(seq); if (!driver->init()) { qDebug("init PortAudio failed"); delete driver; driver = 0; } else usePortaudio = true; } #else (void)usePortaudioFlag; // avoid compiler warning #endif #ifdef USE_ALSA if (driver == 0 && useAlsaFlag) { driver = new AlsaAudio(seq); if (!driver->init()) { qDebug("init ALSA driver failed\n"); delete driver; driver = 0; } else { useALSA = true; } } #else (void)useAlsaFlag; // avoid compiler warning #endif #ifdef USE_JACK if (useJackFlag) { useAlsaFlag = false; usePortaudioFlag = false; driver = new JackAudio(seq); if (!driver->init()) { qDebug("no JACK server found\n"); delete driver; driver = 0; } else useJACK = true; } #else (void)useJackFlag; // avoid compiler warning #endif #endif if (driver == 0) qDebug("no audio driver found"); return driver; }
//----------------------------------------------------------------------------- // <Group::OnGroupChanged> // Change the group contents and notify the watchers //----------------------------------------------------------------------------- void Group::OnGroupChanged ( vector<InstanceAssociation> const& _associations ) { bool notify = false; // If the number of associations is different, we'll save // ourselves some work and clear the old set now. if( _associations.size() != m_associations.size() ) { m_associations.clear(); notify = true; } else { // Handle initial group creation case if ( _associations.size() == 0 && m_associations.size() == 0 ) { notify = true; } } // Add the new associations. uint8 oldSize = (uint8)m_associations.size(); uint8 i; for( i=0; i<_associations.size(); ++i ) { m_associations[_associations[i]] = AssociationCommandVec(); } if( (!notify) && ( oldSize != m_associations.size() ) ) { // The number of nodes in the original and new groups is the same, but // the number of associations has grown. There must be different nodes // in the original and new sets of nodes in the group. The easiest way // to sort this out is to clear the associations and add the new nodes again. m_associations.clear(); for( i=0; i<_associations.size(); ++i ) { m_associations[_associations[i]] = AssociationCommandVec(); } notify = true; } if( notify ) { // If the node supports COMMAND_CLASS_ASSOCIATION_COMMAND_CONFIGURATION, we need to request the command data. if( Driver* driver = Manager::Get()->GetDriver( m_homeId ) ) { if( Node* node = driver->GetNodeUnsafe( m_nodeId ) ) { if( AssociationCommandConfiguration* cc = static_cast<AssociationCommandConfiguration*>( node->GetCommandClass( AssociationCommandConfiguration::StaticGetCommandClassId() ) ) ) { for( map<InstanceAssociation,AssociationCommandVec,classcomp>::iterator it = m_associations.begin(); it != m_associations.end(); ++it ) { cc->RequestCommands( m_groupIdx, it->first.m_nodeId ); } } } } // Send notification that the group contents have changed Notification* notification = new Notification( Notification::Type_Group ); notification->SetHomeAndNodeIds( m_homeId, m_nodeId ); notification->SetGroupIdx( m_groupIdx ); Manager::Get()->GetDriver( m_homeId )->QueueNotification( notification ); // Update routes on remote node if necessary bool update = false; Options::Get()->GetOptionAsBool( "PerformReturnRoutes", &update ); if( update ) { Driver *drv = Manager::Get()->GetDriver( m_homeId ); if (drv) drv->UpdateNodeRoutes( m_nodeId ); } } }
// DIFICIL void test_mueve_estudiante_y_convierte() { // Testea que cuando se mueve un estudiante y rodea a un hippie se convierte Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p1; p1.x = 1; p1.y = 1; aed2::Posicion p2; p2.x = 2; p2.y = 1; aed2::Posicion p3; p3.x = 3; p3.y = 1; Nombre s1 = "pepe"; Nombre s2 = "pepo"; Nombre s3 = "pepa"; // Ingreso 3 estudiantes uno al lado del otro campus.ingresarEstudiante(s1,p1); campus.ingresarEstudiante(s2,p2); campus.ingresarEstudiante(s3,p3); // Avanzo el estudiante del medio campus.moverEstudiante(s2,abajo); campus.moverEstudiante(s2,abajo); // Ahora hago ingresar un hippie Y NO SE TIENE QUE CONVERTIR Nombre h1 = "wololoHippie"; campus.ingresarHippie(h1,p2); ASSERT(campus.cantEstudiantes() == 3); ASSERT(campus.cantHippies() == 1); // Muevo el estudiante hacia arriba y tiene que convertir talannnn campus.moverEstudiante(s2,arriba); ASSERT(campus.cantEstudiantes() == 4); ASSERT(campus.cantHippies() == 0); }
int main() { Driver driver; driver.run(); }
int main(int argc, char * argv[]) { std::cout << "\n Intel(r) Performance Counter Monitor " << INTEL_PCM_VERSION << std::endl; std::cout << "\n Power Monitoring Utility\n Copyright (c) 2011-2012 Intel Corporation\n"; int imc_profile = 0; int pcu_profile = 0; int delay = -1; char * ext_program = NULL; freq_band[0] = default_freq_band[0]; freq_band[1] = default_freq_band[1]; freq_band[2] = default_freq_band[2]; int my_opt = -1; while ((my_opt = getopt(argc, argv, "m:p:a:b:c:")) != -1) { switch(my_opt) { case 'm': imc_profile = atoi(optarg); break; case 'p': pcu_profile = atoi(optarg); break; case 'a': freq_band[0] = atoi(optarg); break; case 'b': freq_band[1] = atoi(optarg); break; case 'c': freq_band[2] = atoi(optarg); break; default: print_usage(argv[0]); return -1; } } if (optind >= argc) { print_usage(argv[0]); return -1; } delay = atoi(argv[optind]); if(delay == 0) ext_program = argv[optind]; else delay = (delay<0)?1:delay; #ifdef _MSC_VER // Increase the priority a bit to improve context switching delays on Windows SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); TCHAR driverPath[1024]; GetCurrentDirectory(1024, driverPath); wcscat(driverPath, L"\\msr.sys"); // WARNING: This driver code (msr.sys) is only for testing purposes, not for production use Driver drv; // drv.stop(); // restart driver (usually not needed) if (!drv.start(driverPath)) { std::cout << "Can not access CPU performance counters" << std::endl; std::cout << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl; return -1; } #endif PCM * m = PCM::getInstance(); m->disableJKTWorkaround(); if(!(m->hasPCICFGUncore())) { std::cout <<"Unsupported processor model ("<<m->getCPUModel()<<"). Only models "<<PCM::JAKETOWN<<" (JAKETOWN), " << PCM::IVYTOWN<< " (IVYTOWN) are supported."<< std::endl; return -1; } if(PCM::Success != m->programServerUncorePowerMetrics(imc_profile,pcu_profile,freq_band)) { #ifdef _MSC_VER std::cout << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program" << std::endl; #elif defined(__linux__) std::cout << "You need to be root and loaded 'msr' Linux kernel module to execute the program. You may load the 'msr' module with 'modprobe msr'. \n"; #endif return -1; } ServerUncorePowerState * BeforeState = new ServerUncorePowerState[m->getNumSockets()]; ServerUncorePowerState * AfterState = new ServerUncorePowerState[m->getNumSockets()]; uint64 BeforeTime = 0, AfterTime = 0; std::cout << std::dec << std::endl; std::cout.precision(2); std::cout << std::fixed; std::cout << "\nMC counter group: "<<imc_profile << std::endl; std::cout << "PCU counter group: "<<pcu_profile << std::endl; if(pcu_profile == 0) std::cout << "Freq bands [0/1/2]: "<<freq_band[0]*100 << " MHz; "<< freq_band[1]*100 << " MHz; "<<freq_band[2]*100 << " MHz; "<<std::endl; if(!ext_program) std::cout << "Update every "<<delay<<" seconds"<< std::endl; uint32 i = 0; BeforeTime = m->getTickCount(); for(i=0; i<m->getNumSockets(); ++i) BeforeState[i] = m->getServerUncorePowerState(i); while(1) { std::cout << "----------------------------------------------------------------------------------------------"<<std::endl; #ifdef _MSC_VER int delay_ms = delay * 1000; // compensate slow Windows console output if(AfterTime) delay_ms -= (int)(m->getTickCount() - BeforeTime); if(delay_ms < 0) delay_ms = 0; #else int delay_ms = delay * 1000; #endif if(ext_program) MySystem(ext_program); else MySleepMs(delay_ms); AfterTime = m->getTickCount(); for(i=0; i<m->getNumSockets(); ++i) AfterState[i] = m->getServerUncorePowerState(i); std::cout << "Time elapsed: "<<AfterTime-BeforeTime<<" ms\n"; std::cout << "Called sleep function for "<<delay_ms<<" ms\n"; for(uint32 socket=0;socket<m->getNumSockets();++socket) { for(uint32 port=0;port<m->getQPILinksPerSocket();++port) { std::cout << "S"<<socket<<"P"<<port << "; QPIClocks: "<< getQPIClocks(port,BeforeState[socket],AfterState[socket]) << "; L0p Tx Cycles: "<< 100.*getNormalizedQPIL0pTxCycles(port,BeforeState[socket],AfterState[socket])<< "%" << "; L1 Cycles: " << 100.*getNormalizedQPIL1Cycles(port,BeforeState[socket],AfterState[socket])<< "%" << "\n"; } for(uint32 channel=0;channel<m->getMCChannelsPerSocket();++channel) { if(imc_profile <= 3 && imc_profile >= 0) { std::cout << "S"<<socket<<"CH"<<channel <<"; DRAMClocks: "<< getDRAMClocks(channel,BeforeState[socket],AfterState[socket]) << "; Rank"<<getFirstRank(imc_profile)<<" CKE Off Residency: "<< std::setw(3) << 100.*getCKEOffResidency(channel,getFirstRank(imc_profile),BeforeState[socket],AfterState[socket])<<"%" << "; Rank"<<getFirstRank(imc_profile)<<" CKE Off Average Cycles: "<< getCKEOffAverageCycles(channel,getFirstRank(imc_profile),BeforeState[socket],AfterState[socket]) << "; Rank"<<getFirstRank(imc_profile)<<" Cycles per transition: "<< getCyclesPerTransition(channel,getFirstRank(imc_profile),BeforeState[socket],AfterState[socket]) << "\n"; std::cout << "S"<<socket<<"CH"<<channel <<"; DRAMClocks: "<< getDRAMClocks(channel,BeforeState[socket],AfterState[socket]) << "; Rank"<<getSecondRank(imc_profile)<<" CKE Off Residency: "<< std::setw(3) << 100.*getCKEOffResidency(channel,getSecondRank(imc_profile),BeforeState[socket],AfterState[socket])<<"%" << "; Rank"<<getSecondRank(imc_profile)<<" CKE Off Average Cycles: "<< getCKEOffAverageCycles(channel,getSecondRank(imc_profile),BeforeState[socket],AfterState[socket]) << "; Rank"<<getSecondRank(imc_profile)<<" Cycles per transition: "<< getCyclesPerTransition(channel,getSecondRank(imc_profile),BeforeState[socket],AfterState[socket]) << "\n"; } else if(imc_profile == 4) { std::cout << "S"<<socket<<"CH"<<channel << "; DRAMClocks: "<< getDRAMClocks(channel,BeforeState[socket],AfterState[socket]) << "; Self-refresh cycles: "<< getSelfRefreshCycles(channel,BeforeState[socket],AfterState[socket]) << "; Self-refresh transitions: "<< getSelfRefreshTransitions(channel,BeforeState[socket],AfterState[socket]) << "\n"; } } switch(pcu_profile) { case 0: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; Freq band 0/1/2 cycles: "<< 100.*getNormalizedPCUCounter(1,BeforeState[socket],AfterState[socket])<<"%" << "; "<< 100.*getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket])<<"%" << "; "<< 100.*getNormalizedPCUCounter(3,BeforeState[socket],AfterState[socket])<<"%" << "\n"; break; case 1: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; core C0/C3/C6-state residency: "<< getNormalizedPCUCounter(1,BeforeState[socket],AfterState[socket]) << "; "<< getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket]) << "; "<< getNormalizedPCUCounter(3,BeforeState[socket],AfterState[socket]) << "\n"; break; case 2: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; Internal prochot cycles: "<< getNormalizedPCUCounter(1,BeforeState[socket],AfterState[socket])*100. <<" %" << "; External prochot cycles:" << getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket])*100. <<" %" << "; Thermal freq limit cycles:" << getNormalizedPCUCounter(3,BeforeState[socket],AfterState[socket])*100. <<" %" << "\n"; break; case 3: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; Thermal freq limit cycles: "<< getNormalizedPCUCounter(1,BeforeState[socket],AfterState[socket])*100. <<" %" << "; Power freq limit cycles:" << getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket])*100. <<" %" << "; Clipped freq limit cycles:" << getNormalizedPCUCounter(3,BeforeState[socket],AfterState[socket])*100. <<" %" << "\n"; break; case 4: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; OS freq limit cycles: "<< getNormalizedPCUCounter(1,BeforeState[socket],AfterState[socket])*100. <<" %" << "; Power freq limit cycles:" << getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket])*100. <<" %" << "; Clipped freq limit cycles:" << getNormalizedPCUCounter(3,BeforeState[socket],AfterState[socket])*100. <<" %" << "\n"; break; case 5: std::cout << "S"<<socket << "; PCUClocks: "<< getPCUClocks(BeforeState[socket],AfterState[socket]) << "; Frequency transition count: "<< getPCUCounter(1,BeforeState[socket],AfterState[socket]) <<" " << "; Cycles spent changing frequency: " << getNormalizedPCUCounter(2,BeforeState[socket],AfterState[socket])*100. <<" %" << "\n"; break; } std::cout << "S"<<socket << "; Consumed energy units: "<< getConsumedEnergy(BeforeState[socket],AfterState[socket]) << "; Consumed Joules: "<< getConsumedJoules(BeforeState[socket],AfterState[socket]) << "; Watts: "<< 1000.*getConsumedJoules(BeforeState[socket],AfterState[socket])/double(AfterTime-BeforeTime) << "; Thermal headroom below TjMax: " << AfterState[socket].getPackageThermalHeadroom() << "\n"; std::cout << "S"<<socket << "; Consumed DRAM energy units: "<< getDRAMConsumedEnergy(BeforeState[socket],AfterState[socket]) << "; Consumed DRAM Joules: "<< getDRAMConsumedJoules(BeforeState[socket],AfterState[socket]) << "; DRAM Watts: "<< 1000.*getDRAMConsumedJoules(BeforeState[socket],AfterState[socket])/double(AfterTime-BeforeTime) << "\n"; } std::swap(BeforeState,AfterState); std::swap(BeforeTime,AfterTime); if(ext_program) { std::cout << "----------------------------------------------------------------------------------------------"<<std::endl; break; } } delete [] BeforeState; delete [] AfterState; }
Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) : Generic_ELF(D, Triple, Args) { GCCInstallation.init(Triple, Args); Multilibs = GCCInstallation.getMultilibs(); llvm::Triple::ArchType Arch = Triple.getArch(); std::string SysRoot = computeSysRoot(); // Cross-compiling binutils and GCC installations (vanilla and openSUSE at // least) put various tools in a triple-prefixed directory off of the parent // of the GCC installation. We use the GCC triple here to ensure that we end // up with tools that support the same amount of cross compiling as the // detected GCC installation. For example, if we find a GCC installation // targeting x86_64, but it is a bi-arch GCC installation, it can also be // used to target i386. // FIXME: This seems unlikely to be Linux-specific. ToolChain::path_list &PPaths = getProgramPaths(); PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" + GCCInstallation.getTriple().str() + "/bin") .str()); Distro Distro(D.getVFS()); if (Distro.IsOpenSUSE() || Distro.IsUbuntu()) { ExtraOpts.push_back("-z"); ExtraOpts.push_back("relro"); } if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) ExtraOpts.push_back("-X"); const bool IsAndroid = Triple.isAndroid(); const bool IsMips = tools::isMipsArch(Arch); const bool IsHexagon = Arch == llvm::Triple::hexagon; if (IsMips && !SysRoot.empty()) ExtraOpts.push_back("--sysroot=" + SysRoot); // Do not use 'gnu' hash style for Mips targets because .gnu.hash // and the MIPS ABI require .dynsym to be sorted in different ways. // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS // ABI requires a mapping between the GOT and the symbol table. // Android loader does not support .gnu.hash. // Hexagon linker/loader does not support .gnu.hash if (!IsMips && !IsAndroid && !IsHexagon) { if (Distro.IsRedhat() || Distro.IsOpenSUSE() || (Distro.IsUbuntu() && Distro >= Distro::UbuntuMaverick)) ExtraOpts.push_back("--hash-style=gnu"); if (Distro.IsDebian() || Distro.IsOpenSUSE() || Distro == Distro::UbuntuLucid || Distro == Distro::UbuntuJaunty || Distro == Distro::UbuntuKarmic) ExtraOpts.push_back("--hash-style=both"); } if (Distro.IsRedhat() && Distro != Distro::RHEL5 && Distro != Distro::RHEL6) ExtraOpts.push_back("--no-add-needed"); #ifdef ENABLE_LINKER_BUILD_ID ExtraOpts.push_back("--build-id"); #endif if (Distro.IsOpenSUSE()) ExtraOpts.push_back("--enable-new-dtags"); // The selection of paths to try here is designed to match the patterns which // the GCC driver itself uses, as this is part of the GCC-compatible driver. // This was determined by running GCC in a fake filesystem, creating all // possible permutations of these directories, and seeing which ones it added // to the link paths. path_list &Paths = getFilePaths(); const std::string OSLibDir = getOSLibDir(Triple, Args); const std::string MultiarchTriple = getMultiarchTriple(D, Triple, SysRoot); // Add the multilib suffixed paths where they are available. if (GCCInstallation.isValid()) { const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); const std::string &LibPath = GCCInstallation.getParentLibPath(); const Multilib &Multilib = GCCInstallation.getMultilib(); const MultilibSet &Multilibs = GCCInstallation.getMultilibs(); // Add toolchain / multilib specific file paths. addMultilibsFilePaths(D, Multilibs, Multilib, GCCInstallation.getInstallPath(), Paths); // Sourcery CodeBench MIPS toolchain holds some libraries under // a biarch-like suffix of the GCC installation. addPathIfExists(D, GCCInstallation.getInstallPath() + Multilib.gccSuffix(), Paths); // GCC cross compiling toolchains will install target libraries which ship // as part of the toolchain under <prefix>/<triple>/<libdir> rather than as // any part of the GCC installation in // <prefix>/<libdir>/gcc/<triple>/<version>. This decision is somewhat // debatable, but is the reality today. We need to search this tree even // when we have a sysroot somewhere else. It is the responsibility of // whomever is doing the cross build targeting a sysroot using a GCC // installation that is *not* within the system root to ensure two things: // // 1) Any DSOs that are linked in from this tree or from the install path // above must be present on the system root and found via an // appropriate rpath. // 2) There must not be libraries installed into // <prefix>/<triple>/<libdir> unless they should be preferred over // those within the system root. // // Note that this matches the GCC behavior. See the below comment for where // Clang diverges from GCC's behavior. addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib/../" + OSLibDir + Multilib.osSuffix(), Paths); // If the GCC installation we found is inside of the sysroot, we want to // prefer libraries installed in the parent prefix of the GCC installation. // It is important to *not* use these paths when the GCC installation is // outside of the system root as that can pick up unintended libraries. // This usually happens when there is an external cross compiler on the // host system, and a more minimal sysroot available that is the target of // the cross. Note that GCC does include some of these directories in some // configurations but this seems somewhere between questionable and simply // a bug. if (StringRef(LibPath).startswith(SysRoot)) { addPathIfExists(D, LibPath + "/" + MultiarchTriple, Paths); addPathIfExists(D, LibPath + "/../" + OSLibDir, Paths); } } // Similar to the logic for GCC above, if we currently running Clang inside // of the requested system root, add its parent library paths to // those searched. // FIXME: It's not clear whether we should use the driver's installed // directory ('Dir' below) or the ResourceDir. if (StringRef(D.Dir).startswith(SysRoot)) { addPathIfExists(D, D.Dir + "/../lib/" + MultiarchTriple, Paths); addPathIfExists(D, D.Dir + "/../" + OSLibDir, Paths); } addPathIfExists(D, SysRoot + "/lib/" + MultiarchTriple, Paths); addPathIfExists(D, SysRoot + "/lib/../" + OSLibDir, Paths); addPathIfExists(D, SysRoot + "/usr/lib/" + MultiarchTriple, Paths); addPathIfExists(D, SysRoot + "/usr/lib/../" + OSLibDir, Paths); // Try walking via the GCC triple path in case of biarch or multiarch GCC // installations with strange symlinks. if (GCCInstallation.isValid()) { addPathIfExists(D, SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() + "/../../" + OSLibDir, Paths); // Add the 'other' biarch variant path Multilib BiarchSibling; if (GCCInstallation.getBiarchSibling(BiarchSibling)) { addPathIfExists(D, GCCInstallation.getInstallPath() + BiarchSibling.gccSuffix(), Paths); } // See comments above on the multilib variant for details of why this is // included even from outside the sysroot. const std::string &LibPath = GCCInstallation.getParentLibPath(); const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); const Multilib &Multilib = GCCInstallation.getMultilib(); addPathIfExists(D, LibPath + "/../" + GCCTriple.str() + "/lib" + Multilib.osSuffix(), Paths); // See comments above on the multilib variant for details of why this is // only included from within the sysroot. if (StringRef(LibPath).startswith(SysRoot)) addPathIfExists(D, LibPath, Paths); } // Similar to the logic for GCC above, if we are currently running Clang // inside of the requested system root, add its parent library path to those // searched. // FIXME: It's not clear whether we should use the driver's installed // directory ('Dir' below) or the ResourceDir. if (StringRef(D.Dir).startswith(SysRoot)) addPathIfExists(D, D.Dir + "/../lib", Paths); addPathIfExists(D, SysRoot + "/lib", Paths); addPathIfExists(D, SysRoot + "/usr/lib", Paths); }
void UnitCfg::QueryResponse (QObject *p, const QString &c, int State, QObject*caller) // notify transaction completerequestrt needs the name record addedivityLled int2);, tion text,repprint int2);ate text); { if(p != this) return; IT_IT("UnitCfg::QueryResponse"); switch (State) { case tList: { // fill the name list box GetConfigureDb ()->FillComboBox (Name, "NAME"); Name->setCurrentItem (0); SelChanged (0); Name->setFocus (); ButtonState (true); }; break; case tItem: { IT_COMMENT("Received User Data"); // fill the fields Comment->setText (UndoEscapeSQLText(GetConfigureDb()->GetString ("COMMENT"))); SetComboItem (UnitType, GetConfigureDb ()->GetString ("UNITTYPE")); Enabled->setChecked (GetConfigureDb ()->GetString ("ENABLED").toInt ()); Comment->setFocus (); ButtonState (true); }; break; case tDrop: { int n = GetConfigureDb()->GetNumberResults(); QStringList list; QString point_list = "("; if (n) { for(int i = 0; i < n; i++,GetConfigureDb()->FetchNext()) { if(i) { point_list += ","; }; point_list += "'" + GetConfigureDb()->GetString("NAME") + "'"; // list << GetConfigureDb()->GetString ("NAME"); }; point_list += ");"; } QString cmd ="delete from TAGS_DB where NAME in " + point_list; GetCurrentDb ()->DoExec (0,cmd,0); // cmd ="delete from CVAL_DB where NAME in " + point_list; GetCurrentDb ()->DoExec (0,cmd,0); if(!list.isEmpty()) { QStringList::Iterator it = list.begin(); for(;it != list.end();++it) { QString cmd = "drop table "+ (*it) + ";"; GetResultDb()->DoExec(0,cmd,0); } } //TO DO APA caricare tutti i Driver *p in un dizionario come fa il monitor //e poi usarli quando e' necessario Driver * p = FindDriver(UnitType->currentText()); if(p) { DOAUDIT(tr("Drop Unit Tables:") + Name->currentText()); p->DropAllSpecTables(list); // invoked the unit level drop tables } } break; case tNew: case tDelete: case tApply: ButtonState (true); default: break; }; };
void test_mover_hippie_a_ingreso() { // Idea del test: el hippie se mueve hacia el estudiante // Luego el estudiante se borra // Luego el hippie se mueve al ingreso mas cercano Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p; p.x = 1; p.y = 1; Nombre t = "pepa"; campus.ingresarEstudiante(t,p); for (int i=0; i < 5; i++) { campus.moverEstudiante(t, abajo); } // Baja el estudiante aed2::Posicion p3 = campus.posEstudianteYHippie(t); ASSERT(p3.x == 1 && p3.y == 6); aed2::Posicion p2; p2.x = 1; p2.y = 1; Nombre s = "pepe"; campus.ingresarHippie(s,p2); campus.moverHippie(s); campus.moverHippie(s); // El hippie se mueve hacia abajo aed2::Posicion p4 = campus.posEstudianteYHippie(s); ASSERT(p4.x == 1 && p4.y == 3); // Hago salir al estudiante, lo muevo a la derecha para no pisar el hippie campus.moverEstudiante(t, der); for (int i=0; i < 6; i++) { campus.moverEstudiante(t, arriba); } ASSERT(campus.cantEstudiantes() == 0); // Muevo al hippie , tiene que ir al ingreso mas cercano campus.moverHippie(s); p4 = campus.posEstudianteYHippie(s); ASSERT(p4.x == 1 && p4.y == 2); }
vector<string> ConnectToDatabase::pobierzBilansKoncowy(string query){ vector<string> tempWektor; string url(EXAMPLE_HOST); const string user(EXAMPLE_USER); const string pass(EXAMPLE_PASS); const string database(EXAMPLE_DB); try { /* INSERT TUTORIAL CODE HERE! */ Driver* driver = get_driver_instance(); auto_ptr<Connection> con(driver->connect(url, user, pass)); con->setSchema(database); auto_ptr<Statement> stmt(con->createStatement()); // We need not check the return value explicitly. If it indicates // an error, Connector/C++ generates an exception. // executeQuery() wysyla zapytanie SELECT zwraca resultSet // executeUpdate() wysyla zapytanie INSERT, UPDATE lub DELETE i nie zwraca zadej wartosci // Jeśli nie wiesz z gory jakiego zapytania uzyjesz, uzyj funkcji execute() // execute() zwraca "true" jesli zapytaniem SQL bylo SELECT i "false" jesli - INSERT, UPDATE lub DELETE auto_ptr<ResultSet> res (stmt->executeQuery(query)); // Aby swtorzyc nowego klienta online, musze pobrac cztery stringi i jeden int // Stringi zapisze do tymczasowej tablicy, a int-a do int-a // next dotyczy wierszy w zwroconym wyniku while (res->next()) { /* Access column data by numeric offset, 1 is the first column */ tempWektor.push_back(res->getString(1)); tempWektor.push_back(res->getString(2)); tempWektor.push_back(res->getString(3)); tempWektor.push_back(res->getString(4)); tempWektor.push_back(res->getString(5)); } // klient = new KlientOnline(true, tempInt, tempTab[1], tempTab[0], tempTab[2], tempTab[3]); /* END OF TUTORIAL CODE */ } catch (sql::SQLException &e) { /* MySQL Connector/C++ throws three different exceptions: - sql::MethodNotImplementedException (derived from sql::SQLException) - sql::InvalidArgumentException (derived from sql::SQLException) - sql::SQLException (derived from std::runtime_error) */ cout << "# ERR: SQLException in " << __FILE__; cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl; /* what() (derived from std::runtime_error) fetches error message */ cout << "# ERR: " << e.what(); cout << " (MySQL error code: " << e.getErrorCode(); cout << ", SQLState: " << e.getSQLState() << " )" << endl; } return tempWektor; };
/** * Find the requested driver and return its class. * @param name the driver to select. * @param type the type of driver to select * @post Sets the driver so GetCurrentDriver() returns it too. */ Driver *DriverFactoryBase::SelectDriver(const char *name, Driver::Type type) { if (GetDrivers().size() == 0) return NULL; if (StrEmpty(name)) { /* Probe for this driver, but do not fall back to dedicated/null! */ for (int priority = 10; priority > 0; priority--) { Drivers::iterator it = GetDrivers().begin(); for (; it != GetDrivers().end(); ++it) { DriverFactoryBase *d = (*it).second; /* Check driver type */ if (d->type != type) continue; if (d->priority != priority) continue; Driver *newd = d->CreateInstance(); const char *err = newd->Start(NULL); if (err == NULL) { DEBUG(driver, 1, "Successfully probed %s driver '%s'", GetDriverTypeName(type), d->name); delete *GetActiveDriver(type); *GetActiveDriver(type) = newd; return newd; } DEBUG(driver, 1, "Probing %s driver '%s' failed with error: %s", GetDriverTypeName(type), d->name, err); delete newd; } } usererror("Couldn't find any suitable %s driver", GetDriverTypeName(type)); } else { char *parm; char buffer[256]; const char *parms[32]; /* Extract the driver name and put parameter list in parm */ strecpy(buffer, name, lastof(buffer)); parm = strchr(buffer, ':'); parms[0] = NULL; if (parm != NULL) { uint np = 0; /* Tokenize the parm. */ do { *parm++ = '\0'; if (np < lengthof(parms) - 1) parms[np++] = parm; while (*parm != '\0' && *parm != ',') parm++; } while (*parm == ','); parms[np] = NULL; } /* Find this driver */ Drivers::iterator it = GetDrivers().begin(); for (; it != GetDrivers().end(); ++it) { DriverFactoryBase *d = (*it).second; /* Check driver type */ if (d->type != type) continue; /* Check driver name */ if (strcasecmp(buffer, d->name) != 0) continue; /* Found our driver, let's try it */ Driver *newd = d->CreateInstance(); const char *err = newd->Start(parms); if (err != NULL) { delete newd; usererror("Unable to load driver '%s'. The error was: %s", d->name, err); } DEBUG(driver, 1, "Successfully loaded %s driver '%s'", GetDriverTypeName(type), d->name); delete *GetActiveDriver(type); *GetActiveDriver(type) = newd; return newd; } usererror("No such %s driver: %s\n", GetDriverTypeName(type), buffer); } }
int main( int argc, char** argv ) { read_dict(); std::string user( argc > 1 ? argv[1] : "root" ); std::string password( argc > 2 ? argv[2] : "root" ); std::string outpath( argc > 3 ? argv[3] : "" ); Driver *driver; Connection *con; driver = get_driver_instance(); con = driver->connect( "123.206.68.214", user.c_str(), password.c_str() ); con->setAutoCommit( 0 ); std::cerr << "\nDatabase connection\'s autocommit mode = " << con->getAutoCommit() << std::endl; DatabaseMetaData *dbcon_meta = con->getMetaData(); std::auto_ptr < ResultSet > rs( dbcon_meta->getSchemas() ); std::vector<std::string> schem_list; std::vector<build_t> zhcn_build_list; while (rs->next()) { schem_list.push_back( rs->getString( "TABLE_SCHEM" ) ); } for (auto i = schem_list.begin(); i != schem_list.end(); i++) { if (i->find( "_zhCN" ) == std::string::npos) continue; zhcn_build_list.push_back( build_t( *i ) ); } std::sort( zhcn_build_list.begin(), zhcn_build_list.end() ); build_t new_build = zhcn_build_list.rbegin()[0]; build_t old_build = zhcn_build_list.rbegin()[1]; build_tt_t old_tt, new_tt; FILE* f = fopen( outpath.c_str(), "wb" ); if ( !f ) f = stdout; get_build_tooltips( con, old_build, old_tt ); get_build_tooltips( con, new_build, new_tt ); fprintf( f, "%s - %s " u8"技能文本改动\n", old_build.toStr().c_str(), new_build.toStr().c_str() ); auto vector_diff = []( std::vector<spell_tt_t>& vold, std::vector<spell_tt_t>& vnew, std::vector<std::string>& vdiff ) { vdiff.clear(); auto i = vold.begin(); auto j = vnew.begin(); while (i != vold.end() || j != vnew.end()) { if (i != vold.end() && j != vnew.end()) { if (*i == *j) { i++; j++; } else if (*i < *j) { std::string d( u8"移除技能[del][color=red]" ); d.append( i->to_str() ); d.append( "[/color][/del]" ); vdiff.push_back( d ); i++; } else if (*j < *i) { std::string d( u8"新技能[color=green]" ); d.append( j->to_str() ); d.append( "[/color]" ); vdiff.push_back( d ); j++; } else { vdiff.push_back( *i ^ *j ); i++; j++; } } else if (i != vold.end()) { std::string d( u8"移除技能[del][color=red]" ); d.append( i->to_str() ); d.append( "[/color][/del]" ); vdiff.push_back( d ); i++; } else { std::string d( u8"新技能[color=green]" ); d.append( j->to_str() ); d.append( "[/color]" ); vdiff.push_back( d ); j++; } } }; std::vector<std::string> vdiff; for (int c = 0; c < 12; c++) { std::string class_header = "[h]"; class_header.append( new_tt.c[c].class_name ); class_header.append( "[/h][list]" ); std::string class_tail = "[/list]"; std::string universal; vector_diff( old_tt.c[c].spells, new_tt.c[c].spells, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, u8"[*]通用技能[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } vector_diff( old_tt.c[c].talents, new_tt.c[c].talents, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, u8"[*]天赋[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } vector_diff( old_tt.c[c].pvptalents, new_tt.c[c].pvptalents, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, u8"[*]PvP天赋[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } for (int s = 0; s < new_tt.c[c].specs.size(); s++) { std::string spec_header = "[*]"; spec_header.append( new_tt.c[c].specs[s].spec_name ); spec_header.append( "[list]" ); std::string spec_tail = "[/list]"; vector_diff( old_tt.c[c].specs[s].spells, new_tt.c[c].specs[s].spells, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, "%s", spec_header.c_str() ); spec_header.clear(); fprintf( f, u8"[*]专精技能[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } vector_diff( old_tt.c[c].specs[s].talents, new_tt.c[c].specs[s].talents, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, "%s", spec_header.c_str() ); spec_header.clear(); fprintf( f, u8"[*]天赋[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } vector_diff( old_tt.c[c].specs[s].pvptalents, new_tt.c[c].specs[s].pvptalents, vdiff ); if (!vdiff.empty()) { fprintf( f, "%s", class_header.c_str() ); class_header.clear(); fprintf( f, "%s", spec_header.c_str() ); spec_header.clear(); fprintf( f, u8"[*]PvP天赋[list]" ); for (auto i = vdiff.begin(); i != vdiff.end(); i++) { fprintf( f, "[*]%s", i->c_str() ); } fprintf( f, "[/list]" ); } if (spec_header.empty()) { fprintf( f, "%s", spec_tail.c_str() ); } } if (class_header.empty()) { fprintf( f, "%s", class_tail.c_str() ); } } // fclose( f ); return EXIT_SUCCESS; }
/*! Creates a declaration (header file) for the form given in \a e \sa createFormImpl() */ void Ui3Reader::createFormDecl(const QDomElement &e) { QDomElement body = e; QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); QStringList typeDefs; QMap<QString, CustomInclude> customWidgetIncludes; /* We are generating a few QImage members that are not strictly necessary in some cases. Ideally, we would use requiredImage, which is computed elsewhere, to keep the generated .h and .cpp files synchronized. */ // at first the images QMap<QString, int> customWidgets; QStringList forwardDecl; QStringList forwardDecl2; for (n = e; !n.isNull(); n = n.nextSibling().toElement()) { if (n.tagName().toLower() == QLatin1String("customwidgets")) { QDomElement n2 = n.firstChild().toElement(); while (!n2.isNull()) { if (n2.tagName().toLower() == QLatin1String("customwidget")) { QDomElement n3 = n2.firstChild().toElement(); QString cl; while (!n3.isNull()) { QString tagName = n3.tagName().toLower(); if (tagName == QLatin1String("class")) { cl = n3.firstChild().toText().data(); if (m_options & CustomWidgetForwardDeclarations) forwardDecl << cl; customWidgets.insert(cl, 0); } else if (tagName == QLatin1String("header")) { CustomInclude ci; ci.header = n3.firstChild().toText().data(); ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global")); if (!ci.header.isEmpty()) forwardDecl.removeAll(cl); customWidgetIncludes.insert(cl, ci); } n3 = n3.nextSibling().toElement(); } } n2 = n2.nextSibling().toElement(); } } } // register the object and unify its name objName = registerObject(objName); QString protector = objName.toUpper() + QLatin1String("_H"); protector.replace(QLatin1String("::"), QLatin1String("_")); out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers QStringList globalIncludes, localIncludes; { QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass); if (it != customWidgetIncludes.end()) { if ((*it).location == QLatin1String("global")) globalIncludes += (*it).header; else localIncludes += (*it).header; } } QStringList::ConstIterator it; globalIncludes = unique(globalIncludes); for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include <" << header << '>' << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include \"" << header << '\"' << endl; } } out << endl; bool dbForm = false; registerDatabases(e); dbConnections = unique(dbConnections); if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // some typedefs, maybe typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) out << "typedef " << *it << ';' << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); for (i = 0; i < (int) nl.length(); i++) forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data()); forwardDecl = unique(forwardDecl); for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != objClass) { QString forwardName = *it; QStringList forwardNamespaces = forwardName.split(QLatin1String("::")); forwardName = forwardNamespaces.last(); forwardNamespaces.removeAt(forwardNamespaces.size()-1); QStringList::ConstIterator ns = forwardNamespaces.constBegin(); while (ns != forwardNamespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class " << forwardName << ';' << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) out << '}' << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); if (!fd.endsWith(QLatin1Char(';'))) fd += QLatin1Char(';'); out << fd << endl; } out << endl; Driver d; d.option().headerProtection = false; d.option().copyrightHeader = false; d.option().extractImages = m_extractImages; d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0; d.option().qrcOutputFile = m_qrcOutputFile; d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0; if (trmacro.size()) d.option().translateFunction = trmacro; DomUI *ui = generateUi4(e); d.uic(fileName, ui, &out); delete ui; createWrapperDeclContents(e); out << "#endif // " << protector << endl; }
CudaInstallationDetector::CudaInstallationDetector( const Driver &D, const llvm::Triple &HostTriple, const llvm::opt::ArgList &Args) : D(D) { SmallVector<std::string, 4> CudaPathCandidates; // In decreasing order so we prefer newer versions to older versions. std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"}; if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) { CudaPathCandidates.push_back( Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ)); } else if (HostTriple.isOSWindows()) { for (const char *Ver : Versions) CudaPathCandidates.push_back( D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" + Ver); } else { CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda"); for (const char *Ver : Versions) CudaPathCandidates.push_back(D.SysRoot + "/usr/local/cuda-" + Ver); } for (const auto &CudaPath : CudaPathCandidates) { if (CudaPath.empty() || !D.getVFS().exists(CudaPath)) continue; InstallPath = CudaPath; BinPath = CudaPath + "/bin"; IncludePath = InstallPath + "/include"; LibDevicePath = InstallPath + "/nvvm/libdevice"; auto &FS = D.getVFS(); if (!(FS.exists(IncludePath) && FS.exists(BinPath) && FS.exists(LibDevicePath))) continue; // On Linux, we have both lib and lib64 directories, and we need to choose // based on our triple. On MacOS, we have only a lib directory. // // It's sufficient for our purposes to be flexible: If both lib and lib64 // exist, we choose whichever one matches our triple. Otherwise, if only // lib exists, we use it. if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64")) LibPath = InstallPath + "/lib64"; else if (FS.exists(InstallPath + "/lib")) LibPath = InstallPath + "/lib"; else continue; llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile = FS.getBufferForFile(InstallPath + "/version.txt"); if (!VersionFile) { // CUDA 7.0 doesn't have a version.txt, so guess that's our version if // version.txt isn't present. Version = CudaVersion::CUDA_70; } else { Version = ParseCudaVersionFile((*VersionFile)->getBuffer()); } std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef FilePath = LI->path(); StringRef FileName = llvm::sys::path::filename(FilePath); // Process all bitcode filenames that look like libdevice.compute_XX.YY.bc const StringRef LibDeviceName = "libdevice."; if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc"))) continue; StringRef GpuArch = FileName.slice( LibDeviceName.size(), FileName.find('.', LibDeviceName.size())); LibDeviceMap[GpuArch] = FilePath.str(); // Insert map entries for specifc devices with this compute // capability. NVCC's choice of the libdevice library version is // rather peculiar and depends on the CUDA version. if (GpuArch == "compute_20") { LibDeviceMap["sm_20"] = FilePath; LibDeviceMap["sm_21"] = FilePath; LibDeviceMap["sm_32"] = FilePath; } else if (GpuArch == "compute_30") { LibDeviceMap["sm_30"] = FilePath; if (Version < CudaVersion::CUDA_80) { LibDeviceMap["sm_50"] = FilePath; LibDeviceMap["sm_52"] = FilePath; LibDeviceMap["sm_53"] = FilePath; } LibDeviceMap["sm_60"] = FilePath; LibDeviceMap["sm_61"] = FilePath; LibDeviceMap["sm_62"] = FilePath; } else if (GpuArch == "compute_35") { LibDeviceMap["sm_35"] = FilePath; LibDeviceMap["sm_37"] = FilePath; } else if (GpuArch == "compute_50") { if (Version >= CudaVersion::CUDA_80) { LibDeviceMap["sm_50"] = FilePath; LibDeviceMap["sm_52"] = FilePath; LibDeviceMap["sm_53"] = FilePath; } } } IsValid = true; break; } }
bool render_with_preview(Driver &driver){ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0){ std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return false; } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); #ifdef DEBUG SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG); #endif const RenderTarget &target = driver.get_scene().get_render_target(); SDL_Window *win = SDL_CreateWindow("tray render", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, target.get_width(), target.get_height(), SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(win); if (ogl_LoadFunctions() == ogl_LOAD_FAILED){ std::cerr << "ogl failed to load OpenGL functions" << std::endl; SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); SDL_Quit(); return false; } glClearColor(0.f, 0.f, 0.f, 1.f); glClearDepth(1.f); #ifdef DEBUG glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageCallbackARB(util::gldebug_callback, NULL); glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE); #endif GLint program = util::load_program(VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC); if (program == -1){ std::cerr << "GLSL shader failed to compile, aborting\n"; SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); SDL_Quit(); return false; } glUseProgram(program); GLuint color; glGenTextures(1, &color); glBindTexture(GL_TEXTURE_2D, color); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, target.get_width(), target.get_height(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); //Disable linear filtering so the image is only as nice as the ray tracer renders it glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //A dummy vao, required for core profile but we don't really need it GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); //Run the driver so it renders while we update the texture with the //new output from it std::vector<Color24> color_buf(target.get_width() * target.get_height()); driver.render(); //We also track if we're done so we can stop updating the textures after doing a last //update bool quit = false, render_done = false; while (!quit){ SDL_Event e; while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)){ driver.cancel(); quit = true; } } //Let the driver do some work SDL_Delay(16); //Update the texture with new data. //We could do better and only update blocks of updated pixels, but this is more //work than I want to put into this if (!render_done){ render_done = driver.done(); target.get_colorbuf(color_buf); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, target.get_width(), target.get_height(), GL_RGB, GL_UNSIGNED_BYTE, color_buf.data()); } glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); SDL_GL_SwapWindow(win); } glDeleteProgram(program); glDeleteTextures(1, &color); glDeleteVertexArrays(1, &vao); SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); SDL_Quit(); //If the user aborted we may not have finished the render so report our status return driver.done(); }
void test_mover_hippie_a_estudiante() { Driver campus; campus.crearCampus(10,10); Dicc<Agente,aed2::Posicion> agentes; campus.comenzarRastrillaje(agentes); aed2::Posicion p; p.x = 1; p.y = 1; Nombre t = "pepa"; campus.ingresarEstudiante(t,p); campus.moverEstudiante(t, abajo); campus.moverEstudiante(t, abajo); campus.moverEstudiante(t, abajo); campus.moverEstudiante(t, abajo); campus.moverEstudiante(t, abajo); // Baja el estudiante aed2::Posicion p3 = campus.posEstudianteYHippie(t); ASSERT(p3.x == 1 && p3.y == 6); aed2::Posicion p2; p2.x = 1; p2.y = 1; Nombre s = "pepe"; campus.ingresarHippie(s,p2); campus.moverHippie(s); // El hippie se mueve hacia abajo aed2::Posicion p4 = campus.posEstudianteYHippie(s); ASSERT(p4.x == 1 && p4.y == 2); aed2::Posicion p5; p5.x = 3; p5.y = 1; Nombre r = "pepo"; campus.ingresarEstudiante(r,p5); // El hippie se mueve hacia el nuevo estudiante campus.moverHippie(s); p4 = campus.posEstudianteYHippie(s); ASSERT((p4.x == 1 && p4.y == 1) || (p4.x == 2 && p4.y == 2) ); }
CudaInstallationDetector::CudaInstallationDetector( const Driver &D, const llvm::Triple &HostTriple, const llvm::opt::ArgList &Args) : D(D) { struct Candidate { std::string Path; bool StrictChecking; Candidate(std::string Path, bool StrictChecking = false) : Path(Path), StrictChecking(StrictChecking) {} }; SmallVector<Candidate, 4> Candidates; // In decreasing order so we prefer newer versions to older versions. std::initializer_list<const char *> Versions = {"8.0", "7.5", "7.0"}; if (Args.hasArg(clang::driver::options::OPT_cuda_path_EQ)) { Candidates.emplace_back( Args.getLastArgValue(clang::driver::options::OPT_cuda_path_EQ).str()); } else if (HostTriple.isOSWindows()) { for (const char *Ver : Versions) Candidates.emplace_back( D.SysRoot + "/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v" + Ver); } else { if (!Args.hasArg(clang::driver::options::OPT_cuda_path_ignore_env)) { // Try to find ptxas binary. If the executable is located in a directory // called 'bin/', its parent directory might be a good guess for a valid // CUDA installation. // However, some distributions might installs 'ptxas' to /usr/bin. In that // case the candidate would be '/usr' which passes the following checks // because '/usr/include' exists as well. To avoid this case, we always // check for the directory potentially containing files for libdevice, // even if the user passes -nocudalib. if (llvm::ErrorOr<std::string> ptxas = llvm::sys::findProgramByName("ptxas")) { SmallString<256> ptxasAbsolutePath; llvm::sys::fs::real_path(*ptxas, ptxasAbsolutePath); StringRef ptxasDir = llvm::sys::path::parent_path(ptxasAbsolutePath); if (llvm::sys::path::filename(ptxasDir) == "bin") Candidates.emplace_back(llvm::sys::path::parent_path(ptxasDir), /*StrictChecking=*/true); } } Candidates.emplace_back(D.SysRoot + "/usr/local/cuda"); for (const char *Ver : Versions) Candidates.emplace_back(D.SysRoot + "/usr/local/cuda-" + Ver); if (Distro(D.getVFS()).IsDebian()) // Special case for Debian to have nvidia-cuda-toolkit work // out of the box. More info on http://bugs.debian.org/882505 Candidates.emplace_back(D.SysRoot + "/usr/lib/cuda"); } bool NoCudaLib = Args.hasArg(options::OPT_nocudalib); for (const auto &Candidate : Candidates) { InstallPath = Candidate.Path; if (InstallPath.empty() || !D.getVFS().exists(InstallPath)) continue; BinPath = InstallPath + "/bin"; IncludePath = InstallPath + "/include"; LibDevicePath = InstallPath + "/nvvm/libdevice"; auto &FS = D.getVFS(); if (!(FS.exists(IncludePath) && FS.exists(BinPath))) continue; bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking); if (CheckLibDevice && !FS.exists(LibDevicePath)) continue; // On Linux, we have both lib and lib64 directories, and we need to choose // based on our triple. On MacOS, we have only a lib directory. // // It's sufficient for our purposes to be flexible: If both lib and lib64 // exist, we choose whichever one matches our triple. Otherwise, if only // lib exists, we use it. if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64")) LibPath = InstallPath + "/lib64"; else if (FS.exists(InstallPath + "/lib")) LibPath = InstallPath + "/lib"; else continue; llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile = FS.getBufferForFile(InstallPath + "/version.txt"); if (!VersionFile) { // CUDA 7.0 doesn't have a version.txt, so guess that's our version if // version.txt isn't present. Version = CudaVersion::CUDA_70; } else { Version = ParseCudaVersionFile((*VersionFile)->getBuffer()); } if (Version >= CudaVersion::CUDA_90) { // CUDA-9+ uses single libdevice file for all GPU variants. std::string FilePath = LibDevicePath + "/libdevice.10.bc"; if (FS.exists(FilePath)) { for (const char *GpuArchName : {"sm_20", "sm_30", "sm_32", "sm_35", "sm_50", "sm_52", "sm_53", "sm_60", "sm_61", "sm_62", "sm_70", "sm_72"}) { const CudaArch GpuArch = StringToCudaArch(GpuArchName); if (Version >= MinVersionForCudaArch(GpuArch) && Version <= MaxVersionForCudaArch(GpuArch)) LibDeviceMap[GpuArchName] = FilePath; } } } else { std::error_code EC; for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE; !EC && LI != LE; LI = LI.increment(EC)) { StringRef FilePath = LI->path(); StringRef FileName = llvm::sys::path::filename(FilePath); // Process all bitcode filenames that look like // libdevice.compute_XX.YY.bc const StringRef LibDeviceName = "libdevice."; if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc"))) continue; StringRef GpuArch = FileName.slice( LibDeviceName.size(), FileName.find('.', LibDeviceName.size())); LibDeviceMap[GpuArch] = FilePath.str(); // Insert map entries for specifc devices with this compute // capability. NVCC's choice of the libdevice library version is // rather peculiar and depends on the CUDA version. if (GpuArch == "compute_20") { LibDeviceMap["sm_20"] = FilePath; LibDeviceMap["sm_21"] = FilePath; LibDeviceMap["sm_32"] = FilePath; } else if (GpuArch == "compute_30") { LibDeviceMap["sm_30"] = FilePath; if (Version < CudaVersion::CUDA_80) { LibDeviceMap["sm_50"] = FilePath; LibDeviceMap["sm_52"] = FilePath; LibDeviceMap["sm_53"] = FilePath; } LibDeviceMap["sm_60"] = FilePath; LibDeviceMap["sm_61"] = FilePath; LibDeviceMap["sm_62"] = FilePath; } else if (GpuArch == "compute_35") { LibDeviceMap["sm_35"] = FilePath; LibDeviceMap["sm_37"] = FilePath; } else if (GpuArch == "compute_50") { if (Version >= CudaVersion::CUDA_80) { LibDeviceMap["sm_50"] = FilePath; LibDeviceMap["sm_52"] = FilePath; LibDeviceMap["sm_53"] = FilePath; } } } } // Check that we have found at least one libdevice that we can link in if // -nocudalib hasn't been specified. if (LibDeviceMap.empty() && !NoCudaLib) continue; IsValid = true; break; } }
void test_mas_vigilante() { // 3 primeras lineas antes de que ingresen los estudiantes // 1 2 3 4 5 // 1 | A | | A | | O // 2 | | A | | O | // 3 ... // Los hippies ingresan en (2,1) y (4,1) los huecos. El Agente en (3,1) se transforma en el mas vigilante Driver campus; campus.crearCampus(10,10); aed2::Posicion o; o.x = 4; o.y = 2; campus.agregarObstaculo(o); aed2::Posicion o2; o2.x = 5; o2.y = 1; campus.agregarObstaculo(o2); Dicc<Agente,aed2::Posicion> agentes; Agente a = 1; Agente a2 = 2; Agente a3 = 3; aed2::Posicion p; p.x = 1; p.y = 1; aed2::Posicion p2; p2.x = 2; p2.y = 2; aed2::Posicion p3; p3.x = 3; p3.y = 1; agentes.Definir(a,p); agentes.Definir(a2,p2); agentes.Definir(a3,p3); campus.comenzarRastrillaje(agentes); aed2::Posicion ph; ph.x = 2; ph.y = 1; Nombre h = "hippie"; campus.ingresarHippie(h,ph); aed2::Posicion ph2; ph2.x = 4; ph2.y = 1; Nombre h2 = "hippie2"; campus.ingresarHippie(h2,ph2); ASSERT(campus.cantHippiesAtrapados(a) == 1); ASSERT(campus.cantHippiesAtrapados(a2) == 1); ASSERT(campus.cantHippiesAtrapados(a3) == 2); ASSERT(campus.masVigilante() == a3); }
void menuscreen_create_menu(void) { Menu *options_menu; Menu *driver_menu; MenuItem *checkbox; MenuItem *slider; Driver *driver; debug(RPT_DEBUG, "%s()", __FUNCTION__); main_menu = menu_create("mainmenu", NULL, "LCDproc Menu", NULL); if (main_menu == NULL) { report(RPT_ERR, "%s: Cannot create main menu", __FUNCTION__); return; } options_menu = menu_create("options", NULL, "Options", NULL); if (options_menu == NULL) { report(RPT_ERR, "%s: Cannot create options menu", __FUNCTION__); return; } menu_add_item(main_menu, options_menu); #ifdef LCDPROC_TESTMENUS /* * TODO: Menu items in the screens menu currently have no functions * assigned. Therefore only enable the menu for testing. If functions * are available, this code should be outside the #ifdef. */ screens_menu = menu_create("screens", NULL, "Screens", NULL); if (screens_menu == NULL) { report(RPT_ERR, "%s: Cannot create screens menu", __FUNCTION__); return; } menu_add_item(main_menu, screens_menu); menuscreen_create_testmenu(); #endif /* * add option menu contents: menu's client is NULL since we're in the * server */ checkbox = menuitem_create_checkbox("heartbeat", heartbeat_handler, "Heartbeat", NULL, true, heartbeat); menu_add_item(options_menu, checkbox); checkbox = menuitem_create_checkbox("backlight", backlight_handler, "Backlight", NULL, true, backlight); menu_add_item(options_menu, checkbox); slider = menuitem_create_slider("titlespeed", titlespeed_handler, "TitleSpeed", NULL, "0", "10", TITLESPEED_NO, TITLESPEED_MAX, 1, titlespeed); menu_add_item(options_menu, slider); /* * add driver specific option menus for each driver: menu's client is * NULL since we're in the server */ for (driver = drivers_getfirst(); driver; driver = drivers_getnext()) { int contrast_avail = (driver->get_contrast && driver->set_contrast) ? 1 : 0; int brightness_avail = (driver->get_brightness && driver->set_brightness) ? 1 : 0; if (contrast_avail || brightness_avail) { /* menu's client is NULL since we're in the server */ driver_menu = menu_create(driver->name, NULL, driver->name, NULL); if (driver_menu == NULL) { report(RPT_ERR, "%s: Cannot create menu for driver %s", __FUNCTION__, driver->name); continue; } menu_set_association(driver_menu, driver); menu_add_item(options_menu, driver_menu); if (contrast_avail) { int contrast = driver->get_contrast(driver); /* menu's client is NULL since we're in the server */ slider = menuitem_create_slider("contrast", contrast_handler, "Contrast", NULL, "min", "max", 0, 1000, 25, contrast); menu_add_item(driver_menu, slider); } if (brightness_avail) { int onbrightness = driver->get_brightness(driver, BACKLIGHT_ON); int offbrightness = driver->get_brightness(driver, BACKLIGHT_OFF); slider = menuitem_create_slider("onbrightness", brightness_handler, "On Brightness", NULL, "min", "max", 0, 1000, 25, onbrightness); menu_add_item(driver_menu, slider); slider = menuitem_create_slider("offbrightness", brightness_handler, "Off Brightness", NULL, "min", "max", 0, 1000, 25, offbrightness); menu_add_item(driver_menu, slider); } } } }
// Gator data flow: collector -> collector fifo -> sender int main(int argc, char** argv) { // Ensure proper signal handling by making gatord the process group leader // e.g. it may not be the group leader when launched as 'sudo gatord' setsid(); // Set up global thread-safe logging logg = new Logging(hasDebugFlag(argc, argv)); // Global data class gSessionData = new SessionData(); // Set up global utility class util = new OlyUtility(); // Initialize drivers new CCNDriver(); prctl(PR_SET_NAME, (unsigned long)&"gatord-main", 0, 0, 0); pthread_mutex_init(&numSessions_mutex, NULL); signal(SIGINT, handler); signal(SIGTERM, handler); signal(SIGABRT, handler); // Set to high priority if (setpriority(PRIO_PROCESS, syscall(__NR_gettid), -19) == -1) { logg->logMessage("setpriority() failed"); } // Parse the command line parameters struct cmdline_t cmdline = parseCommandLine(argc, argv); if (cmdline.update) { return update(argv[0]); } // Verify root permissions uid_t euid = geteuid(); if (euid) { logg->logError(__FILE__, __LINE__, "gatord must be launched with root privileges"); handleException(); } // Call before setting up the SIGCHLD handler, as system() spawns child processes if (!setupFilesystem(cmdline.module)) { logg->logMessage("Unable to setup gatorfs, trying perf"); if (!gSessionData->perf.setup()) { logg->logError(__FILE__, __LINE__, "Unable to locate gator.ko driver:\n" " >>> gator.ko should be co-located with gatord in the same directory\n" " >>> OR insmod gator.ko prior to launching gatord\n" " >>> OR specify the location of gator.ko on the command line\n" " >>> OR run Linux 3.4 or later with perf (CONFIG_PERF_EVENTS and CONFIG_HW_PERF_EVENTS) and tracing (CONFIG_TRACING and CONFIG_CONTEXT_SWITCH_TRACER) support to collect data via userspace only"); handleException(); } } { EventsXML eventsXML; mxml_node_t *xml = eventsXML.getTree(); // Initialize all drivers for (Driver *driver = Driver::getHead(); driver != NULL; driver = driver->getNext()) { driver->readEvents(xml); } mxmlDelete(xml); } // Handle child exit codes signal(SIGCHLD, child_exit); // Ignore the SIGPIPE signal so that any send to a broken socket will return an error code instead of asserting a signal // Handling the error at the send function call is much easier than trying to do anything intelligent in the sig handler signal(SIGPIPE, SIG_IGN); // If the command line argument is a session xml file, no need to open a socket if (gSessionData->mSessionXMLPath) { child = new Child(); child->run(); delete child; } else { gSessionData->annotateListener.setup(); sock = new OlyServerSocket(cmdline.port); udpListener.setup(cmdline.port); if (!monitor.init() || !monitor.add(sock->getFd()) || !monitor.add(udpListener.getReq()) || !monitor.add(gSessionData->annotateListener.getFd()) || false) { logg->logError(__FILE__, __LINE__, "Monitor setup failed"); handleException(); } // Forever loop, can be exited via a signal or exception while (1) { struct epoll_event events[2]; logg->logMessage("Waiting on connection..."); int ready = monitor.wait(events, ARRAY_LENGTH(events), -1); if (ready < 0) { logg->logError(__FILE__, __LINE__, "Monitor::wait failed"); handleException(); } for (int i = 0; i < ready; ++i) { if (events[i].data.fd == sock->getFd()) { handleClient(); } else if (events[i].data.fd == udpListener.getReq()) { udpListener.handle(); } else if (events[i].data.fd == gSessionData->annotateListener.getFd()) { gSessionData->annotateListener.handle(); } } } } cleanUp(); return 0; }
int main () { Driver mainDriver; mainDriver.Run(); return 0; }
/// \brief Get our best guess at the multiarch triple for a target. /// /// Debian-based systems are starting to use a multiarch setup where they use /// a target-triple directory in the library and header search paths. /// Unfortunately, this triple does not align with the vanilla target triple, /// so we provide a rough mapping here. static std::string getMultiarchTriple(const Driver &D, const llvm::Triple &TargetTriple, StringRef SysRoot) { llvm::Triple::EnvironmentType TargetEnvironment = TargetTriple.getEnvironment(); // For most architectures, just use whatever we have rather than trying to be // clever. switch (TargetTriple.getArch()) { default: break; // We use the existence of '/lib/<triple>' as a directory to detect some // common linux triples that don't quite match the Clang triple for both // 32-bit and 64-bit targets. Multiarch fixes its install triples to these // regardless of what the actual target triple is. case llvm::Triple::arm: case llvm::Triple::thumb: if (TargetEnvironment == llvm::Triple::GNUEABIHF) { if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabihf")) return "arm-linux-gnueabihf"; } else { if (D.getVFS().exists(SysRoot + "/lib/arm-linux-gnueabi")) return "arm-linux-gnueabi"; } break; case llvm::Triple::armeb: case llvm::Triple::thumbeb: if (TargetEnvironment == llvm::Triple::GNUEABIHF) { if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabihf")) return "armeb-linux-gnueabihf"; } else { if (D.getVFS().exists(SysRoot + "/lib/armeb-linux-gnueabi")) return "armeb-linux-gnueabi"; } break; case llvm::Triple::x86: if (D.getVFS().exists(SysRoot + "/lib/i386-linux-gnu")) return "i386-linux-gnu"; break; case llvm::Triple::x86_64: // We don't want this for x32, otherwise it will match x86_64 libs if (TargetEnvironment != llvm::Triple::GNUX32 && D.getVFS().exists(SysRoot + "/lib/x86_64-linux-gnu")) return "x86_64-linux-gnu"; break; case llvm::Triple::aarch64: if (D.getVFS().exists(SysRoot + "/lib/aarch64-linux-gnu")) return "aarch64-linux-gnu"; break; case llvm::Triple::aarch64_be: if (D.getVFS().exists(SysRoot + "/lib/aarch64_be-linux-gnu")) return "aarch64_be-linux-gnu"; break; case llvm::Triple::mips: if (D.getVFS().exists(SysRoot + "/lib/mips-linux-gnu")) return "mips-linux-gnu"; break; case llvm::Triple::mipsel: if (D.getVFS().exists(SysRoot + "/lib/mipsel-linux-gnu")) return "mipsel-linux-gnu"; break; case llvm::Triple::mips64: if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnu")) return "mips64-linux-gnu"; if (D.getVFS().exists(SysRoot + "/lib/mips64-linux-gnuabi64")) return "mips64-linux-gnuabi64"; break; case llvm::Triple::mips64el: if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnu")) return "mips64el-linux-gnu"; if (D.getVFS().exists(SysRoot + "/lib/mips64el-linux-gnuabi64")) return "mips64el-linux-gnuabi64"; break; case llvm::Triple::ppc: if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnuspe")) return "powerpc-linux-gnuspe"; if (D.getVFS().exists(SysRoot + "/lib/powerpc-linux-gnu")) return "powerpc-linux-gnu"; break; case llvm::Triple::ppc64: if (D.getVFS().exists(SysRoot + "/lib/powerpc64-linux-gnu")) return "powerpc64-linux-gnu"; break; case llvm::Triple::ppc64le: if (D.getVFS().exists(SysRoot + "/lib/powerpc64le-linux-gnu")) return "powerpc64le-linux-gnu"; break; case llvm::Triple::sparc: if (D.getVFS().exists(SysRoot + "/lib/sparc-linux-gnu")) return "sparc-linux-gnu"; break; case llvm::Triple::sparcv9: if (D.getVFS().exists(SysRoot + "/lib/sparc64-linux-gnu")) return "sparc64-linux-gnu"; break; case llvm::Triple::systemz: if (D.getVFS().exists(SysRoot + "/lib/s390x-linux-gnu")) return "s390x-linux-gnu"; break; } return TargetTriple.str(); }
int runUic(int argc, char *argv[]) { Driver driver; const char *fileName = 0; int arg = 1; while (arg < argc) { QString opt = QString::fromLocal8Bit(argv[arg]); if (opt == QLatin1String("-h") || opt == QLatin1String("-help")) { showHelp(argv[0]); return 0; } else if (opt == QLatin1String("-d") || opt == QLatin1String("-dependencies")) { driver.option().dependencies = true; } else if (opt == QLatin1String("-v") || opt == QLatin1String("-version")) { fprintf(stderr, "Qt User Interface Compiler version %s\n", QT_VERSION_STR); return 0; } else if (opt == QLatin1String("-o") || opt == QLatin1String("-output")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().outputFile = QFile::decodeName(argv[arg]); #ifdef QT_UIC_PERL_GENERATOR } else if (opt == QLatin1String("-x")) { driver.option().execCode = 1; } else if (opt == QLatin1String("-k") || opt == QLatin1String("-kde")) { driver.option().useKDE = 1; #endif } else if (opt == QLatin1String("-p") || opt == QLatin1String("-no-protection")) { driver.option().headerProtection = false; } else if (opt == QLatin1String("-n") || opt == QLatin1String("-no-implicit-includes")) { driver.option().implicitIncludes = false; } else if (opt == QLatin1String("-postfix")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().postfix = QLatin1String(argv[arg]); } else if (opt == QLatin1String("-3")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().uic3 = QFile::decodeName(argv[arg]); } else if (opt == QLatin1String("-tr") || opt == QLatin1String("-translate")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } driver.option().translateFunction = QLatin1String(argv[arg]); } else if (opt == QLatin1String("-g") || opt == QLatin1String("-generator")) { ++arg; if (!argv[arg]) { showHelp(argv[0]); return 1; } QString name = QString::fromLocal8Bit(argv[arg]).toLower (); if (name == QLatin1String("java")) { driver.option().generator = Option::JavaGenerator; } else if (name == QLatin1String("perl")) { driver.option().generator = Option::PerlGenerator; } else { driver.option().generator = Option::CppGenerator; } } else if (!fileName) { fileName = argv[arg]; } else { showHelp(argv[0]); return 1; } ++arg; } QString inputFile; if (fileName) inputFile = QString::fromLocal8Bit(fileName); else driver.option().headerProtection = false; if (driver.option().dependencies) { return !driver.printDependencies(inputFile); } QTextStream *out = 0; QFile f; if (driver.option().outputFile.size()) { f.setFileName(driver.option().outputFile); if (!f.open(QIODevice::WriteOnly | QFile::Text)) { fprintf(stderr, "Could not create output file\n"); return 1; } out = new QTextStream(&f); out->setCodec(QTextCodec::codecForName("UTF-8")); } bool rtn = driver.uic(inputFile, out); delete out; if (!rtn) { if (driver.option().outputFile.size()) { f.close(); f.remove(); } fprintf(stderr, "File '%s' is not valid\n", inputFile.isEmpty() ? "<stdin>" : inputFile.toLocal8Bit().constData()); } return !rtn; }