Example #1
0
/**
* Check to see if we have a local database already.
* If it is, then check if it is up to date.
* If local database is missing or obsolete then recreate it.
* Return true if application has a local items database to run with, false otherwise.
*/
bool DBManager::syncLocalItemsDB(std::tstring const& localfile, std::tstring const& aofolder)
{
    bool hasLocalDB = false;
    std::time_t lastUpdateTime;

    bfs::path local(to_ascii_copy (localfile));
    bfs::path original(to_ascii_copy (aofolder));
    original = original / "cd_image/data/db/ResourceDatabase.dat";

    if (bfs::exists(local) && bfs::is_regular(local))
    {
        hasLocalDB = true;
        lastUpdateTime = bfs::last_write_time(local);
    }

    if (!exists(original))
    {
        Logger::instance().log(_T("Could not locate the original AO database."));
        return hasLocalDB;
    }

    if (hasLocalDB && getAODBSchemeVersion(localfile) == CURRENT_AODB_VERSION)
    {
        std::time_t lastOriginalUpdateTime = bfs::last_write_time(original);
        if (lastOriginalUpdateTime <= lastUpdateTime)
        {
            return true;
        }

        // Ask user if he wants to continue using the old (but compatible) DB or update it now.
        int answer = ::MessageBox(NULL,
                                  _T("You items database is out of date. Do you wish to update it now?\r\nAnswering 'NO' will continue using the old one."),
                                  _T("Question - AO Item Assistant++"), MB_ICONQUESTION | MB_YESNOCANCEL);
        if (answer == IDCANCEL)
        {
            exit(0);
        }
        else if (answer == IDNO)
        {
            return true;
        }
    }

    // If we come this far we need to update the DB.

    bfs::path tmpfile("tmp_" + local.string());
    bfs::remove(tmpfile);

    try
    {
        std::set<ResourceType> resource_types = boost::assign::list_of(AODB_TYP_ITEM)(AODB_TYP_NANO);
        AODatabaseIndex indexer(to_ascii_copy(aofolder) + "/cd_image/data/db/ResourceDatabase.idx", resource_types);
        std::vector<unsigned int> item_offsets = indexer.GetOffsets(AODB_TYP_ITEM);
        std::vector<unsigned int> nano_offsets = indexer.GetOffsets(AODB_TYP_NANO);
        unsigned int itemCount = item_offsets.size();
        unsigned int nanoCount = nano_offsets.size();

        std::vector<std::string> original_files = boost::assign::list_of(original.string())(original.string()+".001")(original.string()+".002");
        AODatabaseParser aodb(original_files);
        AODatabaseWriter writer(tmpfile.string(), Logger::instance().stream());

        CProgressDialog dlg(itemCount + nanoCount, itemCount);
        dlg.SetWindowText(_T("Progress Dialog - Item Assistant"));
        dlg.setText(0, _T("Extracting data from the AO DB..."));
        dlg.setText(1, STREAM2STR("Finished " << 0 << " out of " << itemCount << " items."));
        dlg.setText(2, _T("Overall progress: 0%"));

        // Extract items
        boost::shared_ptr<ao_item> item;
        unsigned int count = 0;
        writer.BeginWrite();
        for (std::vector<unsigned int>::iterator item_it = item_offsets.begin(); item_it != item_offsets.end(); ++item_it)
        {
            item = aodb.GetItem(*item_it);
            count++;
            if (!item)
            {
                LOG(_T("Parsing item ") << count << _T(" at offset ") << *item_it << _T(" failed!"));
                continue;
            }
            writer.WriteItem(item);
            if (count % 1000 == 0) {
                if (dlg.userCanceled()) {
                    return false;
                }
                dlg.setTaskProgress(count, itemCount);
                dlg.setText(1, STREAM2STR("Finished " << count << " out of " << itemCount << " items."));
                dlg.setOverallProgress(count, itemCount + nanoCount);
                dlg.setText(2, STREAM2STR("Overall progress: " << (count * 100) / max(1, itemCount + nanoCount) << "%"));
            }
            if (count % 10000 == 0) {
                writer.CommitItems();
                writer.BeginWrite();
            }
        }
        item.reset();
        dlg.setTaskProgress(count, itemCount);
        dlg.setText(1, STREAM2STR("Finished " << count << " out of " << itemCount << " items."));
        dlg.setOverallProgress(count, itemCount + nanoCount);
        dlg.setText(2, STREAM2STR("Overall progress: " << (count * 100) / max(1, itemCount + nanoCount) << "%"));
        writer.CommitItems();

        if (dlg.userCanceled())
        {
            return false;
        }

        // Extract nano programs
        boost::shared_ptr<ao_item> nano;
        count = 0;
        writer.BeginWrite();
        for (std::vector<unsigned int>::iterator nano_it = nano_offsets.begin(); nano_it != nano_offsets.end(); ++nano_it)
        {
            nano = aodb.GetItem(*nano_it);
            count++;
            if (!nano)
            {
                LOG(_T("Parsing nano ") << count << _T(" at offset ") << *nano_it << _T(" failed!"));
                continue;
            }
            writer.WriteItem(nano);
            if (count % 1000 == 0)
            {
                if (dlg.userCanceled())
                {
                    return false;
                }
                dlg.setTaskProgress(count, nanoCount);
                dlg.setText(1, STREAM2STR("Finished " << count << " out of " << nanoCount << " nanos."));
                dlg.setOverallProgress(itemCount + count, itemCount + nanoCount);
                dlg.setText(2, STREAM2STR("Overall progress: " << ((itemCount + count) * 100) / max(1, itemCount +
                                          nanoCount) << "%"));
            }
            if (count % 10000 == 0)
            {
                writer.CommitItems();
                writer.BeginWrite();
            }
        }
        nano.reset();
        dlg.setTaskProgress(count, nanoCount);
        dlg.setText(1, STREAM2STR("Finished " << count << " out of " << nanoCount << " nanos."));
        dlg.setOverallProgress(itemCount + count, itemCount + nanoCount);
        dlg.setText(2, STREAM2STR("Overall progress: " << ((itemCount + count) * 100) / max(1, itemCount + nanoCount) << "%"));
        writer.CommitItems();

        if (dlg.userCanceled())
        {
            return false;
        }

        writer.PostProcessData();
    }
    catch (std::bad_alloc& e)
    {
        assert(false);
        LOG(_T("Error creating item database. ") << e.what());
        MessageBox(NULL,
                   _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."),
                   _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR);
        return false;
    }
    catch (AODatabaseParser::Exception& e)
    {
        assert(false);
        LOG(_T("Error creating item database. ") << e.what());
        MessageBox(NULL,
                   _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."),
                   _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR);
        return false;
    }
    catch (std::exception& e)
    {
        assert(false);
        LOG(_T("Error creating item database. ") << e.what());
        MessageBox(NULL,
                   _T("Unable to parse the AO database.\n\rMore details might be found in the log-file (if enabled)."),
                   _T("Error - AO Item Assistant++"), MB_OK | MB_ICONERROR);
        return false;
    }

    remove(local);
    rename(tmpfile, local);

    return true;
}
Example #2
0
//=============================================================================
// Initialization
//=============================================================================
StatusCode DeFTDetector::initialize(){

  StatusCode sc = DetectorElement::initialize(); // must be executed first
  if ( sc.isFailure() ) return sc;

  /// Create a MsgStream object with an add-hoc name (the second argument),
  /// instead of the ususual name(), which gives a too long string
  if ( !m_msg ) m_msg.reset( new MsgStream( msgSvc(), "DeFTDetector" ) );

  *m_msg << MSG::DEBUG << "==> Initialize DeFTDetector" << endmsg;

  //load ftversion
  m_FTversion = ( exists("FTversion") ? this->params()->param<int>("FTversion") : 0 );

  *m_msg << MSG::INFO << "Current FT geometry version =   " <<  m_FTversion<<endmsg;

  /// Fill in the vectors holding pointers to the Daugther DetElements
  // loop over stations

  const IDetectorElement::IDEContainer & detelems = childIDetectorElements();
  updMgrSvc()->registerCondition( this, geometry(), &DeFTDetector::geometryUpdate );

  if( m_FTversion >= 20 ){    //geom 20,4x,5x...
    for (auto iS = detelems.begin(); iS != detelems.end(); ++iS) {
      SmartDataPtr<DeFTStation> station(dataSvc(), (*iS)->name());
      if (station  ) {
        /// fill the vector of stations
        m_stations.push_back(station);
        // register UMS dependency
        updMgrSvc()->registerCondition( this, station->geometry(), &DeFTDetector::geometryUpdate );
        ///loop over layers and fill the vector of layers

        if( ! (station->childIDetectorElements().empty()) ){
          for (auto iL = station->childIDetectorElements().begin() ;
               iL != station->childIDetectorElements().end(); ++iL) {
           SmartDataPtr<DeFTLayer>  layer (dataSvc(),(*iL)->name());

           if ( layer ) {
            m_layers.push_back(layer);
            updMgrSvc()->registerCondition( this, layer->geometry(), &DeFTDetector::geometryUpdate );
            //*m_msg << MSG::INFO <<"registered FT  layer "<< iL - station->childIDetectorElements().begin() <<endmsg;
            ///loop over modules and fill the vector of modules
            if( !(layer ->childIDetectorElements().empty()) ){
            for (auto iM = layer->childIDetectorElements().begin(); iM != layer->childIDetectorElements().end(); ++iM) {
              SmartDataPtr<DeFTModule> module (dataSvc(),(*iM)->name());
              if ( module ) {
                m_modules.push_back(module);
                updMgrSvc()->registerCondition( this,
                                                module->geometry(), &DeFTDetector::geometryUpdate );

                if( ! (module ->childIDetectorElements().empty()) ){
                ///loop over fibremodules and fill the vector of fibremodules
                  for (auto iFM = module ->childIDetectorElements().begin();
                       iFM != module->childIDetectorElements().end() ; ++iFM) {
                    if ( std::string::npos != (*iFM)->name().find(m_FibreModuleNameSpec) ){

                      SmartDataPtr<DeFTFibreModule> fibremodule (dataSvc(),(*iFM)->name());
                      if ( fibremodule) {
                        m_fibremodules.push_back(fibremodule);
                        updMgrSvc()->registerCondition( this,
                                     fibremodule->geometry(), &DeFTDetector::geometryUpdate );
                        //*m_msg << MSG::INFO <<"registered FT fibremodule "
                        //       << iFM - module->childIDetectorElements().begin() <<endmsg;

                        if( ! (fibremodule ->childIDetectorElements().empty()) ){
                           ///loop over fibremats and fill the vector of fibremats
                           for (auto iFMat = fibremodule ->childIDetectorElements().begin() ;
                                iFMat != fibremodule ->childIDetectorElements().end() ; ++iFMat) {
                             if ( std::string::npos != (*iFMat)->name().find(m_FibreMatNameSpec) ){

                               SmartDataPtr<DeFTFibreMat> fibremat (dataSvc(),(*iFMat)->name());
                               if ( fibremat) {
                                 m_fibremats.push_back(fibremat);
                                 updMgrSvc()->registerCondition( this,
                                              fibremat->geometry(), &DeFTDetector::geometryUpdate );

                               }} // tests for  existance of fibremat

                           } // loop fibremat

                           } // test existance of children of fibre module


                      }} //tests for existance of fibre module
                }// loop fibremodules
                }//test existance of chilren of module


              }// test existanace of module
            } //loop modules
            } // test existance of children of layer

          }  //test existance of layer
          } // loop layers
        } // test of existance of children of station

      }// test existance of station
    } // loop stations

  }else if ( m_FTversion < 20 )  {
    // old version of geometry; to become obsolete
    for (auto iS = this->childBegin(); iS != this->childEnd(); ++iS) {
      DeFTStation* station = dynamic_cast<DeFTStation*>(*iS);
      if ( station ) {
        /// fill the vector of stations
        m_stations.push_back(station);
        ///loop over layers and fill the vector of bilayers
        for (auto iBL = (*iS)->childBegin(); iBL!= (*iS)->childEnd(); ++iBL) {
          DeFTBiLayer* bilayer = dynamic_cast<DeFTBiLayer*>(*iBL);
          if ( bilayer ) {
            m_bilayers.push_back(bilayer);
            ///loop over modules and fill the vector of modules
            for (auto iL = (*iBL)->childBegin(); iL!= (*iBL)->childEnd(); ++iL) {
              DeFTLayer* layer = dynamic_cast<DeFTLayer*>(*iL);
              if ( layer ) {
                m_layers.push_back(layer);
              }
            } // loop layers
          }
        }//loop bilayers
      }
    } // loop stations
  }


  ///>>> print the layer properties <<<///
  if ( m_msg->level() <= MSG::DEBUG ) {

    if( m_FTversion >= 20 ){

      ///loop over fibremats
      for (auto iFMat = fibremats().begin(); iFMat != fibremats().end(); ++iFMat) {
        DeFTFibreMat* fibremat = dynamic_cast<DeFTFibreMat*>(*iFMat);
        if ( fibremat ) {

          *m_msg << MSG::DEBUG << "Properties of FT fibreMat with ID " << fibremat->FibreMatID() << ":" << endmsg;
          *m_msg << MSG::DEBUG << "\tIn layer  " << fibremat->layer()  <<  endmsg;
          *m_msg << MSG::DEBUG << "\tIn module " << fibremat->module() <<  endmsg;
          *m_msg << MSG::DEBUG << "\tIs bottom " << fibremat->isBottom() <<  endmsg;
          *m_msg << MSG::DEBUG<< "\tGeometrical borders of fibremat: " << endmsg;
          *m_msg << MSG::DEBUG<< format("\txMin/xMax = %.1f / %.1f      yMin/yMax = %.1f / %.1f      zMin/zMax = %.1f / %.1f mm",
                                        fibremat->fibreMatMinX(), fibremat->fibreMatMaxX(),
                                        fibremat->fibreMatMinY(), fibremat->fibreMatMaxY(),
                                        fibremat->fibreMatMinZ(), fibremat->fibreMatMaxZ())<< endmsg;
          *m_msg << MSG::DEBUG<< "\tGeometrical borders of corresponding layer: " << endmsg;
          *m_msg << MSG::DEBUG<< format("\txMin/xMax = %.1f / %.1f      yMin/yMax = %.1f / %.1f      zMin/zMax = %.1f / %.1f mm",
                                        fibremat->layerMinX(), fibremat->layerMaxX(),
                                        fibremat->layerMinY(), fibremat->layerMaxY(),
                                        fibremat->layerMinZ(), fibremat->layerMaxZ())<< endmsg;
          *m_msg << MSG::DEBUG<< "\tBeam pipe radius: " << format("%7.1f mm", fibremat->layerInnerHoleRadius())<< endmsg;
          *m_msg << MSG::DEBUG<< "\tStereo angle: " << format("%.1f degrees", fibremat->angle()/Gaudi::Units::degree)<< endmsg;
          *m_msg << MSG::DEBUG<< "\tSlope dzDy: " << format("%.5f rad", fibremat->slopeDzDy())<< endmsg;
          *m_msg << MSG::DEBUG<< endmsg;

        }
      }
    }
  }

  /// sort the fibremats according to their fibreMatID
  std::sort(m_fibremats.begin(), m_fibremats.end(),
            [](const DeFTFibreMat* lhs, const DeFTFibreMat* rhs){ return lhs->FibreMatID() < rhs->FibreMatID(); });


    // trigger first UMS update
  const StatusCode update = updMgrSvc()->update(this);

  return ( sc && update) ;
}
Example #3
0
bool Hdf::exists(int name) const {
  char buf[12];
  sprintf(buf, "%d", name);
  return exists(buf);
}
Example #4
0
//funzione principale
unsigned initAesCuda(std::string myKeyFile, unsigned char myKeyBuffer[], const unsigned int myKeyBitsSize, std::string myInputFile, char inputArray[], const unsigned inputArraySize){
	
	path inputPath(myInputFile.c_str());
	path keyPath(myKeyFile.c_str());
	
	if ( !exists(keyPath) )
		throw std::string("file "+keyPath.string()+" doesn't exist");

	if ( !exists(inputPath) )
		throw std::string("file "+inputPath.string()+" doesn't exist");
	
	if ( myKeyBitsSize!=256 && myKeyBitsSize!=128)
		throw std::string("cannot use a key dimension different from 256 or 128");

	if ( !myKeyBuffer )
		throw std::string("key array not allocated");

	if ( !inputArray )
		throw std::string("input array not allocated");

	boost::intmax_t inputFileSize	= getFileSize(inputPath);
	boost::intmax_t keyFileSize		= getFileSize(keyPath);

	if ( keyFileSize==0 ) 
		throw std::string("cannot use an empty input file");

	if ( inputFileSize==0 ) 
		throw std::string("cannot use an empty key file");

	if ( inputFileSize > inputArraySize - 1 && MODE) 
		throw std::string("cannot encrypt a file bigger than 34.603.007 bytes");

	if ( inputFileSize > inputArraySize && !MODE) 
		throw std::string("cannot decrypt a file bigger than 33MB");

	//legge l'input
	readFromFileNotForm(inputPath, inputArray, inputFileSize);
	
	std::vector<unsigned> keyArray(myKeyBitsSize/8);
	
	unsigned ekSize = (myKeyBitsSize != 256) ? 176 : 240;

	std::vector<unsigned> expKeyArray(ekSize);
	std::vector<unsigned> invExpKeyArray(ekSize);
	
	//legge la chiave
	readFromFileForm(keyPath, keyArray);

	std::cout << "\n###############################################################\n\n";
	std::cout << "AES - CUDA by Svetlin Manavski)\n\n";
	std::cout << "AES " << myKeyBitsSize << " is running...." << std::endl << std::endl;
	std::cout << "Input file size: " << inputFileSize << " Bytes" << std::endl << std::endl;
	std::cout << "Key: ";
	for (unsigned cnt=0; cnt<keyArray.size(); ++cnt)
		std::cout << std::hex << keyArray[cnt];

	if (MODE){
		//ENCRYPTION MODE

		//PADDING MANAGEMENT FOLLOWING THE PKCS STANDARD
		unsigned mod16 = inputFileSize % 16;
		unsigned div16 = inputFileSize / 16;

		unsigned padElem;
		if ( mod16 != 0 )
			padElem =  16 - mod16;
		else 
			padElem =  16;

		for (unsigned cnt = 0; cnt < padElem; ++cnt)
				inputArray[div16*16 + mod16 + cnt] = padElem;

		inputFileSize = inputFileSize + padElem;
		
		//IN THE ENCRYPTION MODE I NEED THE EXPANDED KEY
		expFunc(keyArray, expKeyArray);
		for (unsigned cnt=0; cnt<expKeyArray.size(); ++cnt){
			unsigned val = expKeyArray[cnt];
			unsigned char *pc = reinterpret_cast<unsigned char *>(&val);
			myKeyBuffer[cnt] = *(pc);
		}
	} else {
		//DECRYPTION MODE 

		//IN THE ENCRYPTION MODE I NEED THE INVERSE EXPANDED KEY
		expFunc(keyArray, expKeyArray);
		invExpFunc(expKeyArray, invExpKeyArray);
		for (unsigned cnt=0; cnt<invExpKeyArray.size(); ++cnt){
			unsigned val = invExpKeyArray[cnt];
			unsigned char *pc = reinterpret_cast<unsigned char *>(&val);
			myKeyBuffer[cnt] = *(pc);
		}
	}
	std::cout << std::endl;

	return inputFileSize;
}
Example #5
0
 node add_file(std::string name) {
     if (!exists(name)) return {};
     files.emplace_back(new file(name));
     return *files.back();
 }
Example #6
0
void keyMapping::setDefaults()
{
    // Map the enums used by this client to ncurses key macros or
    // values.
    if (!exists(keyMapping::K_HELP))
    {
        add(keyMapping::K_HELP, KEY_F(1));
    }

    if (!exists(keyMapping::K_DETACH))
    {
        add(keyMapping::K_DETACH, 'd');
    }

    if (!exists(keyMapping::K_QUIT))
    {
        add(keyMapping::K_QUIT, 'q');
    }

    // Used for dialogs where one cannot press for example
    // 'q', since the dialog accepts this key.
    if (!exists(keyMapping::K_QUITSCREEN))
    {
        add(keyMapping::K_QUITSCREEN, KEY_F(10));
    }

    if (!exists(keyMapping::K_LOAD))
    {
        add(keyMapping::K_LOAD, 'l');
    }

    if (!exists(keyMapping::K_GLIMIT))
    {
        add(keyMapping::K_GLIMIT, 'g');
    }

    if (!exists(keyMapping::K_DOWN))
    {
        add(keyMapping::K_DOWN, KEY_DOWN);
    }

    if (!exists(keyMapping::K_UP))
    {
        add(keyMapping::K_UP, KEY_UP);
    }

    if (!exists(keyMapping::K_LIST_START))
    {
        add(keyMapping::K_LIST_START, KEY_HOME);
    }

    if (!exists(keyMapping::K_LIST_END))
    {
        add(keyMapping::K_LIST_END, KEY_END);
    }

    if (!exists(keyMapping::K_NEXT))
    {
        add(keyMapping::K_NEXT, KEY_RIGHT);
    }

    if (!exists(keyMapping::K_PREV))
    {
        add(keyMapping::K_PREV, KEY_LEFT);
    }

    if (!exists(keyMapping::K_MARK))
    {
        add(keyMapping::K_MARK, 'w');
    }

    if (!exists(keyMapping::K_MARK_ALL))
    {
        add(keyMapping::K_MARK_ALL, 'a');
    }

    if (!exists(keyMapping::K_SELECT))
    {
        add(keyMapping::K_SELECT, '\n');
    }

    if (!exists(keyMapping::K_MENU))
    {
        add(keyMapping::K_MENU, 'm');
    }

    if (!exists(keyMapping::K_SESNAME))
    {
        add(keyMapping::K_SESNAME, 'n');
    }

    if (!exists(keyMapping::K_RESIZE))
    {
        add(keyMapping::K_RESIZE, KEY_RESIZE);
    }

    if (!exists(keyMapping::K_DELETE))
    {
        add(keyMapping::K_DELETE, KEY_DC);
    }
}
Example #7
0
////////////////////////////////////////////////////////////////////////
// 描    述:  当前文件是否存在
// 作    者:  邵凯田
// 创建时间:  2011-11-18 10:22
// 参数说明:  void
// 返 回 值:  true表示文件存在,false表示文件不存在
//////////////////////////////////////////////////////////////////////////
bool SFile::exists()
{
	return exists(m_fileName.data());
}
Example #8
0
 // if an operation deletes or creates a file (or moves etc.), it may need files closed.
 bool FileCreatedOp::needFilesClosed() {
     return exists( _p.asFullPath() );
 }
Example #9
0
bool EntityExistsJob::finished()
{
    emit exists(reply());
    return true;
}
Example #10
0
QFileInfo ShellNodeInfo::fileInfo() const
{
    if (exists())
        return QFileInfo(filesystemPathName());
    return {};
}
Example #11
0
int main(int argc,char **argv)
{
    parseArgs(argc, argv);

    SIZE_T bW = 0, bR = 0;
    char *exeInput = (char *)malloc(MAX_PATH);
    char *dllInput = (char *)malloc(MAX_PATH);
    char *wdrInput = (char *)malloc(MAX_PATH);

    memset(exeInput,0,MAX_PATH);
    memset(dllInput,0,MAX_PATH);
    memset(wdrInput,0,MAX_PATH);

    if (opMode == OPMODE_LIST)
    {
        listProcesses(stringToMatch);
        return 0;
    }
    else if(opMode == OPMODE_INJECT)
    {
        if (globalDll == NULL)
        {
            printf(" [dll] > ");
            fgets(dllInput,MAX_PATH,stdin);
        }
        else
        {
            strcpy(dllInput,globalDll);
        }
        injectIntoProcess(globalInject,dllInput);
        return 0;
    }

    if (globalTest)
    {
        strcpy(exeInput,"test.exe");
        strcpy(dllInput,"shackle.dll");
        strcpy(wdrInput,"c:\\projects\\elegurawolfe\\");
    }
    else if(globalExeName == NULL || globalWorkingDirectory == NULL || globalDll == NULL)
    {
        // printf("* SOMETHING MISSING %08x%08x%08x\n", (unsigned long )globalExeName, (unsigned long )globalWorkingDirectory, (unsigned long )globalDll);
        printf(" [exe] > ");
        fgets(exeInput,MAX_PATH,stdin);
        if (globalDll == NULL)
        {
            printf(" [dll] > ");
            fgets(dllInput,MAX_PATH,stdin);
        }
        else
        {
            strcpy(dllInput,globalDll);
        }
        printf(" [wdr] > ");
        fgets(wdrInput,MAX_PATH,stdin);

        chomp(exeInput);
        chomp(dllInput);
        chomp(wdrInput);
    }
    else
    {
        strcpy(exeInput,globalExeName);
        strcpy(dllInput,globalDll);
        strcpy(wdrInput,globalWorkingDirectory);
    }

    if (exists(exeInput) == 0)
    {
        printf(" [FAIL-EXE] %s does not exist\n",exeInput);
        return 0;
    }

    if(exists(dllInput) == 0)
    {
        printf(" [FAIL-DLL] %s does not exist\n",dllInput);
        return 0;
    }

    PROCESS_INFORMATION pi;
    STARTUPINFO si;

    memset (&pi,0,sizeof(PROCESS_INFORMATION));
    memset (&si, 0, sizeof (STARTUPINFO));
    si.cb = sizeof(si);

    HANDLE hNtDll = LoadLibrary("ntdll.dll");
    NtQueryInformationProcess = (_NtQueryInformationProcess )(GetProcAddress( (HMODULE )hNtDll, "NtQueryInformationProcess"));
    HANDLE hKernel = LoadLibrary("kernel32.dll");
    LPVOID addrLoadLibrary = GetProcAddress( (HMODULE )hKernel, "LoadLibraryA");

    BOOL derp = CreateProcess(exeInput, exeInput, NULL, NULL, FALSE, CREATE_SUSPENDED + CREATE_NEW_CONSOLE, NULL, wdrInput, &si, &pi);
    if (derp == NULL)
    {
        char *errorMessage;
        FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER +
                       FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError (), 0,
                       (char *) &errorMessage, 1, NULL);
        printf (" [FAIL] %s", errorMessage);
        return 0;
    }

    HANDLE hProcess = pi.hProcess;
    HANDLE hThread = pi.hThread;

    globalPid = pi.dwProcessId;
    printf(" * [INFO] new process id is %d\n",pi.dwProcessId);

#if ARCHI == 64
    BOOL wow64 = FALSE;
    IsWow64Process(hProcess,&wow64);

    if (wow64 == TRUE)
    {
        IsDll64Bit(globalDll);
        printf(" [WARN] injecting into wow64 ");
    }
#endif

    printf(" [INFO] process handle is %08x\n",(unsigned long )hProcess);

    PROCESS_BASIC_INFORMATION pib;
    PEB_ARCHI globalPEB;

    NtQueryInformationProcess (hProcess, 0, (PVOID )(&pib), sizeof (pib),& bW);
    printf(" [INFO] pib.PebBaseAddress = 0x%x (size of field is %d)\n", pib.PebBaseAddress, sizeof(pib.PebBaseAddress));

    ReadProcessMemory (hProcess, pib.PebBaseAddress, &globalPEB, sizeof (globalPEB), &bR);
    if (bR != sizeof (globalPEB))
    {
        char *errorMessage;
        FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER +
                       FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError (), 0,
                       (char *) &errorMessage, 1, NULL);
        printf (" [FAIL] %s", errorMessage);
        return 0;
    }

    printf(" [INFO] peb.ImageBaseAddress = %p\n", globalPEB.ImageBaseAddress);

    UINT_PTR entryPoint = guessExecutableEntryPoint (hProcess, globalPEB.ImageBaseAddress);
    printf(" [INFO] entryPoint = 0x%8x\n", entryPoint);

    char oldEntryChars[2];
    DWORD oldProtect = 0;
    DWORD discardProtect = 0;

    VirtualProtectEx(hProcess,(LPVOID )entryPoint,1, PAGE_READWRITE, &oldProtect);
    ReadProcessMemory(hProcess,(LPCVOID )entryPoint,(char *)oldEntryChars,2,&bR);
    printf(" [INFO] old entry is %02x %02x\n", (unsigned char )oldEntryChars[0],(unsigned char )oldEntryChars[1]);
    printf(" [INFO] writing...\n");

    WriteProcessMemory(hProcess,(LPVOID )entryPoint,"\xEB\xFE",2,&bW);
    VirtualProtectEx(hProcess,(LPVOID )entryPoint,1,oldProtect,&discardProtect);

    char newEntryChars[2];

    ReadProcessMemory(hProcess,(LPCVOID )entryPoint,(char *)newEntryChars,2,&bR);
    if (newEntryChars[0] == '\xEB' && newEntryChars[1] == '\xFE')
    {
        printf(" [INFO] new entry is %02x %02x\n", (unsigned char )newEntryChars[0],(unsigned char )newEntryChars[1]);
    }
    else
    {
        printf(" [INFO] new entry is %02x %02x, something's wrong\n", (unsigned char )newEntryChars[0],(unsigned char )newEntryChars[1]);
        return 0;
    }

    CONTEXT context;
    context.ContextFlags = CONTEXT_FULL;

    GetThreadContext (hThread, &context);
    context.PC_REG = entryPoint;
    SetThreadContext(hThread,&context);
    ResumeThread(pi.hThread);

    LPVOID remoteMemory = VirtualAllocEx(hProcess,NULL,strlen(dllInput) + 1,MEM_COMMIT + MEM_RESERVE, PAGE_READWRITE);
    WriteProcessMemory(hProcess,(LPVOID )remoteMemory,dllInput,strlen(dllInput) + 1,&bW);

    printf(" [INFO] trying to create a remote thread at %08x\n",(unsigned long )addrLoadLibrary);

    char *dllOutput = (char *)malloc(MAX_PATH);
    memset(dllOutput,0,MAX_PATH);
    ReadProcessMemory(hProcess,(LPCVOID )remoteMemory,dllOutput,MAX_PATH,&bR);
    printf(" [INFO] confirming process has cave with \"%s\"\n",dllOutput);
    free(dllOutput);

    if(globalWait)
    {
        printf(" [WAIT] press any key to create remote thread...\n");
        getc(stdin);
    }

    HANDLE threadId = CreateRemoteThread(hProcess,NULL,0,(LPTHREAD_START_ROUTINE )addrLoadLibrary,remoteMemory,NULL,NULL);
    if (threadId == NULL)
    {
        printf(" [INFO] could not create remote thread\n");
        return 0;
    }
    else
    {
        WaitForSingleObject(threadId, INFINITE);   //this waits untill thread thread has finished
        // VirtualFree(remoteMemory, 0, MEM_RELEASE); //free myFunc memory
        CloseHandle(threadId);
        // CloseHandle(hProcess);
    }

    int i = globalCooldown;
    for (; i > 0; i--)
    {
        printf(" [INFO] waiting %d seconds\n",i);
        Sleep(1000);
    }

    printf(" [INFO] restoring entrypoint...\n");
    SuspendThread(pi.hThread);

    VirtualProtectEx(hProcess,(LPVOID )entryPoint,1, PAGE_READWRITE, &oldProtect);
    i = WriteProcessMemory(hProcess,(LPVOID )entryPoint,(char *)&oldEntryChars,2,&bW);
    if (i == 0)
    {
        char *errorMessage;
        FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER +
                       FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError (), 0,
                       (char *) &errorMessage, 1, NULL);
        printf (" [FAIL] %s", errorMessage);
        return 0;
    }
    ReadProcessMemory(hProcess,(LPCVOID )entryPoint,(char *)newEntryChars,2,&bR);
    VirtualProtectEx(hProcess,(LPVOID )entryPoint,1, oldProtect, &discardProtect);
    printf(" [INFO] entry restored to %02x %02x\n", (unsigned char )newEntryChars[0],(unsigned char )newEntryChars[1]);
    GetThreadContext (hThread, &context);
    context.PC_REG = entryPoint;
    SetThreadContext(hThread,&context);
    ResumeThread(pi.hThread);

    printf(" [INFO] bye!");
    free(exeInput);
    free(dllInput);
    free(wdrInput);

    return 0;
}
Example #12
0
static bool process(cchar *operation, bool quiet)
{
    cchar   *name, *off, *path;
    int     rc, launch, update, service, upstart;

    /*
        No systemd support yet
     */
    rc = 1;
    name = app->serviceName;
    launch = upstart = update = service = 0;

    if (exists("/bin/launchctl") && exists("/Library/LaunchDaemons/com.%s.%s.plist", slower(BLD_COMPANY), name)) {
        launch++;

    } else if (exists("/sbin/start") && exists("/etc/init/rc.conf") &&
            (exists("/etc/init/%s.conf", name) || exists("/etc/init/%s.off", name))) {
        upstart++;

    } else if (exists("/usr/sbin/update-rc.d") && exists("/etc/init.d/%s", name)) {
        update++;

    } else if (exists("/sbin/service") && exists("/etc/init.d/%s", name)) {
        service++;

    } else {
        mprError("Can't locate system tool to manage service");
        return 0;
    }

    /*
        Operations
     */
    if (smatch(operation, "install")) {
        if (launch) {
            ;

        } else if (service) {
            if (!run("/sbin/chkconfig --del %s", name)) {
                rc = 0;
            } else if (!run("/sbin/chkconfig --add %s", name)) {
                rc = 0;
            } else if (!run("/sbin/chkconfig --level 5 %s", name)) {
                rc = 0;
            }

        } else if (update) {
            ;

        } else if (upstart) {
            ;
        }

    } else if (smatch(operation, "uninstall")) {
        process("disable", 1);

        if (launch) {
            ;

        } else if (service) {
            rc = run("/sbin/chkconfig --del %s", name);

        } else if (update) {
            ;

        } else if (upstart) {
            ;
        }

    } else if (smatch(operation, "enable")) {
        /* 
            Enable service (will start on reboot)
         */
        if (launch) {
            path = sfmt("/Library/LaunchDaemons/com.%s.%s.plist", slower(BLD_COMPANY), name);
            /* 
                Unfortunately, there is no launchctl command to do an enable without starting. So must do a stop below.
             */
            if (!run("/bin/launchctl load -w %s", path)) {
                rc = 0;
            } else {
                rc = process("stop", 1);
            }

        } else if (update) {
            rc = run("/usr/sbin/update-rc.d %s defaults 90 10", name);
            /*
                Not supported on older versions
                rc = run("/usr/sbin/update-rc.d %s enable", name);
             */

        } else if (service) {
            rc = run("/sbin/chkconfig %s on", name);

        } else if (upstart) {
            off = sfmt("/etc/init/%s.off", name);
            if (exists(off) && !run("mv %s /etc/init/%s.conf", off, name)) {
                rc = 0;
            }
        }

    } else if (smatch(operation, "disable")) {
        process("stop", 1);
        if (launch) {
            rc = run("/bin/launchctl unload -w /Library/LaunchDaemons/com.%s.%s.plist", slower(BLD_COMPANY), name);

        } else if (update) {
            /*  
                Not supported on older versions
                rc = run("/usr/sbin/update-rc.d %s disable", name);
             */
            rc = run("/usr/sbin/update-rc.d -f %s remove", name);

        } else if (service) {
            rc = run("/sbin/chkconfig %s off", name);

        } else if (upstart) {
            if (exists("/etc/init/%s.conf", name)) {
                rc = run("mv /etc/init/%s.conf /etc/init/%s.off", name, name);
            }
        }

    } else if (smatch(operation, "start")) {
        if (launch) {
            rc = run("/bin/launchctl load /Library/LaunchDaemons/com.%s.%s.plist", slower(BLD_COMPANY), name);

        } else if (service) {
            rc = run("/sbin/service %s start", name);

        } else if (update) {
            rc = run("/usr/sbin/invoke-rc.d --quiet %s start", name);

        } else if (upstart) {
            rc = run("/sbin/start %s", name);
            if (!rc) {
                if (scontains(app->error, "start: Job is already running", -1)) {
                    rc = 0;
                }
            }
        }

    } else if (smatch(operation, "stop")) {
        if (launch) {
            rc = run("/bin/launchctl unload /Library/LaunchDaemons/com.%s.%s.plist", slower(BLD_COMPANY), name);

        } else if (service) {
            if (!run("/sbin/service %s stop", name)) {
                rc = killPid();
            }

        } else if (update) {
            if (!run("/usr/sbin/invoke-rc.d --quiet %s stop", name)) {
                rc = killPid();
            }

        } else if (upstart) {
            if (exists("/etc/init/%s.conf", name)) {
                rc = run("/sbin/stop %s", name);
            }
        }

    } else if (smatch(operation, "reload")) {
        rc = process("restart", 0);

    } else if (smatch(operation, "restart")) {
        process("stop", 1);
        rc = process("start", 0);

    } else if (smatch(operation, "run")) {
        runService();
    }

    if (!quiet) {
        if (!rc && app->error && *app->error) {
            mprError("Can't run command: %s\nCommand output: %s\n", app->command, app->error);
        }
        /* Logging at level one will be visible if appman -v is used */
        if (app->error && *app->error) {
            mprLog(1, "Error: %s", app->error); 
        }
        if (app->output && *app->output) {
            mprLog(1, "Output: %s", app->output); 
        }
    }
    return rc;
}
Example #13
0
 bool Location::exists() const {
   return exists(path_);
 }
Example #14
0
int MysqlDatabase::connect(bool create_new) {
  if (host.empty() || db.empty())
    return DB_CONNECTION_NONE;

  //CLog::Log(LOGDEBUG, "Connecting to mysql:%s:%s", host.c_str(), db.c_str());

  try
  {
    disconnect();

    if (conn == NULL) {
      conn = mysql_init(conn);
      mysql_ssl_set(
        conn,
        key.empty() ? NULL : key.c_str(),
        cert.empty() ? NULL : cert.c_str(),
        ca.empty() ? NULL : ca.c_str(),
        capath.empty() ? NULL : capath.c_str(),
        ciphers.empty() ? NULL : ciphers.c_str());
    }

    if (!CWakeOnAccess::GetInstance().WakeUpHost(host, "MySQL : " + db))
      return DB_CONNECTION_NONE;

    // establish connection with just user credentials
    if (mysql_real_connect(conn, host.c_str(),
                                 login.c_str(),
                                 passwd.c_str(),
                                 NULL,
                                 atoi(port.c_str()),
                                 NULL,
                                 compression ? CLIENT_COMPRESS : 0) != NULL)
    {
      static bool showed_ver_info = false;
      if (!showed_ver_info)
      {
        CLog::Log(LOGINFO, "MYSQL: Connected to version %s", mysql_get_server_info(conn));
        showed_ver_info = true;
      }

      // disable mysql autocommit since we handle it
      //mysql_autocommit(conn, false);

      // enforce utf8 charset usage
      default_charset = mysql_character_set_name(conn);
      if(mysql_set_character_set(conn, "utf8")) // returns 0 on success
      {
        CLog::Log(LOGERROR, "Unable to set utf8 charset: %s [%d](%s)",
                  db.c_str(), mysql_errno(conn), mysql_error(conn));
      }

      configure_connection();

      // check existence
      if (exists())
      {
        // nothing to see here
      }
      else if (create_new)
      {
        char sqlcmd[512];
        int ret;

        sprintf(sqlcmd, "CREATE DATABASE `%s` CHARACTER SET utf8 COLLATE utf8_general_ci", db.c_str());
        if ( (ret=query_with_reconnect(sqlcmd)) != MYSQL_OK )
        {
          throw DbErrors("Can't create new database: '%s' (%d)", db.c_str(), ret);
        }
      }

      if (mysql_select_db(conn, db.c_str()) == 0)
      {
        active = true;
        return DB_CONNECTION_OK;
      }
    }

    // if we failed above, either credentials were incorrect or the database didn't exist
    if (mysql_errno(conn) == ER_BAD_DB_ERROR && create_new)
    {

      if (create() == MYSQL_OK)
      {
        active = true;

        return DB_CONNECTION_OK;
      }
    }

    CLog::Log(LOGERROR, "Unable to open database: %s [%d](%s)",
              db.c_str(), mysql_errno(conn), mysql_error(conn));

    return DB_CONNECTION_NONE;
  }
  catch(...)
  {
    CLog::Log(LOGERROR, "Unable to open database: %s (%u)",
              db.c_str(), GetLastError());
  }
  return DB_CONNECTION_NONE;
}
Example #15
0
Error QTar::extract()
{
	//ifstream ofstream to seekg()
	QArchive::extract();

	if(!exists()) return Archive::OpenError;
	char buff[Header::RecordSize];
	//QFile outFile;
	//FILE* f;
	size_t bytes_read;
	unsigned int filesize;

#if ARCREADER_QT4
	if(!open(QIODevice::ReadOnly)) {
		error();
#else
	if(open(IO_ReadOnly)) {
		qDebug("open error");
#endif //ARCREADER_QT4
		return Archive::OpenError;
	}
	Q_D(QArchive);
	for (;;) {
#if ARCREADER_QT4
		bytes_read = read(buff,Header::RecordSize);
#else
		bytes_read = readBlock(buff,Header::RecordSize);
#endif //ARCREADER_QT4
		//put them here
		emit byteProcessed(d->processedSize+=Header::RecordSize);
		d->current_fileName=QFileInfo(buff).fileName();

		if (bytes_read < Header::RecordSize) {
			fprintf(stderr,"Short read. expected 512, got %d\n", bytes_read);
			return Archive::ReadError;
		}
		if (isEndBuff(buff)) {
#if USE_SLOT
			emit byteProcessed(d->processedSize+=Header::RecordSize);  //header;
#else
			estimate();
			progressHandler->Progress(d->current_fileName, d->size, d->processedSize+=Header::RecordSize, d->totalSize, d->speed, d->elapsed, d->left);
#endif
			finishMessage();
			return End;
		}
		if (!verifyChecksum(buff)) {
			fprintf(stderr, "Checksum failure\n");
			return ChecksumError;
		}

		switch (buff[156]) {
		case Header::LinkFlag::kLink :			printf(" Ignoring hardlink %s\n", buff); break;
		case Header::LinkFlag::kSymbolicLink :	printf(" Ignoring symlink %s\n", buff); break; /////////////////////////
		case Header::LinkFlag::kCharacter:		printf(" Ignoring character device %s\n", buff); break;
		case Header::LinkFlag::kBlock:			printf(" Ignoring block device %s\n", buff); break;
		case Header::LinkFlag::kDirectory:
			createDir(QString::fromLocal8Bit(buff), parseOct(buff + 100, 8));
			filesize = 0;
			break;
		case Header::LinkFlag::kFIFO:			printf(" Ignoring FIFO %s\n", buff); break;
		default:
			createFile(QString::fromLocal8Bit(buff), parseOct(buff + 100, 8));
			break;
		}

		++d->numFiles;
		filesize = parseOct(buff + 124, 12);
		d->size = filesize;
#if USE_SLOT
		updateMessage();
#endif
		while (filesize > 0) {
			checkTryPause();
#if ARCREADER_QT4
			bytes_read = read(buff,Header::RecordSize);
#else
			bytes_read = readBlock(buff,Header::RecordSize);
#endif //ARCREADER_QT4
			if (bytes_read < Header::RecordSize) {
				fprintf(stderr,"Short read. Expected 512, got %d\n",bytes_read);
				return Archive::ReadError;
			}
			if (filesize < Header::RecordSize) bytes_read = filesize;
			if (d->outFile.isOpen()) {
#if CONFIG_QT4
				if(d->outFile.write(buff,bytes_read)!=bytes_read) {
					fprintf(stderr, "[%s] %s @%d: Failed to write %s\n",__FILE__,__PRETTY_FUNCTION__,__LINE__,qPrintable(d->outFile.fileName()));
#else
				if(d->outFile.writeBlock(buff,bytes_read)!=bytes_read) {
					fprintf(stderr, "[%s] %s @%d: Failed to write %s\n",__FILE__,__PRETTY_FUNCTION__,__LINE__,qPrintable(d->outFile.name()));
#endif
					d->outFile.close();
				}
				/*if (fwrite(buff, 1, bytes_read, f)!= bytes_read) {
					fprintf(stderr, "Failed write\n");
					fclose(f);
					f = NULL;
				}*/
			}
#if USE_SLOT
			forceShowMessage(1000);
			emit byteProcessed(d->processedSize+=Header::RecordSize);//bytes_read);
#else
			estimate();
			progressHandler->Progress(d->current_fileName, d->size, d->processedSize+=Header::RecordSize, d->totalSize, d->speed, d->elapsed, d->left);
#endif
			filesize -= bytes_read;
		}
		//emit byteProcessed(processedSize+=size);
		if(d->outFile.isOpen()) d->outFile.close();
	}
	close();
}

Archive::Error QTar::extract(const QString& archive,const QString& dir)
{
	setArchive(archive);
	setOutDir(dir);

	return extract();
}
Example #16
0
void TypoMan::computeFromWord(const std::string& word)
{
    if (word.empty()) {
        return;
    }
    if (static_cast<int>(word.size()) < minimumWordSize) {
        return;
    }
    if (exists(typos, word)) {
        return;
    }
    auto corrections = correctWord(word, LanguageLocale::en_US);
    if (corrections.empty()) {
        return;
    }
    if (ignoreBritishEnglish) {
        std::vector<std::string> correctionsInUS;
        std::swap(corrections, correctionsInUS);
        auto correctionsInUK = correctWord(word, LanguageLocale::en_UK);
        std::set_intersection(
            std::begin(correctionsInUS),
            std::end(correctionsInUS),
            std::begin(correctionsInUK),
            std::end(correctionsInUK),
            std::back_inserter(corrections));
    }
    if (!isStrictWhiteSpace) {
        for (auto & correction : corrections) {
            auto hunks = somera::computeDiff(word, correction);
            std::string filtered;
            for (auto & hunk : hunks) {
                if (hunk.operation != DiffOperation::Equality
                    && hunk.text == " ") {
                    continue;
                }
                if (hunk.operation != DiffOperation::Deletion) {
                    filtered += hunk.text;
                }
            }
            correction = filtered;
        }
        eraseIf(corrections, [&](const std::string& correction) {
            return correction.empty();
        });
    }
    if (!isStrictHyphen) {
        for (auto & correction : corrections) {
            auto hunks = somera::computeDiff(word, correction);
            std::string filtered;
            for (auto & hunk : hunks) {
                if (hunk.operation != DiffOperation::Equality
                    && hunk.text == "-") {
                    continue;
                }
                if (hunk.operation != DiffOperation::Deletion) {
                    filtered += hunk.text;
                }
            }
            correction = filtered;
        }
        eraseIf(corrections, [&](const std::string& correction) {
            return correction.empty();
        });
    }
    if (!isStrictLetterCase) {
        eraseIf(corrections, [&](const std::string& correction) {
            return StringHelper::toLower(word) == StringHelper::toLower(correction);
        });
    }

    std::sort(std::begin(corrections), std::end(corrections));
    corrections.erase(
        std::unique(std::begin(corrections), std::end(corrections)),
        std::end(corrections));
    sortNearly(word, corrections);

    assert(maxCorrectWordCount > 0);
    if (static_cast<int>(corrections.size()) > maxCorrectWordCount) {
        corrections.resize(maxCorrectWordCount);
    }

    Typo typo;
    typo.typo = word;
    typo.corrections = std::move(corrections);
    if (onFoundTypo && !typo.corrections.empty()) {
        onFoundTypo(typo);
    }
    addTypo(typos, std::move(typo));
}
Example #17
0
bool Hdf::exists(const std::string &name) const {
  return exists(name.c_str());
}
Example #18
0
    const_cursor cend(size_type node_pos)   const { return (is_valid(node_pos) && exists(node_pos)
							    ? __succinct_trie->cend(node_pos)
							    : __succinct_trie->cend()); }
bool NameValueTableWrapper::exists(int64_t k) const {
  return exists(String(k));
}
Example #20
0
/*	Test the "semantics" (with respect to what the outputs should be, 
	given certain input) of the test cases in ../test/*.				 

	This testing has the preconditions of having a text output file in 
	test/files/testX/execution/output (for X = test0, test1, ...) and a 
	executable binary in test/files/testX/execution/bin (for X = test0, 
	test1, ...).													     */
void test_semantics_of_test_cases() {

	std::cout << std::endl << std::endl << "Checking semantics of every test case provided:" << std::endl;

	/*	Test case index. */
	unsigned int t_index = 0;
	/* (input, output) pair index. */
	unsigned int f_index = 0;
	const std::string path_temp = ("../test/files/test");
	
	/*	Input file. */
	std::string input_path;
	
	/*	Output file of execution. */
	std::string output_path;

	/*	The expected output file. */
	std::string exp_output_path;

	while(exists(path_temp + std::to_string(t_index) + std::string("/execution/bin"))) {
		/*	The binary file to be checked on exists. */
		
		f_index = 0;
		std::string binary = path_temp
					+ std::to_string(t_index)
					+ std::string("/execution/bin");

		while(files_exist(path_temp, t_index, f_index)) {
			/*	There is a new (input, output) pair to be checked.			 */

			input_path = path_temp 
					+ std::to_string(t_index) 
					+ std::string("/input") 
					+ std::to_string(f_index);
			output_path = path_temp
					+ std::to_string(t_index)
					+ std::string("/execution/output");
			exp_output_path = path_temp 
					+ std::to_string(t_index) 
					+ std::string("/output") 
					+ std::to_string(f_index);

			std::string execution = binary
					+ (std::string(" < ") + input_path)
					+ (std::string(" > ") + output_path);
			std::system(execution.c_str());
			

			/*	------------------------------------------------------------ */
			/*	These instructions check that there was no difference between
				the output that resulted from execution, and the expected 
				output. 													 */

			// First, build diff command.
			std::string diff = std::string("diff ")
					+ output_path
					+ std::string(" ")
					+ exp_output_path
					+ std::string(" > extra.diff");
			// Execute diff command.
			std::system(diff.c_str());
			// Open file that contains results of diff execution.
			std::fstream extra;
			extra.open("extra.diff", std::fstream::in);
			assert(!extra.fail());
			// Check that the end of the file is at position 0 
			// (i.e., length is 0).
			extra.seekg(0, extra.end);
			if ((int)extra.tellg() != 0) {
				std::cout << "Differences have been found between ";
				std::cout << output_path << " and " << exp_output_path;
				std::cout << ":" << std::endl;
				std::system("cat extra.diff");
				exit(1);
			}

			/*	------------------------------------------------------------ */

			++f_index;
		}
	
		++t_index;
	}
	
	if (exists(std::string("extra.diff")))
		std::system("rm extra.diff");

	std::cout << "\tSemantics of the test cases has been proven correct." << std::endl;
}
Example #21
0
boost::intmax_t getFileSize(path &myPath){
	if ( !exists(myPath) )
		throw std::string("file "+myPath.string()+" doesn't exist");

	return file_size(myPath);
}
Example #22
0
void datasource_cache::register_datasources(const std::string& str)
{       
#ifdef MAPNIK_THREADSAFE
    mutex::scoped_lock lock(mapnik::singleton<mapnik::datasource_cache,
                            mapnik::CreateStatic>::mutex_);
#endif
    boost::filesystem::path path(str);
    plugin_directories_.push_back(str);
    boost::filesystem::directory_iterator end_itr;
 
    if (exists(path) && is_directory(path))
    {
        for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr )
        {

#if BOOST_VERSION < 103400 
            if (!is_directory( *itr )  && is_input_plugin(itr->leaf()))
#else
#if (BOOST_FILESYSTEM_VERSION == 3)      
            if (!is_directory( *itr )  && is_input_plugin(itr->path().filename().string()))
#else // v2
            if (!is_directory( *itr )  && is_input_plugin(itr->path().leaf())) 
#endif 
#endif
            {
                try 
                {
#ifdef LIBTOOL_SUPPORTS_ADVISE
                    /* Note: the below was added as a workaround pre http://trac.mapnik.org/ticket/790
                       It could now be removed, but also is not doing any harm AFAICT.
                    */
                    
                    // with ltdl >=2.2 we can actually pass RTDL_GLOBAL to dlopen via the
                    // ltdl advise trick which is required on linux unless plugins are directly
                    // linked to libmapnik (and deps) at build time. The only other approach is to
                    // set the dlopen flags in the calling process (like in the python bindings)

                    // clear errors
                    lt_dlerror();

                    lt_dlhandle module = 0;
                    lt_dladvise advise;
                    int ret;
                
                    ret = lt_dlinit();
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }
                
                    ret = lt_dladvise_init(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading: " << lt_dlerror() << "\n";
                    }
                
                    ret = lt_dladvise_global(&advise);
                    if (ret != 0) {
                        std::clog << "Datasource loader: could not intialize dynamic loading of global symbols: " << lt_dlerror() << "\n";
                    }
#if (BOOST_FILESYSTEM_VERSION == 3)                    
                    module = lt_dlopenadvise (itr->path().string().c_str(), advise);
#else // v2
                    module = lt_dlopenadvise (itr->string().c_str(), advise);
#endif 

                    lt_dladvise_destroy(&advise);
#else

#if (BOOST_FILESYSTEM_VERSION == 3)   
                    lt_dlhandle module = lt_dlopen(itr->path().string().c_str());
#else // v2
                    lt_dlhandle module = lt_dlopen(itr->string().c_str());
#endif

#endif
                    if (module)
                    {
                        // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings
                        #ifdef __GNUC__
                        __extension__
                        #endif
                        datasource_name* ds_name = 
                            reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name"));
                        if (ds_name && insert(ds_name(),module))
                        {            
#ifdef MAPNIK_DEBUG
                            std::clog << "Datasource loader: registered: " << ds_name() << std::endl;
#endif 
                            registered_=true;
                        }
                    }
                    else
                    {
#if (BOOST_FILESYSTEM_VERSION == 3) 
                        std::clog << "Problem loading plugin library: " << itr->path().string() 
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;
#else // v2
                        std::clog << "Problem loading plugin library: " << itr->string() 
                                  << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)" << std::endl;    
#endif
                    }
                }
                catch (...) {}
            }
        }
    }
}
Example #23
0
// Helper used to create an absolute filename using the passed
// directory and xdebug-specific format string
static String format_filename(folly::StringPiece dir,
                              folly::StringPiece formatFile,
                              bool addSuffix) {
  // Create a string buffer and append the directory name
  auto const formatlen = formatFile.size();
  StringBuffer buf(formatlen * 2); // Slightly larger than formatlen
  if (!dir.empty()) {
    buf.append(dir);
    buf.append('/');
  }

  // Append the filename
  auto globals = get_global_variables()->asArrayData();
  for (int pos = 0; pos < formatlen; pos++) {
    auto c = formatFile[pos];
    if (c != '%' || pos + 1 == formatlen) {
      buf.append(c);
      continue;
    }

    c = formatFile[++pos];
    switch (c) {
      // crc32 of current working directory
      case 'c': {
        auto const crc32 = HHVM_FN(crc32)(g_context->getCwd());
        buf.append(crc32);
        break;
      }
      // process id
      case 'p':
        buf.append(getpid());
        break;
      // Random number
      case 'r':
        buf.printf("%lx", (long)HHVM_FN(rand)());
        break;
      // Script name
      case 's': {
        auto server = globals->get(s_SERVER).toArray();
        if (server.exists(s_SCRIPT_NAME) && server[s_SCRIPT_NAME].isString()) {
          const String scriptname(server[s_SCRIPT_NAME].toString(), CopyString);
          replace_special_chars(scriptname.get());
          buf.append(scriptname);
        }
        break;
      }
      // Timestamp (seconds)
      case 't': {
        auto const sec = (int64_t)time(nullptr);
        if (sec != -1) {
          buf.append(sec);
        }
        break;
      }
      // Timestamp (microseconds)
      case 'u': {
        struct timeval tv;
        if (gettimeofday(&tv, 0) != -1) {
          buf.printf("%ld_%ld", long(tv.tv_sec), long(tv.tv_usec));
        }
        break;
      }
      // $_SERVER['HTTP_HOST']
      case 'H': {
        Array server = globals->get(s_SERVER).toArray();
        if (server.exists(s_HTTP_HOST) && server[s_HTTP_HOST].isString()) {
          const String hostname(server[s_HTTP_HOST].toString(), CopyString);
          replace_special_chars(hostname.get());
          buf.append(hostname);
        }
        break;
      }
      // $_SERVER['REQUEST_URI']
      case 'R': {
        auto server = globals->get(s_SERVER).toArray();
        if (globals->exists(s_REQUEST_URI)) {
          const String requri(server[s_REQUEST_URI].toString(), CopyString);
          replace_special_chars(requri.get());
          buf.append(requri);
        }
        break;
      }
      // $_SERVER['UNIQUE_ID']
      case 'U': {
        auto server = globals->get(s_SERVER).toArray();
        if (server.exists(s_UNIQUE_ID) && server[s_UNIQUE_ID].isString()) {
          const String uniqueid(server[s_UNIQUE_ID].toString(), CopyString);
          replace_special_chars(uniqueid.get());
          buf.append(uniqueid);
        }
        break;
      }
      // session id
      case 'S': {
        // First we grab the session name from the ini settings, then the id
        // from the cookies
        String session_name;
        if (IniSetting::Get(s_SESSION_NAME, session_name)) {
          auto cookies = globals->get(s_COOKIE).toArray();
          if (cookies.exists(session_name) &&
              cookies[session_name].isString()) {
            const String sessionstr(cookies[session_name].toString(),
                                    CopyString);
            replace_special_chars(sessionstr.get());
            buf.append(sessionstr);
          }
          break;
        }
      }
      // Literal
      case '%':
        buf.append('%');
        break;
      default:
        buf.append('%');
        buf.append(c);
        break;
    }
  }

  // Optionally add .xt file extension
  if (addSuffix) {
    buf.append(".xt");
  }
  return buf.copy();
}
static inline bool exists(const std::string& filename)
{ return exists(filename.c_str()); }
Example #25
0
int main(int argc, char *argv[]) {
	int i, j, nf;

	progname = argv[0];

	UpdatePaths( progname );

	ac = argc + 50;
	av = alloc(ac*sizeof(char *));
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, interrupt);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, interrupt);
#ifdef SIGHUP
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, interrupt);
#endif
	if (getenv("TMP"))
		tempdir = getenv("TMP");
	else if (getenv("TEMP"))
		tempdir = getenv("TEMP");
	else if (getenv("TMPDIR"))
		tempdir = getenv("TMPDIR");
	assert(tempdir);
	i = strlen(tempdir);
	for (; (i > 0 && tempdir[i-1] == '/') || tempdir[i-1] == '\\'; i--)
		tempdir[i-1] = '\0';
	if (argc <= 1) {
		help();
		exit(0);
	}
	plist = append("-D__LCC__", 0);
	initinputs();
	if (getenv("LCCDIR"))
		option(stringf("-lccdir=%s", getenv("LCCDIR")));
	for (nf = 0, i = j = 1; i < argc; i++) {
		if (strcmp(argv[i], "-o") == 0) {
			if (++i < argc) {
				if (suffix(argv[i], suffixes, 2) >= 0) {
					error("-o would overwrite %s", argv[i]);
					exit(8);
				}
				outfile = argv[i];
				continue;
			} else {
				error("unrecognized option `%s'", argv[i-1]);
				exit(8);
			}
		} else if (strcmp(argv[i], "-target") == 0) {
			if (argv[i+1] && *argv[i+1] != '-')
				i++;
			continue;
		} else if (*argv[i] == '-' && argv[i][1] != 'l') {
			opt(argv[i]);
			continue;
		} else if (*argv[i] != '-' && suffix(argv[i], suffixes, 3) >= 0)
			nf++;
		argv[j++] = argv[i];
	}
	if ((cflag || Sflag) && outfile && nf != 1) {
		fprintf(stderr, "%s: -o %s ignored\n", progname, outfile);
		outfile = 0;
	}
	argv[j] = 0;
	for (i = 0; include[i]; i++)
		plist = append(include[i], plist);
	if (ilist) {
		List b = ilist;
		do {
			b = b->link;
			plist = append(b->str, plist);
		} while (b != ilist);
	}
	ilist = 0;
	for (i = 1; argv[i]; i++)
		if (*argv[i] == '-')
			opt(argv[i]);
		else {
			char *name = exists(argv[i]);
			if (name) {
				if (strcmp(name, argv[i]) != 0
				|| (nf > 1 && suffix(name, suffixes, 3) >= 0))
					fprintf(stderr, "%s:\n", name);
				filename(name, 0);
			} else
				error("can't find `%s'", argv[i]);
		}
	if (errcnt == 0 && !Eflag && !Sflag && !cflag && llist[1]) {
		compose(ld, llist[0], llist[1],
			append(outfile ? outfile : concat("a", first(suffixes[4])), 0));
		if (callsys(av))
			errcnt++;
	}
	rm(rmlist);	
	return errcnt ? EXIT_FAILURE : EXIT_SUCCESS;
}
Example #26
0
	constexpr bool _exists(const tuple &t, const seq<S...>&){
		return exists(std::get<S>(t)...);
	}
Example #27
0
int main(int argc, char **argv)
{
	int devnull_fd = -1;
#ifdef TIOCNOTTY
	int tty_fd = -1;
#endif

#ifdef HAVE_PAM
	pam_handle_t *pamh = NULL;
	int pamr;
	const char *const *pamenv = NULL;
#endif

	int opt;
	size_t size = 0;
	bool start = false;
	bool stop = false;
	bool oknodo = false;
	bool test = false;
	char *exec = NULL;
	char *startas = NULL;
	char *name = NULL;
	char *pidfile = NULL;
	char *retry = NULL;
	int sig = -1;
	int nicelevel = 0, ionicec = -1, ioniced = 0;
	bool background = false;
	bool makepidfile = false;
	bool interpreted = false;
	bool progress = false;
	uid_t uid = 0;
	gid_t gid = 0;
	char *home = NULL;
	int tid = 0;
	char *redirect_stderr = NULL;
	char *redirect_stdout = NULL;
	char *stderr_process = NULL;
	char *stdout_process = NULL;
	int stdin_fd;
	int stdout_fd;
	int stderr_fd;
	pid_t pid, spid;
	RC_PIDLIST *pids;
	int i;
	char *svcname = getenv("RC_SVCNAME");
	RC_STRINGLIST *env_list;
	RC_STRING *env;
	char *tmp, *newpath, *np;
	char *p;
	char *token;
	char *exec_file = NULL;
	struct passwd *pw;
	struct group *gr;
	char *line = NULL;
	FILE *fp;
	size_t len;
	mode_t numask = 022;
	char **margv;
	unsigned int start_wait = 0;

	applet = basename_c(argv[0]);
	atexit(cleanup);

	signal_setup(SIGINT, handle_signal);
	signal_setup(SIGQUIT, handle_signal);
	signal_setup(SIGTERM, handle_signal);

	if ((tmp = getenv("SSD_NICELEVEL")))
		if (sscanf(tmp, "%d", &nicelevel) != 1)
			eerror("%s: invalid nice level `%s' (SSD_NICELEVEL)",
			    applet, tmp);
	if ((tmp = getenv("SSD_IONICELEVEL"))) {
		int n = sscanf(tmp, "%d:%d", &ionicec, &ioniced);
		if (n != 1 && n != 2)
			eerror("%s: invalid ionice level `%s' (SSD_IONICELEVEL)",
			    applet, tmp);
		if (ionicec == 0)
			ioniced = 0;
		else if (ionicec == 3)
			ioniced = 7;
		ionicec <<= 13; /* class shift */
	}

	/* Get our user name and initial dir */
	p = getenv("USER");
	home = getenv("HOME");
	if (home == NULL || p == NULL) {
		pw = getpwuid(getuid());
		if (pw != NULL) {
			if (p == NULL)
				setenv("USER", pw->pw_name, 1);
			if (home == NULL) {
				setenv("HOME", pw->pw_dir, 1);
				home = pw->pw_dir;
			}
		}
	}

	while ((opt = getopt_long(argc, argv, getoptstring, longopts,
		    (int *) 0)) != -1)
		switch (opt) {
		case 'I': /* --ionice */
			if (sscanf(optarg, "%d:%d", &ionicec, &ioniced) == 0)
				eerrorx("%s: invalid ionice `%s'",
				    applet, optarg);
			if (ionicec == 0)
				ioniced = 0;
			else if (ionicec == 3)
				ioniced = 7;
			ionicec <<= 13; /* class shift */
			break;

		case 'K':  /* --stop */
			stop = true;
			break;

		case 'N':  /* --nice */
			if (sscanf(optarg, "%d", &nicelevel) != 1)
				eerrorx("%s: invalid nice level `%s'",
				    applet, optarg);
			break;

		case 'P':  /* --progress */
			progress = true;
			break;

		case 'R':  /* --retry <schedule>|<timeout> */
			retry = optarg;
			break;

		case 'S':  /* --start */
			start = true;
			break;

		case 'b':  /* --background */
			background = true;
			break;

		case 'c':  /* --chuid <username>|<uid> */
			/* DEPRECATED */
			ewarn("WARNING: -c/--chuid is deprecated and will be removed in the future, please use -u/--user instead");
			/* falls through */
		case 'u':  /* --user <username>|<uid> */
		{
			p = optarg;
			tmp = strsep(&p, ":");
			changeuser = xstrdup(tmp);
			if (sscanf(tmp, "%d", &tid) != 1)
				pw = getpwnam(tmp);
			else
				pw = getpwuid((uid_t)tid);

			if (pw == NULL)
				eerrorx("%s: user `%s' not found",
				    applet, tmp);
			uid = pw->pw_uid;
			home = pw->pw_dir;
			unsetenv("HOME");
			if (pw->pw_dir)
				setenv("HOME", pw->pw_dir, 1);
			unsetenv("USER");
			if (pw->pw_name)
				setenv("USER", pw->pw_name, 1);
			if (gid == 0)
				gid = pw->pw_gid;

			if (p) {
				tmp = strsep (&p, ":");
				if (sscanf(tmp, "%d", &tid) != 1)
					gr = getgrnam(tmp);
				else
					gr = getgrgid((gid_t) tid);

				if (gr == NULL)
					eerrorx("%s: group `%s'"
					    " not found",
					    applet, tmp);
				gid = gr->gr_gid;
			}
		}
		break;

		case 'd':  /* --chdir /new/dir */
			ch_dir = optarg;
			break;

		case 'e': /* --env */
			putenv(optarg);
			break;

		case 'g':  /* --group <group>|<gid> */
			if (sscanf(optarg, "%d", &tid) != 1)
				gr = getgrnam(optarg);
			else
				gr = getgrgid((gid_t)tid);
			if (gr == NULL)
				eerrorx("%s: group `%s' not found",
				    applet, optarg);
			gid = gr->gr_gid;
			break;

		case 'i': /* --interpreted */
			interpreted = true;
			break;

		case 'k':
			if (parse_mode(&numask, optarg))
				eerrorx("%s: invalid mode `%s'",
				    applet, optarg);
			break;

		case 'm':  /* --make-pidfile */
			makepidfile = true;
			break;

		case 'n':  /* --name <process-name> */
			name = optarg;
			break;

		case 'o':  /* --oknodo */
			/* DEPRECATED */
			ewarn("WARNING: -o/--oknodo is deprecated and will be removed in the future");
			oknodo = true;
			break;

		case 'p':  /* --pidfile <pid-file> */
			pidfile = optarg;
			break;

		case 's':  /* --signal <signal> */
			sig = parse_signal(applet, optarg);
			break;

		case 't':  /* --test */
			test = true;
			break;

		case 'r':  /* --chroot /new/root */
			ch_root = optarg;
			break;

		case 'a': /* --startas <name> */
			/* DEPRECATED */
			ewarn("WARNING: -a/--startas is deprecated and will be removed in the future, please use -x/--exec or -n/--name instead");
			startas = optarg;
			break;
		case 'w':
			if (sscanf(optarg, "%d", &start_wait) != 1)
				eerrorx("%s: `%s' not a number",
				    applet, optarg);
			break;
		case 'x':  /* --exec <executable> */
			exec = optarg;
			break;

		case '1':   /* --stdout /path/to/stdout.lgfile */
			redirect_stdout = optarg;
			break;

		case '2':  /* --stderr /path/to/stderr.logfile */
			redirect_stderr = optarg;
			break;

		case '3':   /* --stdout-logger "command to run for stdout logging" */
			stdout_process = optarg;
			break;

		case '4':  /* --stderr-logger "command to run for stderr logging" */
			stderr_process = optarg;
			break;

		case_RC_COMMON_GETOPT
		}

	endpwent();
	argc -= optind;
	argv += optind;

	/* Allow start-stop-daemon --signal HUP --exec /usr/sbin/dnsmasq
	 * instead of forcing --stop --oknodo as well */
	if (!start &&
	    !stop &&
	    sig != SIGINT &&
	    sig != SIGTERM &&
	    sig != SIGQUIT &&
	    sig != SIGKILL)
		oknodo = true;

	if (!exec)
		exec = startas;
	else if (!name)
		name = startas;

	if (!exec) {
		exec = *argv;
		if (!exec)
			exec = name;
		if (name && start)
			*argv = name;
	} else if (name) {
		*--argv = name;
		++argc;
    } else if (exec) {
		*--argv = exec;
		++argc;
	};

	if (stop || sig != -1) {
		if (sig == -1)
			sig = SIGTERM;
		if (!*argv && !pidfile && !name && !uid)
			eerrorx("%s: --stop needs --exec, --pidfile,"
			    " --name or --user", applet);
		if (background)
			eerrorx("%s: --background is only relevant with"
			    " --start", applet);
		if (makepidfile)
			eerrorx("%s: --make-pidfile is only relevant with"
			    " --start", applet);
		if (redirect_stdout || redirect_stderr)
			eerrorx("%s: --stdout and --stderr are only relevant"
			    " with --start", applet);
		if (stdout_process || stderr_process)
			eerrorx("%s: --stdout-logger and --stderr-logger are only relevant"
			    " with --start", applet);
		if (start_wait)
			ewarn("using --wait with --stop has no effect,"
			    " use --retry instead");
	} else {
		if (!exec)
			eerrorx("%s: nothing to start", applet);
		if (makepidfile && !pidfile)
			eerrorx("%s: --make-pidfile is only relevant with"
			    " --pidfile", applet);
		if ((redirect_stdout || redirect_stderr) && !background)
			eerrorx("%s: --stdout and --stderr are only relevant"
			    " with --background", applet);
		if ((stdout_process || stderr_process) && !background)
			eerrorx("%s: --stdout-logger and --stderr-logger are only relevant"
			    " with --background", applet);
		if (redirect_stdout && stdout_process)
			eerrorx("%s: do not use --stdout and --stdout-logger together",
					applet);
		if (redirect_stderr && stderr_process)
			eerrorx("%s: do not use --stderr and --stderr-logger together",
					applet);
	}

	/* Expand ~ */
	if (ch_dir && *ch_dir == '~')
		ch_dir = expand_home(home, ch_dir);
	if (ch_root && *ch_root == '~')
		ch_root = expand_home(home, ch_root);
	if (exec) {
		if (*exec == '~')
			exec = expand_home(home, exec);

		/* Validate that the binary exists if we are starting */
		if (*exec == '/' || *exec == '.') {
			/* Full or relative path */
			if (ch_root)
				xasprintf(&exec_file, "%s/%s", ch_root, exec);
			else
				xasprintf(&exec_file, "%s", exec);
		} else {
			/* Something in $PATH */
			p = tmp = xstrdup(getenv("PATH"));
			exec_file = NULL;
			while ((token = strsep(&p, ":"))) {
				if (ch_root)
					xasprintf(&exec_file, "%s/%s/%s", ch_root, token, exec);
				else
					xasprintf(&exec_file, "%s/%s", token, exec);
				if (exec_file && exists(exec_file))
					break;
				free(exec_file);
				exec_file = NULL;
			}
			free(tmp);
		}
	}
	if (start && !exists(exec_file)) {
		eerror("%s: %s does not exist", applet,
		    *exec_file ? exec_file : exec);
		free(exec_file);
		exit(EXIT_FAILURE);
	}
	if (start && retry)
		ewarn("using --retry with --start has no effect,"
		    " use --wait instead");

	/* If we don't have a pidfile we should check if it's interpreted
	 * or not. If it we, we need to pass the interpreter through
	 * to our daemon calls to find it correctly. */
	if (interpreted && !pidfile) {
		fp = fopen(exec_file, "r");
		if (fp) {
			line = NULL;
			if (getline(&line, &size, fp) == -1)
				eerrorx("%s: %s", applet, strerror(errno));
			p = line;
			fclose(fp);
			if (p != NULL && line[0] == '#' && line[1] == '!') {
				p = line + 2;
				/* Strip leading spaces */
				while (*p == ' ' || *p == '\t')
					p++;
				/* Remove the trailing newline */
				len = strlen(p) - 1;
				if (p[len] == '\n')
					p[len] = '\0';
				token = strsep(&p, " ");
				free(exec_file);
				xasprintf(&exec_file, "%s", token);
				opt = 0;
				for (nav = argv; *nav; nav++)
					opt++;
				nav = xmalloc(sizeof(char *) * (opt + 3));
				nav[0] = exec_file;
				len = 1;
				if (p)
					nav[len++] = p;
				for (i = 0; i < opt; i++)
					nav[i + len] = argv[i];
				nav[i + len] = '\0';
			}
		}
	}
	margv = nav ? nav : argv;

	if (stop || sig != -1) {
		if (sig == -1)
			sig = SIGTERM;
		if (!stop)
			oknodo = true;
		if (retry)
			parse_schedule(applet, retry, sig);
		else if (test || oknodo)
			parse_schedule(applet, "0", sig);
		else
			parse_schedule(applet, NULL, sig);
		if (pidfile) {
			pid = get_pid(applet, pidfile);
			if (pid == -1 && errno != ENOENT)
				exit(EXIT_FAILURE);
		} else {
			pid = 0;
		}
		i = run_stop_schedule(applet, exec, (const char *const *)margv,
		    pid, uid, test, progress, false);

		if (i < 0)
			/* We failed to stop something */
			exit(EXIT_FAILURE);
		if (test || oknodo)
			return i > 0 ? EXIT_SUCCESS : EXIT_FAILURE;

		/* Even if we have not actually killed anything, we should
		 * remove information about it as it may have unexpectedly
		 * crashed out. We should also return success as the end
		 * result would be the same. */
		if (pidfile && exists(pidfile))
			unlink(pidfile);
		if (svcname)
			rc_service_daemon_set(svcname, exec,
			    (const char *const *)argv,
			    pidfile, false);
		exit(EXIT_SUCCESS);
	}

	if (pidfile)
		pid = get_pid(applet, pidfile);
	else
		pid = 0;

	if (pid)
		pids = rc_find_pids(NULL, NULL, 0, pid);
	else
		pids = rc_find_pids(exec, (const char * const *) argv, uid, 0);
	if (pids)
		eerrorx("%s: %s is already running", applet, exec);

	free(pids);
	if (test) {
		if (rc_yesno(getenv("EINFO_QUIET")))
			exit (EXIT_SUCCESS);

		einfon("Would start");
		while (argc-- > 0)
			printf(" %s", *argv++);
		printf("\n");
		eindent();
		if (uid != 0)
			einfo("as user id %d", uid);
		if (gid != 0)
			einfo("as group id %d", gid);
		if (ch_root)
			einfo("in root `%s'", ch_root);
		if (ch_dir)
			einfo("in dir `%s'", ch_dir);
		if (nicelevel != 0)
			einfo("with a priority of %d", nicelevel);
		if (name)
			einfo ("with a process name of %s", name);
		eoutdent();
		exit(EXIT_SUCCESS);
	}

	ebeginv("Detaching to start `%s'", exec);
	eindentv();

	/* Remove existing pidfile */
	if (pidfile)
		unlink(pidfile);

	if (background)
		signal_setup(SIGCHLD, handle_signal);

	if ((pid = fork()) == -1)
		eerrorx("%s: fork: %s", applet, strerror(errno));

	/* Child process - lets go! */
	if (pid == 0) {
		pid_t mypid = getpid();
		umask(numask);

#ifdef TIOCNOTTY
		tty_fd = open("/dev/tty", O_RDWR);
#endif

		devnull_fd = open("/dev/null", O_RDWR);

		if (nicelevel) {
			if (setpriority(PRIO_PROCESS, mypid, nicelevel) == -1)
				eerrorx("%s: setpritory %d: %s",
				    applet, nicelevel,
				    strerror(errno));
		}

		if (ionicec != -1 &&
		    ioprio_set(1, mypid, ionicec | ioniced) == -1)
			eerrorx("%s: ioprio_set %d %d: %s", applet,
			    ionicec, ioniced, strerror(errno));

		if (ch_root && chroot(ch_root) < 0)
			eerrorx("%s: chroot `%s': %s",
			    applet, ch_root, strerror(errno));

		if (ch_dir && chdir(ch_dir) < 0)
			eerrorx("%s: chdir `%s': %s",
			    applet, ch_dir, strerror(errno));

		if (makepidfile && pidfile) {
			fp = fopen(pidfile, "w");
			if (! fp)
				eerrorx("%s: fopen `%s': %s", applet, pidfile,
				    strerror(errno));
			fprintf(fp, "%d\n", mypid);
			fclose(fp);
		}

#ifdef HAVE_PAM
		if (changeuser != NULL) {
			pamr = pam_start("start-stop-daemon",
			    changeuser, &conv, &pamh);

			if (pamr == PAM_SUCCESS)
				pamr = pam_acct_mgmt(pamh, PAM_SILENT);
			if (pamr == PAM_SUCCESS)
				pamr = pam_open_session(pamh, PAM_SILENT);
			if (pamr != PAM_SUCCESS)
				eerrorx("%s: pam error: %s",
					applet, pam_strerror(pamh, pamr));
		}
#endif

		if (gid && setgid(gid))
			eerrorx("%s: unable to set groupid to %d",
			    applet, gid);
		if (changeuser && initgroups(changeuser, gid))
			eerrorx("%s: initgroups (%s, %d)",
			    applet, changeuser, gid);
		if (uid && setuid(uid))
			eerrorx ("%s: unable to set userid to %d",
			    applet, uid);

		/* Close any fd's to the passwd database */
		endpwent();

#ifdef TIOCNOTTY
		ioctl(tty_fd, TIOCNOTTY, 0);
		close(tty_fd);
#endif

		/* Clean the environment of any RC_ variables */
		env_list = rc_stringlist_new();
		i = 0;
		while (environ[i])
			rc_stringlist_add(env_list, environ[i++]);

#ifdef HAVE_PAM
		if (changeuser != NULL) {
			pamenv = (const char *const *)pam_getenvlist(pamh);
			if (pamenv) {
				while (*pamenv) {
					/* Don't add strings unless they set a var */
					if (strchr(*pamenv, '='))
						putenv(xstrdup(*pamenv));
					else
						unsetenv(*pamenv);
					pamenv++;
				}
			}
		}
#endif

		TAILQ_FOREACH(env, env_list, entries) {
			if ((strncmp(env->value, "RC_", 3) == 0 &&
				strncmp(env->value, "RC_SERVICE=", 10) != 0 &&
				strncmp(env->value, "RC_SVCNAME=", 10) != 0) ||
				strncmp(env->value, "SSD_NICELEVEL=", 14) == 0 ||
				strncmp(env->value, "SSD_IONICELEVEL=", 16) == 0)
			{
				p = strchr(env->value, '=');
				*p = '\0';
				unsetenv(env->value);
				continue;
			}
		}
		rc_stringlist_free(env_list);

		/* For the path, remove the rcscript bin dir from it */
		if ((token = getenv("PATH"))) {
			len = strlen(token);
			newpath = np = xmalloc(len + 1);
			while (token && *token) {
				p = strchr(token, ':');
				if (p) {
					*p++ = '\0';
					while (*p == ':')
						p++;
				}
				if (strcmp(token, RC_LIBEXECDIR "/bin") != 0 &&
				    strcmp(token, RC_LIBEXECDIR "/sbin") != 0)
				{
					len = strlen(token);
					if (np != newpath)
						*np++ = ':';
					memcpy(np, token, len);
					np += len;
				}
				token = p;
			}
			*np = '\0';
			unsetenv("PATH");
			setenv("PATH", newpath, 1);
		}

		stdin_fd = devnull_fd;
		stdout_fd = devnull_fd;
		stderr_fd = devnull_fd;
		if (redirect_stdout) {
			if ((stdout_fd = open(redirect_stdout,
				    O_WRONLY | O_CREAT | O_APPEND,
				    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1)
				eerrorx("%s: unable to open the logfile"
				    " for stdout `%s': %s",
				    applet, redirect_stdout, strerror(errno));
		}else if (stdout_process) {
			stdout_fd = rc_pipe_command(stdout_process);
			if (stdout_fd == -1)
				eerrorx("%s: unable to open the logging process"
				    " for stdout `%s': %s",
				    applet, stdout_process, strerror(errno));
		}
		if (redirect_stderr) {
			if ((stderr_fd = open(redirect_stderr,
				    O_WRONLY | O_CREAT | O_APPEND,
				    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1)
				eerrorx("%s: unable to open the logfile"
				    " for stderr `%s': %s",
				    applet, redirect_stderr, strerror(errno));
		}else if (stderr_process) {
			stderr_fd = rc_pipe_command(stderr_process);
			if (stderr_fd == -1)
				eerrorx("%s: unable to open the logging process"
				    " for stderr `%s': %s",
				    applet, stderr_process, strerror(errno));
		}

		if (background)
			dup2(stdin_fd, STDIN_FILENO);
		if (background || redirect_stdout || stdout_process
				|| rc_yesno(getenv("EINFO_QUIET")))
			dup2(stdout_fd, STDOUT_FILENO);
		if (background || redirect_stderr || stderr_process
				|| rc_yesno(getenv("EINFO_QUIET")))
			dup2(stderr_fd, STDERR_FILENO);

		for (i = getdtablesize() - 1; i >= 3; --i)
			close(i);

		setsid();
		execvp(exec, argv);
#ifdef HAVE_PAM
		if (changeuser != NULL && pamr == PAM_SUCCESS)
			pam_close_session(pamh, PAM_SILENT);
#endif
		eerrorx("%s: failed to exec `%s': %s",
		    applet, exec,strerror(errno));
	}
void
ProjectGenerator::init()
{
    int file_count = 0;
    verifyCompilers();

    project->loadSpec();
    project->evaluateFeatureFile("default_pre.prf");
    project->evaluateFeatureFile("default_post.prf");
    project->evaluateConfigFeatures();
    project->values("CONFIG").clear();
    Option::postProcessProject(project);

    ProValueMap &v = project->variables();
    QString templ = Option::globals->user_template.isEmpty() ? QString("app") : Option::globals->user_template;
    if (!Option::globals->user_template_prefix.isEmpty())
        templ.prepend(Option::globals->user_template_prefix);
    v["TEMPLATE_ASSIGN"] += templ;

    //the scary stuff
    if(project->first("TEMPLATE_ASSIGN") != "subdirs") {
        QString builtin_regex = project_builtin_regx();
        QStringList dirs = Option::projfile::project_dirs;
        if(Option::projfile::do_pwd) {
            if(!v["INCLUDEPATH"].contains("."))
                v["INCLUDEPATH"] += ".";
            dirs.prepend(qmake_getpwd());
        }

        for(int i = 0; i < dirs.count(); ++i) {
            QString dir, regex, pd = dirs.at(i);
            bool add_depend = false;
            if(exists(pd)) {
                QFileInfo fi(fileInfo(pd));
                if(fi.isDir()) {
                    dir = pd;
                    add_depend = true;
                    if(dir.right(1) != Option::dir_sep)
                        dir += Option::dir_sep;
                    if (Option::recursive) {
                        QStringList files = QDir(dir).entryList(QDir::Files);
                        for (int i = 0; i < files.count(); i++)
                            dirs.append(dir + files[i] + QDir::separator() + builtin_regex);
                    }
                    regex = builtin_regex;
                } else {
                    QString file = pd;
                    int s = file.lastIndexOf(Option::dir_sep);
                    if(s != -1)
                        dir = file.left(s+1);
                    if(addFile(file)) {
                        add_depend = true;
                        file_count++;
                    }
                }
            } else { //regexp
                regex = pd;
            }
            if(!regex.isEmpty()) {
                int s = regex.lastIndexOf(Option::dir_sep);
                if(s != -1) {
                    dir = regex.left(s+1);
                    regex = regex.right(regex.length() - (s+1));
                }
                if (Option::recursive) {
                    QStringList entries = QDir(dir).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
                    for (int i = 0; i < entries.count(); i++)
                        dirs.append(dir + entries[i] + QDir::separator() + regex);
                }
                QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regex));
                for(int i = 0; i < (int)files.count(); i++) {
                    QString file = dir + files[i];
                    if (addFile(file)) {
                        add_depend = true;
                        file_count++;
                    }
                }
            }
            if(add_depend && !dir.isEmpty() && !v["DEPENDPATH"].contains(dir, Qt::CaseInsensitive)) {
                QFileInfo fi(fileInfo(dir));
                if(fi.absoluteFilePath() != qmake_getpwd())
                    v["DEPENDPATH"] += fileFixify(dir);
            }
        }
    }
    if(!file_count) { //shall we try a subdir?
        QStringList knownDirs = Option::projfile::project_dirs;
        if(Option::projfile::do_pwd)
            knownDirs.prepend(".");
        const QString out_file = fileFixify(Option::output.fileName());
        for(int i = 0; i < knownDirs.count(); ++i) {
            QString pd = knownDirs.at(i);
            if(exists(pd)) {
                QString newdir = pd;
                QFileInfo fi(fileInfo(newdir));
                if(fi.isDir()) {
                    newdir = fileFixify(newdir);
                    ProStringList &subdirs = v["SUBDIRS"];
                    if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) &&
                       !subdirs.contains(newdir, Qt::CaseInsensitive)) {
                        subdirs.append(newdir);
                    } else {
                        QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files);
                        for(int i = 0; i < (int)profiles.count(); i++) {
                            QString nd = newdir;
                            if(nd == ".")
                                nd = "";
                            else if(!nd.isEmpty() && !nd.endsWith(QString(QChar(QDir::separator()))))
                                nd += QDir::separator();
                            nd += profiles[i];
                            fileFixify(nd);
                            if (!subdirs.contains(nd, Qt::CaseInsensitive) && !out_file.endsWith(nd))
                                subdirs.append(nd);
                        }
                    }
                    if (Option::recursive) {
                        QStringList dirs = QDir(newdir).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
                        for(int i = 0; i < (int)dirs.count(); i++) {
                            QString nd = fileFixify(newdir + QDir::separator() + dirs[i]);
                            if (!knownDirs.contains(nd, Qt::CaseInsensitive))
                                knownDirs.append(nd);
                        }
                    }
                }
            } else { //regexp
                QString regx = pd, dir;
                int s = regx.lastIndexOf(Option::dir_sep);
                if(s != -1) {
                    dir = regx.left(s+1);
                    regx = regx.right(regx.length() - (s+1));
                }
                QStringList files = QDir(dir).entryList(QDir::nameFiltersFromString(regx),
                                                        QDir::Dirs | QDir::NoDotAndDotDot);
                ProStringList &subdirs = v["SUBDIRS"];
                for(int i = 0; i < (int)files.count(); i++) {
                    QString newdir(dir + files[i]);
                    QFileInfo fi(fileInfo(newdir));
                    {
                        newdir = fileFixify(newdir);
                        if(exists(fi.filePath() + QDir::separator() + fi.fileName() + Option::pro_ext) &&
                           !subdirs.contains(newdir)) {
                           subdirs.append(newdir);
                        } else {
                            QStringList profiles = QDir(newdir).entryList(QStringList("*" + Option::pro_ext), QDir::Files);
                            for(int i = 0; i < (int)profiles.count(); i++) {
                                QString nd = newdir + QDir::separator() + files[i];
                                fileFixify(nd);
                                if(files[i] != "." && files[i] != ".." && !subdirs.contains(nd, Qt::CaseInsensitive)) {
                                    if(newdir + files[i] != Option::output_dir + Option::output.fileName())
                                        subdirs.append(nd);
                                }
                            }
                        }
                        if (Option::recursive && !knownDirs.contains(newdir, Qt::CaseInsensitive))
                            knownDirs.append(newdir);
                    }
                }
            }
        }
        v["TEMPLATE_ASSIGN"] = ProStringList("subdirs");
        return;
    }

    //setup deplist
    QList<QMakeLocalFileName> deplist;
    {
        const ProStringList &d = v["DEPENDPATH"];
        for(int i = 0; i < d.size(); ++i)
            deplist.append(QMakeLocalFileName(d[i].toQString()));
    }
    setDependencyPaths(deplist);

    ProStringList &h = v["HEADERS"];
    bool no_qt_files = true;
    static const char *srcs[] = { "SOURCES", "YACCSOURCES", "LEXSOURCES", "FORMS", 0 };
    for (int i = 0; srcs[i]; i++) {
        const ProStringList &l = v[srcs[i]];
        QMakeSourceFileInfo::SourceFileType type = QMakeSourceFileInfo::TYPE_C;
        QMakeSourceFileInfo::addSourceFiles(l, QMakeSourceFileInfo::SEEK_DEPS, type);
        for(int i = 0; i < l.size(); ++i) {
            QStringList tmp = QMakeSourceFileInfo::dependencies(l.at(i).toQString());
            if(!tmp.isEmpty()) {
                for(int dep_it = 0; dep_it < tmp.size(); ++dep_it) {
                    QString dep = tmp[dep_it];
                    dep = fixPathToQmake(dep);
                    QString file_dir = dep.section(Option::dir_sep, 0, -2),
                        file_no_path = dep.section(Option::dir_sep, -1);
                    if(!file_dir.isEmpty()) {
                        for(int inc_it = 0; inc_it < deplist.size(); ++inc_it) {
                            QMakeLocalFileName inc = deplist[inc_it];
                            if(inc.local() == file_dir && !v["INCLUDEPATH"].contains(inc.real(), Qt::CaseInsensitive))
                                v["INCLUDEPATH"] += inc.real();
                        }
                    }
                    if(no_qt_files && file_no_path.indexOf(QRegExp("^q[a-z_0-9].h$")) != -1)
                        no_qt_files = false;
                    QString h_ext;
                    for(int hit = 0; hit < Option::h_ext.size(); ++hit) {
                        if(dep.endsWith(Option::h_ext.at(hit))) {
                            h_ext = Option::h_ext.at(hit);
                            break;
                        }
                    }
                    if(!h_ext.isEmpty()) {
                        for(int cppit = 0; cppit < Option::cpp_ext.size(); ++cppit) {
                            QString src(dep.left(dep.length() - h_ext.length()) +
                                        Option::cpp_ext.at(cppit));
                            if(exists(src)) {
                                ProStringList &srcl = v["SOURCES"];
                                if(!srcl.contains(src, Qt::CaseInsensitive))
                                    srcl.append(src);
                            }
                        }
                    } else if(dep.endsWith(Option::lex_ext) &&
                              file_no_path.startsWith(Option::lex_mod)) {
                        addConfig("lex_included");
                    }
                    if(!h.contains(dep, Qt::CaseInsensitive))
                        h += dep;
                }
            }
        }
    }

    //strip out files that are actually output from internal compilers (ie temporary files)
    const ProStringList &quc = project->values("QMAKE_EXTRA_COMPILERS");
    for (ProStringList::ConstIterator it = quc.begin(); it != quc.end(); ++it) {
        QString tmp_out = project->first(ProKey(*it + ".output")).toQString();
        if(tmp_out.isEmpty())
            continue;

        ProStringList var_out = project->values(ProKey(*it + ".variable_out"));
        bool defaults = var_out.isEmpty();
        for(int i = 0; i < var_out.size(); ++i) {
            ProString v = var_out.at(i);
            if(v.startsWith("GENERATED_")) {
                defaults = true;
                break;
            }
        }
        if(defaults) {
            var_out << "SOURCES";
            var_out << "HEADERS";
            var_out << "FORMS";
        }
        const ProStringList &tmp = project->values(ProKey(*it + ".input"));
        for (ProStringList::ConstIterator it2 = tmp.begin(); it2 != tmp.end(); ++it2) {
            ProStringList &inputs = project->values((*it2).toKey());
            for (ProStringList::Iterator input = inputs.begin(); input != inputs.end(); ++input) {
                QString path = replaceExtraCompilerVariables(tmp_out, (*input).toQString(), QString(), NoShell);
                path = fixPathToQmake(path).section('/', -1);
                for(int i = 0; i < var_out.size(); ++i) {
                    ProString v = var_out.at(i);
                    ProStringList &list = project->values(v.toKey());
                    for(int src = 0; src < list.size(); ) {
                        if(list[src] == path || list[src].endsWith("/" + path))
                            list.removeAt(src);
                        else
                            ++src;
                    }
                }
            }
        }
    }
}
Example #29
0
int Interpret(int, char* [])
{
  MockDb db = {};
  MockDb::_serializer_context_t printer = {};

  const auto f = test::TabFoo{};
  const auto t = test::TabBar{};
  select(t.alpha.as(t.beta));

  serialize(insert_into(t).columns(t.beta, t.gamma), printer).str();
  {
    auto i = insert_into(t).columns(t.gamma, t.beta);
    i.values.add(t.gamma = true, t.beta = "cheesecake");
    serialize(i, printer).str();
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin("coffee"));
    i.values.add(t.gamma = false, t.beta = sqlpp::tvin(std::string()));
    serialize(i, printer).str();
    i.values.add(t.gamma = sqlpp::default_value, t.beta = sqlpp::null);
    serialize(i, printer).str();
  }

  serialize(t.alpha = sqlpp::null, printer).str();
  serialize(t.alpha = sqlpp::default_value, printer).str();
  serialize(t.alpha, printer).str();
  serialize(-t.alpha, printer).str();
  serialize(+t.alpha, printer).str();
  serialize(-(t.alpha + 7), printer).str();
  serialize(t.alpha = 0, printer).str();
  serialize(t.alpha = sqlpp::tvin(0), printer).str();
  serialize(t.alpha == 0, printer).str();
  serialize(t.alpha == sqlpp::tvin(0), printer).str();
  serialize(t.alpha != 0, printer).str();
  serialize(t.gamma != sqlpp::tvin(false), printer).str();
  serialize(t.alpha == 7, printer).str();
  serialize(t.delta = sqlpp::tvin(0), printer).str();
  serialize(t.beta + "kaesekuchen", printer).str();

  serialize(sqlpp::select(), printer).str();
  serialize(sqlpp::select().flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta).flags(sqlpp::distinct), printer).str();
  serialize(select(t.alpha, t.beta), printer).str();
  serialize(select(t.alpha, t.beta).from(t), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma), printer).str();
  serialize(select(t.alpha, t.beta).from(t).where(t.alpha == 3).group_by(t.gamma).having(t.beta.like("%kuchen")),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc()),
            printer).str();
  serialize(select(t.alpha, t.beta)
                .from(t)
                .where(t.alpha == 3)
                .group_by(t.gamma)
                .having(t.beta.like("%kuchen"))
                .order_by(t.beta.asc())
                .limit(17)
                .offset(3),
            printer).str();

  serialize(parameter(sqlpp::bigint(), t.alpha), printer).str();
  serialize(parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha), printer).str();
  serialize(t.alpha == parameter(t.alpha) and (t.beta + "gimmick").like(parameter(t.beta)), printer).str();

  serialize(insert_into(t), printer).str();
  serialize(insert_into(f).default_values(), printer).str();
  serialize(insert_into(t).set(t.gamma = true), printer).str();
  // serialize(insert_into(t).set(t.gamma = sqlpp::tvin(false)), printer).str(); cannot test this since gamma cannot be
  // null and a static assert is thrown

  serialize(update(t), printer).str();
  serialize(update(t).set(t.gamma = true), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in("kaesekuchen", "cheesecake")), printer).str();
  serialize(update(t).set(t.gamma = true).where(t.beta.in()), printer).str();

  serialize(remove_from(t), printer).str();
  serialize(remove_from(t).using_(t), printer).str();
  serialize(remove_from(t).where(t.alpha == sqlpp::tvin(0)), printer).str();
  serialize(remove_from(t).using_(t).where(t.alpha == sqlpp::tvin(0)), printer).str();

  // functions
  serialize(sqlpp::value(7), printer).str();
  serialize(sqlpp::verbatim<sqlpp::integral>("irgendwas integrales"), printer).str();
  serialize(sqlpp::value_list(std::vector<int>({1, 2, 3, 4, 5, 6, 8})), printer).str();
  serialize(exists(select(t.alpha).from(t)), printer).str();
  serialize(any(select(t.alpha).from(t)), printer).str();
  serialize(some(select(t.alpha).from(t)), printer).str();
  serialize(count(t.alpha), printer).str();
  serialize(min(t.alpha), printer).str();
  serialize(max(t.alpha), printer).str();
  serialize(avg(t.alpha), printer).str();
  serialize(sum(t.alpha), printer).str();
  serialize(sqlpp::verbatim_table("whatever"), printer).str();

  // alias
  serialize(t.as(t.alpha), printer).str();
  serialize(t.as(t.alpha).beta, printer).str();

  // select alias
  serialize(select(t.alpha).from(t).where(t.beta > "kaesekuchen").as(t.gamma), printer).str();

  serialize(t.alpha.is_null(), printer).str();

  // join
  serialize(t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta), printer).str();
  {
    auto inner = t.inner_join(t.as(t.alpha)).on(t.beta == t.as(t.alpha).beta);
    serialize(select(t.alpha).from(inner), printer).str();
  }

  // multi_column
  serialize(multi_column(t.alpha, (t.beta + "cake").as(t.gamma)).as(t.alpha), printer).str();
  serialize(multi_column(all_of(t)).as(t), printer).str();
  serialize(all_of(t).as(t), printer).str();

  // dynamic select
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    auto s = dynamic_select(db).dynamic_flags().dynamic_columns().from(t);
    s.select_flags.add(sqlpp::distinct);
    s.selected_columns.add(t.beta);
    s.selected_columns.add(t.gamma);
    serialize(s, printer).str();
  }
  {
    // Behold, dynamically constructed queries might compile but be illegal SQL
    auto s = dynamic_select(db).dynamic_flags(sqlpp::distinct).dynamic_columns(t.alpha);
    s.select_flags.add(sqlpp::all);
    s.selected_columns.add(without_table_check(t.beta));
    s.selected_columns.add(without_table_check(t.gamma));
    serialize(s, printer).str();
  }

  // distinct aggregate
  serialize(count(sqlpp::distinct, t.alpha % 7), printer).str();
  serialize(avg(sqlpp::distinct, t.alpha - 7), printer).str();
  serialize(sum(sqlpp::distinct, t.alpha + 7), printer).str();

  serialize(select(all_of(t)).from(t).unconditionally(), printer).str();

  for (const auto& row : db(select(all_of(t)).from(t).unconditionally()))
  {
    serialize(row.alpha, printer);
    serialize(row.beta, printer);
    serialize(row.gamma, printer);
  }

  get_sql_name(t);
  get_sql_name(t.alpha);

  flatten(t.alpha == 7, db);

  auto x = boolean_expression(db, t.alpha == 7);
  x = sqlpp::boolean_expression<MockDb>(t.beta.like("%cheesecake"));
  x = x and boolean_expression(db, t.gamma);
  std::cerr << "----------------------------" << std::endl;
  printer.reset();
  std::cerr << serialize(x, printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in(select(f.epsilon).from(f).unconditionally())),
                         printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.in()), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(select(all_of(t)).from(t).where(t.alpha.not_in()), printer).str() << std::endl;

  auto schema = db.attach("lorem");
  auto s = schema_qualified_table(schema, t).as(sqlpp::alias::x);

  printer.reset();
  std::cerr << serialize(select(all_of(s)).from(s).unconditionally(), printer).str() << std::endl;

  printer.reset();
  std::cerr << serialize(sqlpp::case_when(true).then(t.alpha).else_(t.alpha + 1).as(t.beta), printer).str()
            << std::endl;

  return 0;
}
Example #30
0
void LibraryModule::addSettingsForModuleToExporter (ProjectExporter& exporter, ProjectSaver& projectSaver) const
{
    auto& project = exporter.getProject();

    const auto moduleRelativePath = exporter.getModuleFolderRelativeToProject (getID());

    exporter.addToExtraSearchPaths (moduleRelativePath.getParentDirectory());

    String libDirPlatform;
    if (exporter.isLinux())
        libDirPlatform = "Linux";
    else if (exporter.isCodeBlocks() && exporter.isWindows())
        libDirPlatform = "MinGW";
    else
        libDirPlatform = exporter.getTargetFolder().getFileName();

    const auto libSubdirPath = String (moduleRelativePath.toUnixStyle() + "/libs/") + libDirPlatform;
    const auto moduleLibDir = File (project.getProjectFolder().getFullPathName() + "/" + libSubdirPath);

    if (moduleLibDir.exists())
        exporter.addToModuleLibPaths (RelativePath (libSubdirPath, moduleRelativePath.getRoot()));

    const auto extraInternalSearchPaths = moduleInfo.getExtraSearchPaths().trim();

    if (extraInternalSearchPaths.isNotEmpty())
    {
        StringArray paths;
        paths.addTokens (extraInternalSearchPaths, true);

        for (int i = 0; i < paths.size(); ++i)
            exporter.addToExtraSearchPaths (moduleRelativePath.getChildFile (paths.getReference(i)));
    }

    {
        const String extraDefs (moduleInfo.getPreprocessorDefs().trim());

        if (extraDefs.isNotEmpty())
            exporter.getExporterPreprocessorDefs() = exporter.getExporterPreprocessorDefsString() + "\n" + extraDefs;
    }

    {
        Array<File> compiled;
        auto& modules = project.getModules();
        auto id = getID();

        const File localModuleFolder = modules.shouldCopyModuleFilesLocally (id).getValue()
                                          ? project.getLocalModuleFolder (id)
                                          : moduleInfo.getFolder();

        findAndAddCompiledUnits (exporter, &projectSaver, compiled);

        if (modules.shouldShowAllModuleFilesInProject (id).getValue())
            addBrowseableCode (exporter, compiled, localModuleFolder);
    }

    if (exporter.isXcode())
    {
        auto& xcodeExporter = dynamic_cast<XcodeProjectExporter&> (exporter);

        if (project.isAUPluginHost())
            xcodeExporter.xcodeFrameworks.addTokens (xcodeExporter.isOSX() ? "AudioUnit CoreAudioKit" : "CoreAudioKit", false);

        const String frameworks (moduleInfo.moduleInfo [xcodeExporter.isOSX() ? "OSXFrameworks" : "iOSFrameworks"].toString());
        xcodeExporter.xcodeFrameworks.addTokens (frameworks, ", ", {});

        parseAndAddLibs (xcodeExporter.xcodeLibs, moduleInfo.moduleInfo [exporter.isOSX() ? "OSXLibs" : "iOSLibs"].toString());
    }
    else if (exporter.isLinux())
    {
        parseAndAddLibs (exporter.linuxLibs, moduleInfo.moduleInfo ["linuxLibs"].toString());
        parseAndAddLibs (exporter.linuxPackages, moduleInfo.moduleInfo ["linuxPackages"].toString());
    }
    else if (exporter.isWindows())
    {
        if (exporter.isCodeBlocks())
            parseAndAddLibs (exporter.mingwLibs, moduleInfo.moduleInfo ["mingwLibs"].toString());
        else
            parseAndAddLibs (exporter.windowsLibs, moduleInfo.moduleInfo ["windowsLibs"].toString());
    }
    else if (exporter.isAndroid())
    {
        parseAndAddLibs (exporter.androidLibs, moduleInfo.moduleInfo ["androidLibs"].toString());
    }
}