myMenuCommands::myMenuCommands(const char *_Title,cList<cNestedItem> *_Commands,const char *Parameters):cOsdMenu(_Title)
#else
myMenuCommands::myMenuCommands(const char *_Title,cCommands *_Commands, const char *Parameters):cOsdMenu(_Title)
#endif
{
 SetHasHotkeys();
 commands=_Commands;
#if VDRVERSNUM > 10713
 result=NULL;
 parameters=Parameters;
 for(cNestedItem *Command=commands->First();Command;Command=commands->Next(Command)) {
  const char *s=Command->Text();
  if(Command->SubItems())
   Add(new cOsdItem(hk(cString::sprintf("%s...", s))));
  else if(Parse(s))
   Add(new cOsdItem(hk(title)));
 }
#else
 parameters=Parameters?strdup(Parameters):NULL;
 for(cCommand *command=commands->First();command;command=commands->Next(command))
  Add(new cOsdItem(hk(command->Title())));
#endif
}

myMenuCommands::~myMenuCommands()
{
#if VDRVERSNUM > 10713
 free(result);
#else
 free(parameters);
#endif
}

#if VDRVERSNUM > 10713
bool myMenuCommands::Parse(const char *s)
{
 const char *p=strchr(s,':');
 if(p) {
  int l=p-s;
  if(l>0) {
   char t[l+1];
   stripspace(strn0cpy(t,s,l+1));
   l=strlen(t);
   if(l>1&&t[l-1]=='?') {
    t[l-1]=0;
    confirm=true;
   }
   else
    confirm=false;
   title=t;
   command=skipspace(p+1);
   return true;
  }
 }
 return false;
}
#endif

#if VDRVERSNUM > 10713
eOSState myMenuCommands::Execute()
{
 cNestedItem *Command=commands->Get(Current());
 if(Command) {
  if(Command->SubItems())
   return AddSubMenu(new myMenuCommands(Title(),Command->SubItems(),parameters));
  if(Parse(Command->Text())) {
   if(!confirm||Interface->Confirm(cString::sprintf("%s?",*title))) {
    Skins.Message(mtStatus,cString::sprintf("%s...",*title));
    free(result);
    result=NULL;
    cString cmdbuf;
    if(!isempty(parameters))
     cmdbuf=cString::sprintf("%s %s",*command,*parameters);
    const char *cmd=*cmdbuf?*cmdbuf:*command;
    dsyslog("executing command '%s'",cmd);
    cPipe p;
    if(p.Open(cmd,"r")) {
     int l=0;
     int c;
     while((c=fgetc(p))!=EOF) {
      if(l%20==0)
       result=(char *)realloc(result,l+21);
      result[l++]=char(c);
     }
     if(result)
      result[l]=0;
     p.Close();
    }
    else
     esyslog("ERROR: can't open pipe for command '%s'",cmd);
    Skins.Message(mtStatus,NULL);
    if(result)
     return AddSubMenu(new cMenuText(title,result,fontFix));
    return osEnd;
   }
  }
 }
 return osContinue;
}
#else
eOSState myMenuCommands::Execute()
{
 cCommand *command=commands->Get(Current());
 if(command)
 {
  char *buffer=NULL;
  bool confirmed=false;
#ifdef CMDSUBMENUVERSNUM
  if (command->hasChilds())
  {
   AddSubMenu(new myMenuCommands(command->Title(), command->getChilds(), parameters));
   return osContinue;
  }
#endif
  if(command->Confirm())
  {
   if(asprintf(&buffer,"%s?",command->Title())!=-1)
   {
    confirmed=Interface->Confirm(buffer);
    free(buffer);
   }
  } else {
    confirmed=true;
  }
  if(confirmed)
  {
   if(asprintf(&buffer, "%s...",command->Title())!=-1)
   {
    Skins.Message(mtStatus,buffer);
    free(buffer);
   }
   const char *Result=command->Execute(parameters);
   Skins.Message(mtStatus,NULL);
   if(Result)
    return AddSubMenu(new cMenuText(command->Title(),Result,fontFix));
   return osEnd;
  }
 }
 return osContinue;
}
#endif

eOSState myMenuCommands::ProcessKey(eKeys Key)
{
 eOSState state=cOsdMenu::ProcessKey(Key);

 if(state==osUnknown)
 {
  switch(Key)
  {
   case kRed:
   case kGreen:
   case kYellow:
   case kBlue: return osContinue;
   case kOk: return Execute();
   default: break;
  }
 }
 return state;
}
//----------------------------------------------------------------------------
FxCompiler::FxCompiler (const std::string& fxName, bool alreadyCompiled)
    :
    mActiveProfile(0),
    mEffect(0),
    mAlreadyCompiled(alreadyCompiled)
{
    if (!mAlreadyCompiled)
    {
        // Use a command interpreter to compile the shaders using the Cg
        // compiler.
        bool compileSucceeded = false;
        std::string command;
        int i;
        for (i = 1; i < Shader::MAX_PROFILES; ++i)
        {
            // Delete the old vertex shader output (if it exists).
            command = "del " + fxName + "." + msVProfileName[i] + ".txt";
            system(command.c_str());

            // Compile the vertex shader.
            command = "cgc -profile " + msVProfileName[i];
            if (i == 1)
            {
                // VS_1_1 requires profile options for DX9 not to barf when
                // trying to assemble the program.
                command += " -profileopts dcls";
            }
            command += " -entry v_" + fxName + " -o " + fxName + ".";
            command += msVProfileName[i] + ".txt " + fxName + ".fx";
            int cgVStatus = system(command.c_str());

            // Delete the old pixel shader output (if it exists).
            command = "del " + fxName + "." + msPProfileName[i] + ".txt";
            system(command.c_str());

            // Compile the pixel shader.
            command = "cgc -profile " + msPProfileName[i];
            command += " -entry p_" + fxName + " -o " + fxName + ".";
            command += msPProfileName[i] + ".txt " + fxName + ".fx";
            int cgPStatus = system(command.c_str());

            if (cgVStatus == 0 && cgPStatus == 0)
            {
                // At least one profile compiled.
                compileSucceeded = true;
                Messages.push_back("The profile pair " + msVProfileName[i] +
                    " and " + msPProfileName[i] + " compiled.\n");
            }
            else
            {
                // Delete the output file when only one of the shaders
                // compiled.
                if (cgVStatus == 0)
                {
                    // The vertex shader compiled but the pixel shader did
                    // not.
                    command = "del " + fxName + "." + msVProfileName[i] +
                        ".txt";
                    system(command.c_str());
                }
                else
                {
                    Messages.push_back("Profile " + msVProfileName[i] +
                        " did not compile.\n");
                }

                if (cgPStatus == 0)
                {
                    // The pixel shader compiled but the vertex shader did
                    // not.
                    command = "del " + fxName + "." + msPProfileName[i];
                    command += ".txt";
                    system(command.c_str());
                }
                else
                {
                    Messages.push_back("Profile " + msPProfileName[i] +
                        " did not compile.\n");
                }
                Messages.push_back("The profile pair " + msVProfileName[i] +
                    " and " + msPProfileName[i] + " did not compile.\n");
            }
        }

        if (!compileSucceeded)
        {
            Messages.push_back("All profiles failed to compile.\n");
            return;
        }
    }

    InitializeMaps();

    Program vProgram[Shader::MAX_PROFILES];
    Program pProgram[Shader::MAX_PROFILES];
    for (int i = 1; i < Shader::MAX_PROFILES; ++i)
    {
        mActiveProfile = i;

        std::string inVName = fxName + "." + msVProfileName[i] + ".txt";
        bool hasVProfile = Parse(inVName, msVProfileName[i], vProgram[i]);

        std::string inPName = fxName + "." + msPProfileName[i] + ".txt";
        bool hasPProfile = Parse(inPName, msPProfileName[i], pProgram[i]);

        if (hasVProfile && hasPProfile)
        {
            if (mEffect == 0)
            {
                if (!CreateEffect(vProgram[i], pProgram[i]))
                {
                    return;
                }
            }
            else
            {
                if (!UpdateEffect(vProgram[i], pProgram[i]))
                {
                    return;
                }
            }
        }
    }

    if (mEffect)
    {
        mEffect->SaveWMFX(fxName + ".wmfx");
    }
}
void CxxPreProcessorScanner::Parse(CxxPreProcessor* pp) throw(CxxLexerException)
{
    CxxLexerToken token;
    bool searchingForBranch = false;
    CxxPreProcessorToken::Map_t& ppTable = pp->GetTokens();
    while(::LexerNext(m_scanner, token)) {
        // Pre Processor state
        switch(token.type) {
        case T_PP_INCLUDE_FILENAME: {
            // we found an include statement, recurse into it
            wxFileName include;
            if(pp->ExpandInclude(m_filename, token.text, include)) {
                CxxPreProcessorScanner* scanner = new CxxPreProcessorScanner(include, pp->GetOptions());
                try {
                    scanner->Parse(pp);
                } catch(CxxLexerException& e) {
                    // catch the exception
                    CL_DEBUG("Exception caught: %s\n", e.message);
                }
                // make sure we always delete the scanner
                wxDELETE(scanner);
                DEBUGMSG("<== Resuming parser on file: %s\n", m_filename.GetFullPath());
            }
            break;
        }
        case T_PP_IFDEF: {
            searchingForBranch = true;
            // read the identifier
            ReadUntilMatch(T_PP_IDENTIFIER, token);
            if(IsTokenExists(ppTable, token)) {
                DEBUGMSG("=> ifdef condition is TRUE (line: %d)\n", token.lineNumber);
                searchingForBranch = false;
                // condition is true
                Parse(pp);
            } else {
                DEBUGMSG("=> ifdef condition is FALSE (line: %d)\n", token.lineNumber);
                // skip until we find the next:
                // else, elif, endif (but do not consume these tokens)
                if(!ConsumeCurrentBranch()) return;
            }
            break;
        }
        case T_PP_IFNDEF: {
            searchingForBranch = true;
            // read the identifier
            ReadUntilMatch(T_PP_IDENTIFIER, token);
            if(!IsTokenExists(ppTable, token)) {
                DEBUGMSG("=> ifndef condition is TRUE (line: %d)\n", token.lineNumber);
                searchingForBranch = false;
                // condition is true
                Parse(pp);
            } else {
                DEBUGMSG("=> ifndef condition is FALSE (line: %d)\n", token.lineNumber);
                // skip until we find the next:
                // else, elif, endif (but do not consume these tokens)
                if(!ConsumeCurrentBranch()) return;
            }
            break;
        }
        case T_PP_IF:
            searchingForBranch = true;
        case T_PP_ELIF: {
            if(searchingForBranch) {
                // We expect a condition
                if(!CheckIf(ppTable)) {
                    DEBUGMSG("=> if condition is FALSE (line: %d)\n", token.lineNumber);
                    // skip until we find the next:
                    // else, elif, endif (but do not consume these tokens)
                    if(!ConsumeCurrentBranch()) return;

                } else {
                    DEBUGMSG("=> if condition is TRUE (line: %d)\n", token.lineNumber);
                    searchingForBranch = false;
                    // condition is true
                    Parse(pp);
                }
            } else {
                ConsumeBlock();
                return;
            }
            break;
        }
        case T_PP_ELSE: {
            if(searchingForBranch) {
                // if we reached an else, it means that we could not match
                // a if/elif/ifdef condition until now - enter it
                Parse(pp);
                searchingForBranch = false;
            } else {
                // we already found the branch for the current block
                // this means that the 'else' is a stop sign for us
                ConsumeBlock();
                return;
            }
            break;
        }
        case T_PP_ENDIF: {
            return;
        }
        case T_PP_DEFINE: {
            if(!::LexerNext(m_scanner, token) || token.type != T_PP_IDENTIFIER) {
                // Recover
                wxString dummy;
                GetRestOfPPLine(dummy);
                break;
            }
            wxString macroName = token.text;

            wxString macroValue;
            // Optionally get the value
            GetRestOfPPLine(macroValue, m_options & kLexerOpt_CollectMacroValueNumbers);

            CxxPreProcessorToken pp;
            pp.name = macroName;
            pp.value = macroValue;
            // mark this token for deletion when the entire TU parsing is done
            pp.deleteOnExit = (m_options & kLexerOpt_DontCollectMacrosDefinedInThisFile);
            DEBUGMSG("=> Adding macro: %s=%s (line %d)\n", pp.name, pp.value, token.lineNumber);
            ppTable.insert(std::make_pair(pp.name, pp));
            break;
        }
        }
    }
}
Exemple #4
0
bool CXBMCTinyXML::Parse(const std::string& data, const std::string& dataCharset)
{
  m_SuggestedCharset = dataCharset;
  StringUtils::ToUpper(m_SuggestedCharset);
  return Parse(data, TIXML_ENCODING_UNKNOWN);
}
Exemple #5
0
/** Returns the CA certificates that should be trusted for Mojang-related connections. */
static cX509CertPtr GetCACerts(void)
{
	static const char CertString[] =
		// GeoTrust root CA cert
		// Currently used for signing *.mojang.com's cert
		// Exported from Mozilla Firefox's built-in CA repository
		"-----BEGIN CERTIFICATE-----\n"
		"MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT\n"
		"MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i\n"
		"YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG\n"
		"EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg\n"
		"R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9\n"
		"9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq\n"
		"fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv\n"
		"iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU\n"
		"1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+\n"
		"bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW\n"
		"MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA\n"
		"ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l\n"
		"uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn\n"
		"Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS\n"
		"tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF\n"
		"PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un\n"
		"hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV\n"
		"5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw==\n"
		"-----END CERTIFICATE-----\n\n"

		// Equifax root CA cert
		// Exported from Mozilla Firefox's built-in CA repository
		"-----BEGIN CERTIFICATE-----\n"
		"MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV\n"
		"UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy\n"
		"dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1\n"
		"MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx\n"
		"dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B\n"
		"AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f\n"
		"BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A\n"
		"cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC\n"
		"AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ\n"
		"MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm\n"
		"aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw\n"
		"ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj\n"
		"IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF\n"
		"MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA\n"
		"A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y\n"
		"7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh\n"
		"1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4\n"
		"-----END CERTIFICATE-----\n\n"

		// Starfield G2 cert
		// This is the data of the root certs for Starfield Technologies, the CA that used to sign sessionserver.mojang.com's cert
		// Downloaded from https://certs.starfieldtech.com/repository/
		"-----BEGIN CERTIFICATE-----\n"
		"MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\n"
		"EDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\n"
		"HFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\n"
		"ZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\n"
		"MFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\n"
		"b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\n"
		"aG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\n"
		"Y2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\n"
		"ggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\n"
		"nLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\n"
		"HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\n"
		"Hwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\n"
		"dloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\n"
		"HZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\n"
		"BgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\n"
		"CSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\n"
		"sHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n"
		"4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n"
		"8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\n"
		"pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\n"
		"mMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n"
		"-----END CERTIFICATE-----\n\n"

		// Starfield original (G1) cert:
		"-----BEGIN CERTIFICATE-----\n"
		"MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\n"
		"MCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\n"
		"U3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\n"
		"NjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\n"
		"ChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\n"
		"ZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\n"
		"DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\n"
		"8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n"
		"+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\n"
		"X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\n"
		"K4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n"
		"1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\n"
		"A1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\n"
		"zt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\n"
		"YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\n"
		"bGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\n"
		"DQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\n"
		"L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\n"
		"eruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\n"
		"xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\n"
		"VSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\n"
		"WQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n"
		"-----END CERTIFICATE-----\n"
	;

	static auto X509Cert = [&]()
	{
		auto Cert = std::make_shared<cX509Cert>();
		VERIFY(0 == Cert->Parse(CertString, sizeof(CertString)));
		return Cert;
	}();

	return X509Cert;
}
Exemple #6
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
    if ( !file ) 
    {
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Delete the existing data:
    Clear();
    location.Clear();

    // Get the file size, so we can pre-allocate the string. HUGE speed impact.
    long length = 0;
    fseek( file, 0, SEEK_END );
    length = ftell( file );
    fseek( file, 0, SEEK_SET );

    // Strange case, but good to handle up front.
    if ( length <= 0 )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Subtle bug here. TinyXml did use fgets. But from the XML spec:
    // 2.11 End-of-Line Handling
    // <snip>
    // <quote>
    // ...the XML processor MUST behave as if it normalized all line breaks in external 
    // parsed entities (including the document entity) on input, before parsing, by translating 
    // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to 
    // a single #xA character.
    // </quote>
    //
    // It is not clear fgets does that, and certainly isn't clear it works cross platform. 
    // Generally, you expect fgets to translate from the convention of the OS to the c/unix
    // convention, and not work generally.

    /*
    while( fgets( buf, sizeof(buf), file ) )
    {
        data += buf;
    }
    */

    char* buf = new char[ length+1 ];
    buf[0] = 0;

    if ( fread( buf, length, 1, file ) != 1 ) {
        delete [] buf;
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Process the buffer in place to normalize new lines. (See comment above.)
    // Copies from the 'p' to 'q' pointer, where p can advance faster if
    // a newline-carriage return is hit.
    //
    // Wikipedia:
    // Systems based on ASCII or a compatible character set use either LF  (Line feed, '\n', 0x0A, 10 in decimal) or 
    // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)...
    //		* LF:    Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others
    //		* CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS
    //		* CR:    Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9

    const char* p = buf;	// the read head
    char* q = buf;			// the write head
    const char CR = 0x0d;
    const char LF = 0x0a;

    buf[length] = 0;
    while( *p ) {
        assert( p < (buf+length) );
        assert( q <= (buf+length) );
        assert( q <= p );

        if ( *p == CR ) {
            *q++ = LF;
            p++;
            if ( *p == LF ) {		// check for CR+LF (and skip LF)
                p++;
            }
        }
        else {
            *q++ = *p++;
        }
    }
    assert( q <= (buf+length) );
    *q = 0;

    Parse( buf, 0, encoding );

    delete [] buf;
    return !Error();
}
DateTime DateTime::Parse(const core::string& str)
{
	DateTime ret;
	Parse(str, ret);
	return ret;
}
Exemple #8
0
//-----------------------------------------------------------------------------
int mglParser::Parse(mglGraph *gr, const char *str, long pos)
{
	int r=0;
	MGL_TO_WCS(str,r = Parse(gr,wcs,pos));
	return r;
}
Exemple #9
0
//-----------------------------------------------------------------------------
// return values: 0 - OK, 1 - wrong arguments, 2 - wrong command, 3 - string too long, 4 -- unclosed string
int mglParser::Parse(mglGraph *gr, std::wstring str, long pos)
{
	if(Stop || gr->NeedStop())	return 0;
	curGr = gr->Self();
	std::wstring arg[1024];
	str=mgl_trim_ws(str);
	long n,k=0,m=0,mm=0,res;
	// try parse ':' -- several commands in line
	for(n=0;n<long(str.length());n++)
	{
		if(str[n]=='\'' && (n==0 || str[n-1]!='\\'))	k++;
		if(k%2)	continue;
		if(str[n]=='(')	m++;	if(str[n]==')')	m--;
		if(str[n]=='{')	mm++;	if(str[n]=='}')	mm--;
		if(str[n]=='#')	break;
		if((str[n]==':' || str[n]=='\n') && k%2==0 && m==0 && mm==0)
		{
			res=Parse(gr,str.substr(0,n),pos);
			if(!res)	res=Parse(gr,str.substr(n+1),pos);
			return res;
		}
	}
	if(k%2 || m || mm)	return 4;	// strings is not closed
	// define parameters or start cycle
	res = ParseDef(str);	if(res)	return res-1;
	// parse arguments (parameters $1, ..., $9)
	PutArg(str,false);	str=mgl_trim_ws(str);

	std::wstring opt;
	for(k=0;k<1024;k++)	// parse string to substrings (by spaces)
	{
		n = mglFindArg(str);
		if(n<1)	// this is option
		{
			if(str[-n]==';')	opt = str.substr(-n+1);
			if(n<0)	str = str.substr(0,-n);
			break;
		}
		arg[k] = str.substr(0,n);
		str = mgl_trim_ws(str.substr(n+1));
	}
	// try to find last argument
	if(str[0]!=0 && str[0]!='#' && str[0]!=';')	{	arg[k] = str;	k++;	}
	if(k<1) n =0;
	else
	{
		// fill arguments by its values
		mglArg *a = new mglArg[k];
		FillArg(gr, k, arg, a);
		// execute first special (program-flow-control) commands
		if(!skip() && !arg[0].compare(L"stop"))
		{	Stop = true;	delete []a;	return 0;	}
		if(!arg[0].compare(L"func"))
		{	Stop = true;	delete []a;	return 0;	}
		n = FlowExec(gr, arg[0].c_str(),k-1,a);
		if(n)		{	delete []a;	return n-1;	}
		if(skip())	{	delete []a;	return 0;	}
		if(!arg[0].compare(L"load"))
		{
			int n = a[0].type==1?0:1;
			a[0].s.assign(a[0].w.begin(),a[0].w.end());
			if(!n)	mgl_parser_load(this,a[0].s.c_str());
			delete []a;	return n;
		}
		if(!arg[0].compare(L"define"))
		{
			if(k==3)
			{
				DeleteVar(arg[1].c_str());	// force to delete variable with the same name
				mglNum *v=AddNum(arg[1].c_str());
				if(arg[2][0]=='!')	// complex number is added
				{	HADT dd = mglFormulaCalcC(arg[2].substr(1),this, DataList);
					v->d=NAN;	v->c = dd->a[0];	delete dd;	}
				else
				{	HMDT dd = mglFormulaCalc(arg[2],this, DataList);
					v->c = v->d = dd->a[0];	delete dd;	}
			}
			delete []a;	return k==3?0:1;
		}
		if(!arg[0].compare(L"rkstep"))
		{
			int res=1;
			if(k>2 && a[0].type==1 && a[1].type==1)
			{
				std::wstring a1 = arg[1], a2=arg[2];	res = 0;
				if(a1[0]=='\'')	a1 = a1.substr(1,a1.length()-2);
				if(a2[0]=='\'')	a2 = a2.substr(1,a2.length()-2);
				mgl_rk_step_w(this, a1.c_str(), a2.c_str(), (k>=3 && a[2].type==2)?a[2].v:1);
			}
			delete []a;	return res;
		}
		if(!arg[0].compare(L"call"))
		{
			n = 1;
			if(a[0].type==1)
			{
				int na=0;
				a[0].s.assign(a[0].w.begin(),a[0].w.end());
				n=-IsFunc(a[0].w.c_str(),&na);
				if(n && k!=na+2)
				{
					char buf[64];
					snprintf(buf,64,"Bad arguments for %ls: %ld instead of %d\n", a[0].w.c_str(),k-2,na);
					buf[63]=0;	gr->SetWarn(-1,buf);	n = 1;
				}
				else if(n)
				{
					mglFnStack fn;			fn.pos = pos;
					for(int i=0;i<10;i++)	{	fn.par[i] = par[i];	par[i]=L"";	}
					for(int i=1;i<k-1;i++)	AddParam(i,arg[i+1].c_str());
					fn_stack.push_back(fn);	n--;
				}
				else if(AllowFileIO)	// disable external scripts if AllowFileIO=false
				{
					FILE *fp = fopen(a[0].s.c_str(),"rt");
					if(fp)
					{
						register int i;
						mglParser *prs = new mglParser(AllowSetSize);
						prs->DataList.swap(DataList);	prs->NumList.swap(NumList);	prs->Cmd=Cmd;
						for(i=10;i<30;i++)	prs->AddParam(i,par[i].c_str());
						prs->Execute(gr,fp);
						for(i=10;i<30;i++)	AddParam(i,prs->par[i].c_str());
						DataList.swap(prs->DataList);	NumList.swap(prs->NumList);
						prs->Cmd=0;	delete prs;	fclose(fp);
					}
					else	n=1;
				}
			}
			delete []a;	return n;
		}
		if(!arg[0].compare(L"for"))
		{
			n = 1;
			char ch = arg[1][0];
			int r = ch-'0';
			if(ch>='a' && ch<='z')	r = 10+ch-'a';
//			int r = int(a[0].v);
			if(arg[1][1]==0 && (r>=0 && r<40))
			{
				if(a[1].type==0)
				{
					n=0;		fval[r] = *(a[1].d);
					fval[r].nx *= fval[r].ny*fval[r].nz;
				}
				else if(a[1].type==2 && a[2].type==2 && a[2].v>a[1].v)
				{
					mreal step = a[3].type==2?a[3].v:1;
					mm = int(step>0 ? (a[2].v-a[1].v)/step : 0);
					if(mm>0)
					{
						n=0;	fval[r].Create(mm+1);
						for(int ii=0;ii<mm+1;ii++)
							fval[r].a[ii] = a[1].v + step*ii;
					}
				}
				if(n==0)
				{
					for(int i=39;i>0;i--)
					{	for_stack[i]=for_stack[i-1];	if_for[i]=if_for[i-1];	}
					for_stack[0] = r+1;		fval[r].nz = pos;	if_for[0]=if_pos;
					wchar_t buf[32];		mglprintf(buf,32,L"%g",fval[r].a[0]);
					AddParam(r, buf);	fval[r].ny = 1;
				}
			}
			delete []a;	return n;
		}
		// alocate new arrays and execute the command itself
		n = PreExec(gr, k, arg, a);
		if(n>0)	n--;
		else if(!arg[0].compare(L"setsize") && !AllowSetSize)	n = 2;
		else	n = Exec(gr, arg[0].c_str(),k-1,a, arg[1].c_str(), opt.c_str());
		delete []a;
	}
	// delete temporary data arrays
	for(size_t i=0;i<DataList.size();i++)	if(DataList[i] && DataList[i]->temp)
	{	mglDataA *u=DataList[i];	DataList[i]=0;	delete u;	}
	return n;
}
Exemple #10
0
static void parse(int tok, SToken *tok_data)
{
    Parse(parser, tok, tok_data);
}
Exemple #11
0
 JsonExpectationsSource::JsonExpectationsSource(const char *jsonPath) {
     Parse(jsonPath, &fJsonRoot);
     fJsonExpectedResults = fJsonRoot[kJsonKey_ExpectedResults];
 }
void tTJSScriptBlock::SetText(tTJSVariant *result, const tjs_char *text,
                              iTJSDispatch2 * context, bool isexpression)
{
    TJS_F_TRACE("tTJSScriptBlock::SetText");


    // compiles text and executes its global level scripts.
    // the script will be compiled as an expression if isexpressn is true.
    if(!text) return;
    if(!text[0]) return;

    TJS_D((TJS_W("Counting lines ...\n")))

    Script = new tjs_char[TJS_strlen(text)+1];
    TJS_strcpy(Script, text);

    // calculation of line-count
    tjs_char *ls = Script;
    tjs_char *p = Script;
    while(*p)
    {
        if(*p == TJS_W('\r') || *p == TJS_W('\n'))
        {
            LineVector.push_back(int(ls - Script));
            LineLengthVector.push_back(int(p - ls));
            if(*p == TJS_W('\r') && p[1] == TJS_W('\n')) p++;
            p++;
            ls = p;
        }
        else
        {
            p++;
        }
    }

    if(p!=ls)
    {
        LineVector.push_back(int(ls - Script));
        LineLengthVector.push_back(int(p - ls));
    }

    try
    {

        // parse and execute
#ifdef TJS_DEBUG_PROFILE_TIME
        {
            tTJSTimeProfiler p(parsetime);
#endif

            Parse(text, isexpression, result != NULL);

#ifdef TJS_DEBUG_PROFILE_TIME
        }

        {
            char buf[256];
            sprintf(buf, "parsing : %d", parsetime);
            OutputDebugString(buf);
            if(parsetime)
            {
                sprintf(buf, "Commit : %d (%d%%)", time_Commit, time_Commit*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "yylex : %d (%d%%)", time_yylex, time_yylex*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "MakeNP : %d (%d%%)", time_make_np, time_make_np*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "GenNodeCode : %d (%d%%)", time_GenNodeCode, time_GenNodeCode*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "  PutCode : %d (%d%%)", time_PutCode, time_PutCode*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "  PutData : %d (%d%%)", time_PutData, time_PutData*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "  this_proxy : %d (%d%%)", time_this_proxy, time_this_proxy*100/parsetime);
                OutputDebugString(buf);

                sprintf(buf, "ns::Push : %d (%d%%)", time_ns_Push, time_ns_Push*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "ns::Pop : %d (%d%%)", time_ns_Pop, time_ns_Pop*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "ns::Find : %d (%d%%)", time_ns_Find, time_ns_Find*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "ns::Remove : %d (%d%%)", time_ns_Remove, time_ns_Remove*100/parsetime);
                OutputDebugString(buf);
                sprintf(buf, "ns::Commit : %d (%d%%)", time_ns_Commit, time_ns_Commit*100/parsetime);
                OutputDebugString(buf);

            }
        }
#endif

#ifdef TJS_DEBUG_DISASM
        std::list<tTJSInterCodeContext *>::iterator i =
            InterCodeContextList.begin();
        while(i != InterCodeContextList.end())
        {
            ConsoleOutput(TJS_W(""), (void*)this);
            ConsoleOutput((*i)->GetName(), (void*)this);
            (*i)->Disassemble(ConsoleOutput, (void*)this);
            i++;
        }
#endif

        // execute global level script
        ExecuteTopLevelScript(result, context);
    }
    catch(...)
    {
        if(InterCodeContextList.size() != 1)
        {
            if(TopLevelContext) TopLevelContext->Release(), TopLevelContext = NULL;
            while(ContextStack.size())
            {
                ContextStack.top()->Release();
                ContextStack.pop();
            }
        }
        throw;
    }

    if(InterCodeContextList.size() != 1)
    {
        // this is not a single-context script block
        // (may hook itself)
        // release all contexts and global at this time
        if(TopLevelContext) TopLevelContext->Release(), TopLevelContext = NULL;
        while(ContextStack.size())
        {
            ContextStack.top()->Release();
            ContextStack.pop();
        }
    }
}
Exemple #13
0
////--------------------
/// FFConfigParser::Init
//------------------------
//	Reads the force feedback configuration file. Call this once after the device
//	is initialized.
//
//	Parameters:
//	*	filename
//
//	Returns:
//	*	qtrue - the effects set directory has been set according to the initialized
//			device. (See base/fffx/fffx.cfg)
//	*	qfalse - no effects set could be determined for this device.
//
qboolean FFConfigParser::Init( const char *filename )
{
	Clear();	// Always cleanup

	return qboolean( filename && Parse( LoadFile( filename ) ) );
}
/*
  Parser
*/
Parser::Parser(const char *file_name)
{
	Parse(file_name);
}
Exemple #15
0
unsigned int JsonObjectNode::Parse(const tstring& content)
{
	return Parse(content.c_str(), content.length());
}
Exemple #16
0
LTBOOL CAIGoalButeMgr::Init(const char* szAttributeFile)
{
    if (g_pAIGoalButeMgr || !szAttributeFile) return LTFALSE;
    if (!Parse(szAttributeFile))
	{
		AIASSERT1( 0, NULL, "CAIGoalButeMgr::Init: Failed to parse %s", szAttributeFile );
		return LTFALSE;
	}

	// Set up global pointer

	g_pAIGoalButeMgr = this;

	// Read Goal Sets.
	
	uint32 iGoalSet = 0;
	sprintf(s_aTagName, "%s%d", "GoalSet", iGoalSet);
	
	while (m_buteMgr.Exist(s_aTagName))
	{
		ReadGoalSet();
		++iGoalSet;
		sprintf(s_aTagName, "%s%d", "GoalSet", iGoalSet);
	}


	// Create an array as big as the goal type enum list.
	
	m_aTemplates = debug_newa(AIGBM_GoalTemplate, kGoal_Count);

	// See how many goal templates there are

	uint32 cTemplates = 0;
	sprintf(s_aTagName, "%s%d", "Goal", cTemplates);

	while (m_buteMgr.Exist(s_aTagName))
	{
		++cTemplates;
		sprintf(s_aTagName, "%s%d", "Goal", cTemplates);
	}

	
	// Read the goal templates.

	for ( uint32 iTemplate = 0 ; iTemplate < cTemplates ; ++iTemplate )
	{
		ReadGoalTemplate(iTemplate);
	}

	// Read SmartObject templates.
	
	uint32 iSmartObject = 0;
	sprintf(s_aTagName, "%s%d", "SmartObject", iSmartObject);
	
	while (m_buteMgr.Exist(s_aTagName))
	{
		ReadSmartObjectTemplate(iSmartObject);
		++iSmartObject;
		sprintf(s_aTagName, "%s%d", "SmartObject", iSmartObject);
	}


	m_buteMgr.Term();

    return LTTRUE;
}
Exemple #17
0
/**
 * Parses a JSON encoded value to a JSONValue object
 *
 * @access protected
 *
 * @param wchar_t** data Pointer to a wchar_t* that contains the data
 *
 * @return JSONValue* Returns a pointer to a JSONValue object on success, NULL on error
 */
JSONValue *JSONValue::Parse(const wchar_t **data)
{
	// Is it a string?
	if (**data == '"')
	{
		std::wstring str;
		if (!JSON::ExtractString(&(++(*data)), str))
			return NULL;
		else
			return new JSONValue(str);
	}

	// Is it a boolean?
	else if ((simplejson_wcsnlen(*data, 4) && wcsncasecmp(*data, L"true", 4) == 0) || (simplejson_wcsnlen(*data, 5) && wcsncasecmp(*data, L"false", 5) == 0))
	{
		bool value = wcsncasecmp(*data, L"true", 4) == 0;
		(*data) += value ? 4 : 5;
		return new JSONValue(value);
	}

	// Is it a null?
	else if (simplejson_wcsnlen(*data, 4) && wcsncasecmp(*data, L"null", 4) == 0)
	{
		(*data) += 4;
		return new JSONValue();
	}

	// Is it a number?
	else if (**data == L'-' || (**data >= L'0' && **data <= L'9'))
	{
		// Negative?
		bool neg = **data == L'-';
		if (neg) (*data)++;

		double number = 0.0;

		// Parse the whole part of the number - only if it wasn't 0
		if (**data == L'0')
			(*data)++;
		else if (**data >= L'1' && **data <= L'9')
			number = JSON::ParseInt(data);
		else
			return NULL;

		// Could be a decimal now...
		if (**data == '.')
		{
			(*data)++;

			// Not get any digits?
			if (!(**data >= L'0' && **data <= L'9'))
				return NULL;

			// Find the decimal and sort the decimal place out
			// Use ParseDecimal as ParseInt won't work with decimals less than 0.1
			// thanks to Javier Abadia for the report & fix
			double decimal = JSON::ParseDecimal(data);

			// Save the number
			number += decimal;
		}

		// Could be an exponent now...
		if (**data == L'E' || **data == L'e')
		{
			(*data)++;

			// Check signage of expo
			bool neg_expo = false;
			if (**data == L'-' || **data == L'+')
			{
				neg_expo = **data == L'-';
				(*data)++;
			}

			// Not get any digits?
			if (!(**data >= L'0' && **data <= L'9'))
				return NULL;

			// Sort the expo out
			double expo = JSON::ParseInt(data);
			for (double i = 0.0; i < expo; i++)
				number = neg_expo ? (number / 10.0) : (number * 10.0);
		}

		// Was it neg?
		if (neg) number *= -1;

		return new JSONValue(number);
	}

	// An object?
	else if (**data == L'{')
	{
		JSONObject object;

		(*data)++;

		while (**data != 0)
		{
			// Whitespace at the start?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// Special case - empty object
			if (object.size() == 0 && **data == L'}')
			{
				(*data)++;
				return new JSONValue(object);
			}

			// We want a string now...
			std::wstring name;
			if (!JSON::ExtractString(&(++(*data)), name))
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// More whitespace?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// Need a : now
			if (*((*data)++) != L':')
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// More whitespace?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// The value is here			
			JSONValue *value = Parse(data);
			if (value == NULL)
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// Add the name:value
			if (object.find(name) != object.end())
				delete object[name];
			object[name] = value;

			// More whitespace?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_OBJECT(object);
				return NULL;
			}

			// End of object?
			if (**data == L'}')
			{
				(*data)++;
				return new JSONValue(object);
			}

			// Want a , now
			if (**data != L',')
			{
				FREE_OBJECT(object);
				return NULL;
			}

			(*data)++;
		}

		// Only here if we ran out of data
		FREE_OBJECT(object);
		return NULL;
	}

	// An array?
	else if (**data == L'[')
	{
		JSONArray array;

		(*data)++;

		while (**data != 0)
		{
			// Whitespace at the start?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_ARRAY(array);
				return NULL;
			}

			// Special case - empty array
			if (array.size() == 0 && **data == L']')
			{
				(*data)++;
				return new JSONValue(array);
			}

			// Get the value
			JSONValue *value = Parse(data);
			if (value == NULL)
			{
				FREE_ARRAY(array);
				return NULL;
			}

			// Add the value
			array.push_back(value);

			// More whitespace?
			if (!JSON::SkipWhitespace(data))
			{
				FREE_ARRAY(array);
				return NULL;
			}

			// End of array?
			if (**data == L']')
			{
				(*data)++;
				return new JSONValue(array);
			}

			// Want a , now
			if (**data != L',')
			{
				FREE_ARRAY(array);
				return NULL;
			}

			(*data)++;
		}

		// Only here if we ran out of data
		FREE_ARRAY(array);
		return NULL;
	}

	// Ran out of possibilites, it's bad!
	else
	{
		return NULL;
	}
}
Exemple #18
0
bool DllLoader::Load()
{
  if (!Parse())
  {
    CLog::Log(LOGERROR, "Unable to open dll %s", GetFileName());
    return false;
  }

  ResolveImports();
  LoadSymbols();

  // only execute DllMain if no EntryPoint is found
  if (!EntryAddress)
    ResolveExport("DllMain", (void**)&EntryAddress);

  // patch some unwanted calls in memory
  if (strstr(GetName(), "QuickTime.qts"))
  {
    int i;
    uintptr_t dispatch_addr;
    uintptr_t imagebase_addr;
    uintptr_t dispatch_rva;

    ResolveExport("theQuickTimeDispatcher", (void **)&dispatch_addr);
    imagebase_addr = (uintptr_t)hModule;
    CLog::Log(LOGDEBUG,
              "Virtual Address of theQuickTimeDispatcher = %p",
              (void *)dispatch_addr);
    CLog::Log(LOGDEBUG, "ImageBase of %s = %p",
              GetName(), (void *)imagebase_addr);

    dispatch_rva = dispatch_addr - imagebase_addr;

    CLog::Log(LOGDEBUG,
              "Relative Virtual Address of theQuickTimeDispatcher = %p",
              (void *)dispatch_rva);

    uintptr_t base = imagebase_addr;
    if (dispatch_rva == 0x124C30)
    {
      CLog::Log(LOGINFO, "QuickTime5 DLLs found\n");
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x19e842)[i] = 0x90; // make_new_region ?
      for (i = 0;i < 28;i++) ((BYTE*)base + 0x19e86d)[i] = 0x90; // call__call_CreateCompatibleDC ?
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x19e898)[i] = 0x90; // jmp_to_call_loadbitmap ?
      for (i = 0;i < 9;i++) ((BYTE*)base + 0x19e8ac)[i] = 0x90; // call__calls_OLE_shit ?
      for (i = 0;i < 106;i++) ((BYTE*)base + 0x261B10)[i] = 0x90; // disable threads
    }
    else if (dispatch_rva == 0x13B330)
    {
      CLog::Log(LOGINFO, "QuickTime6 DLLs found\n");
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x2730CC)[i] = 0x90; // make_new_region
      for (i = 0;i < 28;i++) ((BYTE*)base + 0x2730f7)[i] = 0x90; // call__call_CreateCompatibleDC
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x273122)[i] = 0x90; // jmp_to_call_loadbitmap
      for (i = 0;i < 9;i++) ((BYTE*)base + 0x273131)[i] = 0x90; // call__calls_OLE_shit
      for (i = 0;i < 96;i++) ((BYTE*)base + 0x2AC852)[i] = 0x90; // disable threads
    }
    else if (dispatch_rva == 0x13C3E0)
    {
      CLog::Log(LOGINFO, "QuickTime6.3 DLLs found\n");
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x268F6C)[i] = 0x90; // make_new_region
      for (i = 0;i < 28;i++) ((BYTE*)base + 0x268F97)[i] = 0x90; // call__call_CreateCompatibleDC
      for (i = 0;i < 5;i++) ((BYTE*)base + 0x268FC2)[i] = 0x90; // jmp_to_call_loadbitmap
      for (i = 0;i < 9;i++) ((BYTE*)base + 0x268FD1)[i] = 0x90; // call__calls_OLE_shit
      for (i = 0;i < 96;i++) ((BYTE*)base + 0x2B4722)[i] = 0x90; // disable threads
    }
    else
    {
      CLog::Log(LOGERROR, "Unsupported QuickTime version");
    }

    CLog::Log(LOGINFO, "QuickTime.qts patched!!!\n");
  }

#ifdef LOGALL
  CLog::Log(LOGDEBUG, "Executing EntryPoint with DLL_PROCESS_ATTACH at: 0x%x - Dll: %s", pLoader->EntryAddress, sName);
#endif

  if(EntryAddress)
  {
    EntryFunc initdll = (EntryFunc)EntryAddress;
    /* since we are handing execution over to unknown code, safeguard here */
    try
    {
#ifdef _LINUX
	extend_stack_for_dll_alloca();
#endif
      initdll((HINSTANCE)hModule, DLL_PROCESS_ATTACH , 0); //call "DllMain" with DLL_PROCESS_ATTACH

#ifdef LOGALL
      CLog::Log(LOGDEBUG, "EntryPoint with DLL_PROCESS_ATTACH called - Dll: %s", sName);
#endif

    }
    XBMCCOMMONS_HANDLE_UNCHECKED
    catch(...)
    {
      CLog::Log(LOGERROR, "%s - Unhandled exception during DLL_PROCESS_ATTACH", __FUNCTION__);

      // vp7vfw.dll throws a CUserException due to a missing export
      // but the export isn't really needed for normal operation
      // and dll works anyway, so let's ignore it

      if(stricmp(GetName(), "vp7vfw.dll") != 0)
        return false;


      CLog::Log(LOGDEBUG, "%s - Ignoring exception during DLL_PROCESS_ATTACH", __FUNCTION__);
    }

    // init function may have fixed up the export table
    // this is what I expect should happens on PECompact2
    // dll's if export table is compressed.
    if(!m_pExportHead)
      LoadExports();
  }

  return true;
}
CDate CDate::Parse(const core::string& str)
{
	CDate ret;
	Parse(str, ret);
	return ret;
}
Exemple #20
0
tst_t *Parse_config_string(bstring content) 
{
    Token *temp = NULL;
    void *parser = ParseAlloc(malloc);
    check_mem(parser);
    ParserState state = {.settings = NULL, .error = 0, .line_number = 1};

    char *p = bdata(content);
    char *pe = bdataofs(content, blength(content) - 1);
    char *eof = pe;
    int cs = -1;
    int act = -1;
    char *ts = NULL;
    char *te = NULL;

    
#line 80 "src/lexer.c"
	{
	cs = m2sh_lexer_start;
	ts = 0;
	te = 0;
	act = 0;
	}

#line 103 "src/lexer.rl"
    
#line 90 "src/lexer.c"
	{
	if ( p == pe )
		goto _test_eof;
	switch ( cs )
	{
tr1:
#line 44 "src/lexer.rl"
	{te = p+1;{ TKSTR(QSTRING) }}
	goto st8;
tr4:
#line 59 "src/lexer.rl"
	{te = p+1;}
	goto st8;
tr9:
#line 45 "src/lexer.rl"
	{te = p+1;{ TKSTR(PATTERN) }}
	goto st8;
tr10:
#line 57 "src/lexer.rl"
	{te = p+1;}
	goto st8;
tr12:
#line 56 "src/lexer.rl"
	{te = p+1;{ state.line_number++; }}
	goto st8;
tr13:
#line 51 "src/lexer.rl"
	{te = p+1;{ TK(LPAREN) }}
	goto st8;
tr14:
#line 52 "src/lexer.rl"
	{te = p+1;{ TK(RPAREN) }}
	goto st8;
tr15:
#line 53 "src/lexer.rl"
	{te = p+1;{ TK(COMMA) }}
	goto st8;
tr17:
#line 54 "src/lexer.rl"
	{te = p+1;{ TK(COLON) }}
	goto st8;
tr18:
#line 46 "src/lexer.rl"
	{te = p+1;{ TK(EQ) }}
	goto st8;
tr20:
#line 49 "src/lexer.rl"
	{te = p+1;{ TK(LBRACE) }}
	goto st8;
tr21:
#line 50 "src/lexer.rl"
	{te = p+1;{ TK(RBRACE) }}
	goto st8;
tr23:
#line 47 "src/lexer.rl"
	{te = p+1;{ TK(LBRACKET) }}
	goto st8;
tr24:
#line 48 "src/lexer.rl"
	{te = p+1;{ TK(RBRACKET) }}
	goto st8;
tr25:
#line 61 "src/lexer.rl"
	{te = p;p--;{ TK(NUMBER) }}
	goto st8;
tr26:
#line 1 "src/lexer.rl"
	{	switch( act ) {
	case 16:
	{{p = ((te))-1;} TK(CLASS) }
	break;
	case 17:
	{{p = ((te))-1;} TK(IDENT) }
	break;
	}
	}
	goto st8;
tr28:
#line 63 "src/lexer.rl"
	{te = p;p--;{ TK(IDENT) }}
	goto st8;
st8:
#line 1 "src/lexer.rl"
	{ts = 0;}
	if ( ++p == pe )
		goto _test_eof8;
case 8:
#line 1 "src/lexer.rl"
	{ts = p;}
#line 180 "src/lexer.c"
	switch( (*p) ) {
		case 10: goto tr12;
		case 32: goto tr10;
		case 34: goto st1;
		case 35: goto st3;
		case 39: goto st4;
		case 40: goto tr13;
		case 41: goto tr14;
		case 44: goto tr15;
		case 58: goto tr17;
		case 61: goto tr18;
		case 91: goto tr20;
		case 93: goto tr21;
		case 96: goto st6;
		case 123: goto tr23;
		case 125: goto tr24;
	}
	if ( (*p) < 48 ) {
		if ( 9 <= (*p) && (*p) <= 13 )
			goto tr10;
	} else if ( (*p) > 57 ) {
		if ( (*p) > 90 ) {
			if ( 95 <= (*p) && (*p) <= 122 )
				goto st11;
		} else if ( (*p) >= 65 )
			goto tr19;
	} else
		goto st9;
	goto st0;
st0:
cs = 0;
	goto _out;
st1:
	if ( ++p == pe )
		goto _test_eof1;
case 1:
	switch( (*p) ) {
		case 34: goto tr1;
		case 92: goto st2;
	}
	goto st1;
st2:
	if ( ++p == pe )
		goto _test_eof2;
case 2:
	goto st1;
st3:
	if ( ++p == pe )
		goto _test_eof3;
case 3:
	if ( (*p) == 10 )
		goto tr4;
	goto st3;
st4:
	if ( ++p == pe )
		goto _test_eof4;
case 4:
	switch( (*p) ) {
		case 39: goto tr1;
		case 92: goto st5;
	}
	goto st4;
st5:
	if ( ++p == pe )
		goto _test_eof5;
case 5:
	goto st4;
st9:
	if ( ++p == pe )
		goto _test_eof9;
case 9:
	if ( 48 <= (*p) && (*p) <= 57 )
		goto st9;
	goto tr25;
tr19:
#line 1 "src/lexer.rl"
	{te = p+1;}
#line 63 "src/lexer.rl"
	{act = 17;}
	goto st10;
tr27:
#line 1 "src/lexer.rl"
	{te = p+1;}
#line 62 "src/lexer.rl"
	{act = 16;}
	goto st10;
st10:
	if ( ++p == pe )
		goto _test_eof10;
case 10:
#line 271 "src/lexer.c"
	if ( (*p) == 95 )
		goto st11;
	if ( (*p) < 65 ) {
		if ( 48 <= (*p) && (*p) <= 57 )
			goto st11;
	} else if ( (*p) > 90 ) {
		if ( 97 <= (*p) && (*p) <= 122 )
			goto tr27;
	} else
		goto tr27;
	goto tr26;
st11:
	if ( ++p == pe )
		goto _test_eof11;
case 11:
	if ( (*p) == 95 )
		goto st11;
	if ( (*p) < 65 ) {
		if ( 48 <= (*p) && (*p) <= 57 )
			goto st11;
	} else if ( (*p) > 90 ) {
		if ( 97 <= (*p) && (*p) <= 122 )
			goto st11;
	} else
		goto st11;
	goto tr28;
st6:
	if ( ++p == pe )
		goto _test_eof6;
case 6:
	switch( (*p) ) {
		case 92: goto st7;
		case 96: goto tr9;
	}
	goto st6;
st7:
	if ( ++p == pe )
		goto _test_eof7;
case 7:
	goto st6;
	}
	_test_eof8: cs = 8; goto _test_eof; 
	_test_eof1: cs = 1; goto _test_eof; 
	_test_eof2: cs = 2; goto _test_eof; 
	_test_eof3: cs = 3; goto _test_eof; 
	_test_eof4: cs = 4; goto _test_eof; 
	_test_eof5: cs = 5; goto _test_eof; 
	_test_eof9: cs = 9; goto _test_eof; 
	_test_eof10: cs = 10; goto _test_eof; 
	_test_eof11: cs = 11; goto _test_eof; 
	_test_eof6: cs = 6; goto _test_eof; 
	_test_eof7: cs = 7; goto _test_eof; 

	_test_eof: {}
	if ( p == eof )
	{
	switch ( cs ) {
	case 9: goto tr25;
	case 10: goto tr26;
	case 11: goto tr28;
	}
	}

	_out: {}
	}

#line 104 "src/lexer.rl"


    if(state.error) {
        Parse_print_error("SYNTAX ERROR", content, 
                (int)(ts - bdata(content)), ++state.line_number);
    } else if( cs == 
#line 345 "src/lexer.c"
0
#line 109 "src/lexer.rl"
 ) {
        Parse_print_error("INVALID CHARACTER", content,
                (int)(ts - bdata(content)), ++state.line_number);
    } else if( cs >= 
#line 352 "src/lexer.c"
8
#line 112 "src/lexer.rl"
 ) {
        Parse(parser, TKEOF, NULL, &state);
    } else {
        log_err("INCOMPLETE CONFIG FILE. There needs to be more to this.");
    }

    Parse(parser, 0, 0, &state);
    ParseFree(parser, free);

    return state.settings;

error:
    if(state.error) {
        Parse_print_error("SYNTAX ERROR", content, 
                (int)(ts - bdata(content)), ++state.line_number);
    }
    ParseFree(parser, free);
    return NULL;
}


tst_t *Parse_config_file(const char *path)
{
    FILE *script;
    bstring buffer = NULL;
    tst_t *settings = NULL;

    script = fopen(path, "r");
    check(script, "Failed to open file: %s", path);

    buffer = bread((bNread)fread, script);
    check_mem(buffer);

    fclose(script); script = NULL;

    settings = Parse_config_string(buffer);
    check(settings != NULL, "Failed to parse file: %s", path);

    bdestroy(buffer);
    buffer = NULL;

    return settings;

error:
    bdestroy(buffer);
    if(script) fclose(script);
    return NULL;
}
Exemple #21
0
bool CXBMCTinyXML::Parse(const char *_data, TiXmlEncoding encoding)
{
  return Parse(std::string(_data), encoding);
}
Exemple #22
0
	JsonMessage::JsonMessage(const JsonMessage& message)
		: chromecast::JsonMessagePart(_document, _allocator),
		_document(&_allocator)
	{
		Parse(message.ToString());
	}
Exemple #23
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
    if ( !file )
    {
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Delete the existing data:
    Clear();
    location.Clear();

    // Get the file size, so we can pre-allocate the string. HUGE speed impact.
    long length = 0;
    fseek( file, 0, SEEK_END );
    length = ftell( file );
    fseek( file, 0, SEEK_SET );

    // Strange case, but good to handle up front.
    if ( length <= 0 )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // If we have a file, assume it is all one big XML file, and read it in.
    // The document parser may decide the document ends sooner than the entire file, however.
    TIXML_STRING data;
    data.reserve( length );

    // Subtle bug here. TinyXml did use fgets. But from the XML spec:
    // 2.11 End-of-Line Handling
    // <snip>
    // <quote>
    // ...the XML processor MUST behave as if it normalized all line breaks in external
    // parsed entities (including the document entity) on input, before parsing, by translating
    // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to
    // a single #xA character.
    // </quote>
    //
    // It is not clear fgets does that, and certainly isn't clear it works cross platform.
    // Generally, you expect fgets to translate from the convention of the OS to the c/unix
    // convention, and not work generally.

    /*
    while( fgets( buf, sizeof(buf), file ) )
    {
    	data += buf;
    }
    */

    char* buf = new char[ length+1 ];
    buf[0] = 0;

    if ( fread( buf, length, 1, file ) != 1 ) {
        delete [] buf;
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    const char* lastPos = buf;
    const char* p = buf;

    buf[length] = 0;
    while( *p ) {
        assert( p < (buf+length) );
        if ( *p == 0xa ) {
            // Newline character. No special rules for this. Append all the characters
            // since the last string, and include the newline.
            data.append( lastPos, (p-lastPos+1) );	// append, include the newline
            ++p;									// move past the newline
            lastPos = p;							// and point to the new buffer (may be 0)
            assert( p <= (buf+length) );
        }
        else if ( *p == 0xd ) {
            // Carriage return. Append what we have so far, then
            // handle moving forward in the buffer.
            if ( (p-lastPos) > 0 ) {
                data.append( lastPos, p-lastPos );	// do not add the CR
            }
            data += (char)0xa;						// a proper newline

            if ( *(p+1) == 0xa ) {
                // Carriage return - new line sequence
                p += 2;
                lastPos = p;
                assert( p <= (buf+length) );
            }
            else {
                // it was followed by something else...that is presumably characters again.
                ++p;
                lastPos = p;
                assert( p <= (buf+length) );
            }
        }
        else {
            ++p;
        }
    }
    // Handle any left over characters.
    if ( p-lastPos ) {
        data.append( lastPos, p-lastPos );
    }
    delete [] buf;
    buf = 0;

    Parse( data.c_str(), 0, encoding );

    if (  Error() )
        return false;
    else
        return true;
}
Exemple #24
0
UniValue deriveaddresses(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.empty() || request.params.size() > 2) {
        throw std::runtime_error(
            RPCHelpMan{"deriveaddresses",
            {"\nDerives one or more addresses corresponding to an output descriptor.\n"
            "Examples of output descriptors are:\n"
            "    pkh(<pubkey>)                        P2PKH outputs for the given pubkey\n"
            "    wpkh(<pubkey>)                       Native segwit P2PKH outputs for the given pubkey\n"
            "    sh(multi(<n>,<pubkey>,<pubkey>,...)) P2SH-multisig outputs for the given threshold and pubkeys\n"
            "    raw(<hex script>)                    Outputs whose scriptPubKey equals the specified hex scripts\n"
            "\nIn the above, <pubkey> either refers to a fixed public key in hexadecimal notation, or to an xpub/xprv optionally followed by one\n"
            "or more path elements separated by \"/\", where \"h\" represents a hardened child key.\n"
            "For more information on output descriptors, see the documentation in the doc/descriptors.md file.\n"},
            {
                {"descriptor", RPCArg::Type::STR, RPCArg::Optional::NO, "The descriptor."},
                {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED_NAMED_ARG, "If a ranged descriptor is used, this specifies the end or the range (in [begin,end] notation) to derive."},
            },
            RPCResult{
                "[ address ] (array) the derived addresses\n"
            },
            RPCExamples{
                "First three native segwit receive addresses\n" +
                HelpExampleCli("deriveaddresses", "\"wpkh([d34db33f/84h/0h/0h]xpub6DJ2dNUysrn5Vt36jH2KLBT2i1auw1tTSSomg8PhqNiUtx8QX2SvC9nrHu81fT41fvDUnhMjEzQgXnQjKEu3oaqMSzhSrHMxyyoEAmUHQbY/0/*)#cjjspncu\" \"[0,2]\"")
            }}.ToString()
        );
    }

    RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType()}); // Range argument is checked later
    const std::string desc_str = request.params[0].get_str();

    int64_t range_begin = 0;
    int64_t range_end = 0;

    if (request.params.size() >= 2 && !request.params[1].isNull()) {
        std::tie(range_begin, range_end) = ParseDescriptorRange(request.params[1]);
    }

    FlatSigningProvider key_provider;
    auto desc = Parse(desc_str, key_provider, /* require_checksum = */ true);
    if (!desc) {
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Invalid descriptor"));
    }

    if (!desc->IsRange() && request.params.size() > 1) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
    }

    if (desc->IsRange() && request.params.size() == 1) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Range must be specified for a ranged descriptor");
    }

    UniValue addresses(UniValue::VARR);

    for (int i = range_begin; i <= range_end; ++i) {
        FlatSigningProvider provider;
        std::vector<CScript> scripts;
        if (!desc->Expand(i, key_provider, scripts, provider)) {
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Cannot derive script without private keys"));
        }

        for (const CScript &script : scripts) {
            CTxDestination dest;
            if (!ExtractDestination(script, dest)) {
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Descriptor does not have a corresponding address"));
            }

            addresses.push_back(EncodeDestination(dest));
        }
    }

    // This should not be possible, but an assert seems overkill:
    if (addresses.empty()) {
        throw JSONRPCError(RPC_MISC_ERROR, "Unexpected empty result");
    }

    return addresses;
}
Exemple #25
0
int main(int argc, char *argv[]) {
 transferfun *transfer;
 char driverName[13];
 int stilloptions=1;
 char *home;
 brlapi_settings_t brlapi_settings;
 
 transfer=CheckSendOrRecv(argv[0]);

/* first use options file */
 if ((home=getenv("HOME"))) {
  char vstprc[strlen(home)+strlen(VSTPRC)+2];
  strcpy(vstprc,home);
  strcat(vstprc,"/" VSTPRC);
  Parse(vstprc);
 }

/* a first pass to check options and record them, before doing anything */
 CheckOptions(argc--,argv++);

/* ok, one can try to open the socket */
 brlapi_settings.host = socketport;
 brlapi_settings.auth = keyname; 
 if (brlapi_initializeConnection(&brlapi_settings,NULL)<0)
 {
  brlapi_perror("Couldn't initialize connection with BrlAPI");
  exit(RET_ECONN);
 }
 if (brlapi_getDriverName(driverName, sizeof(driverName))<12)
 {
  brlapi_perror("Couldn't get driver name");
  brlapi_closeConnection();
  exit(RET_ECONN);
 }
 if (strcmp(driverName,"VisioBraille"))
 {
  fprintf(stderr,"braille driver is not VisioBraille\n");
  brlapi_closeConnection();
  exit(RET_ECONN);  
 }
 
 if (brlapi_enterRawMode("VisioBraille")<0) {
  fprintf(stderr,"Couldn't get raw mode\n");
  brlapi_closeConnection();
  exit(RET_ECONN);
 }

 signal(SIGINT,handleint);
 signal(SIGTERM,handleint);

#ifdef SIGHUP
 signal(SIGHUP,handleint);
#endif /* SIGHUP */

#ifdef SIGQUIT
 signal(SIGQUIT,handleint);
#endif /* SIGQUIT */

#ifdef SIGPIPE
 signal(SIGPIPE,handleint);
#endif /* SIGPIPE */

#ifdef SIGALRM
 signal(SIGALRM,transfer_timeout);
#endif /* SIGALRM */

 if (visiobases_dir && chdir(visiobases_dir)<0) {
  perror(visiobases_dir);
  fprintf(stderr,"couldn't chdir to download dir, please use -d if you want to store files in .\n");
  exit(RET_EUNIX);
 }

 for(;argc;argc--, argv++) {
/* is it an option ? */
  if (stilloptions)
  if (argv[0][0]=='-') {
   switch (argv[0][1]) {
     case '-': stilloptions=0; continue;
     case 's': /* already parsed */
     case 'k':
     case 'm':
	       argc--;
	       argv++;
     case 'b':
     case 'n':
     case 'f':
     case 'i':
     case 'd':
     default:
	       continue;
   }
  }
  
/* no, a file name, let's try to transfer it */
  transfer(argv[0]);
 }
 printf("transfers finished\n");
 transfer_finish(transfer);
 brlapi_leaveRawMode(); /* can't do much it it fails ! */
 brlapi_closeConnection();
 return 0;
}
Exemple #26
0
static int Level6( double* r )
{
   int  i;
   int  n;
   double a[3];

   if( *token == '(' )
   {
      Parse();
      if( *token == ')' )
         return( E_NOARG );
      Level1( r );
      if( *token != ')' )
         return( E_UNBALAN );
      Parse();
   }
   else
   {
      if( type == NUM )
      {
         *r = (double) atof( token );
         Parse();
      }
      else if( type == VAR )
      {
         if( *expression == '(' )
         {
            for( i = 0; *Funcs[i].name; i++ )
               if( ! strcmp( token, Funcs[i].name ) )
               {
                  Parse();
                  n = 0;
                  do
                  {
                     Parse();
                     if( *token == ')' || *token == ',' )
                        return( E_NOARG );
                     a[n] = 0;
                     Level1( &a[n] );
                     n++;
                  } while( n < 4 && *token == ',' );
                  Parse();
                  if( n != Funcs[i].args )
                  {
                     strcpy( token, Funcs[i].name );
                     return( E_NUMARGS );
                  }
                  //*r = Funcs[i].func( a[0], a[1], a[2] );
                  *r = Funcs[i].func( a[0] );
                  return E_OK;
               }
               if( ! *Funcs[i].name )
                  return( E_BADFUNC );
            }
            else if( ! GetValue( token, r ) )
               return( E_UNKNOWN );
         Parse();
      }
      else
         return( E_SYNTAX );
   }
   return E_OK;
}
Exemple #27
0
/* The main program.  Parse the command line and do it... */
int main(int argc, char **argv)
{
    static int version = 0;
    static int rpflag = 0;
    static int basisflag = 0;
    static int compress = 0;
    static int quiet = 0;
    static int statistics = 0;
    static int mhflag = 0;
    static struct s_options options[] = {
        {OPT_FLAG, "b", (char*)&basisflag, "Print only the basis in report."},
        {OPT_FLAG, "c", (char*)&compress, "Don't compress the action table."},
        {OPT_FSTR, "D", (char*)handle_D_option, "Define an %ifdef macro."},
        {OPT_FLAG, "g", (char*)&rpflag, "Print grammar without actions."},
        {OPT_FSTR, "l", (char*)handle_l_option, "Set an output language (c, c++, d)."},
        {OPT_FLAG, "m", (char*)&mhflag, "Output a makeheaders compatible file"},
        {OPT_FLAG, "q", (char*)&quiet, "(Quiet) Don't print the report file."},
        {OPT_FLAG, "s", (char*)&statistics,
            "Print parser stats to standard output."},
        {OPT_FLAG, "x", (char*)&version, "Print the version number."},
        {OPT_FLAG,0,0,0}
    };
    int i;
    struct lemon lem;
    
    OptInit(argv,options,stderr);
    if( version ){
        printf("Lemon version 1.0\n");
        exit(0);
    }
    if( OptNArgs()!=1 ){
        ErrorMsg("lemon", LINENO_NONE, "Exactly one filename argument is required.\n");
        exit(1);
    }
    memset(&lem, 0, sizeof(lem));
    lem.errorcnt = 0;
    
    /* Initialize the machine */
    Strsafe_init();
    Symbol_init();
    State_init();
    lem.argv0 = argv[0];
    lem.filename = OptArg(0);
    lem.basisflag = basisflag;
    Symbol_new("$");
    lem.errsym = Symbol_new("error");
    lem.errsym->useCnt = 0;
    
    /* Parse the input file */
    Parse(&lem);
    if( lem.errorcnt ) exit(lem.errorcnt);
        if( lem.nrule==0 ){
            ErrorMsg(lem.filename, LINENO_NONE, "Empty grammar.\n");
            exit(1);
        }
    
    /* Count and index the symbols of the grammar */
    lem.nsymbol = Symbol_count();
    Symbol_new("{default}");
    lem.symbols = Symbol_arrayof();
    for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
        qsort(lem.symbols,lem.nsymbol+1,sizeof(struct symbol*),
              (int(*)())Symbolcmpp);
        for(i=0; i<=lem.nsymbol; i++) lem.symbols[i]->index = i;
            for(i=1; isupper(lem.symbols[i]->name[0]); i++);
    lem.nterminal = i;
    
    /* Generate a reprint of the grammar, if requested on the command line */
    if( rpflag ){
        Reprint(&lem);
    }else{
        /* Initialize the size for all follow and first sets */
        SetSize(lem.nterminal+1);
        
        /* Find the precedence for every production rule (that has one) */
        FindRulePrecedences(&lem);
        
        /* Compute the lambda-nonterminals and the first-sets for every
         ** nonterminal */
        FindFirstSets(&lem);
        
        /* Compute all LR(0) states.  Also record follow-set propagation
         ** links so that the follow-set can be computed later */
        lem.nstate = 0;
        FindStates(&lem);
        lem.sorted = State_arrayof();
        
        /* Tie up loose ends on the propagation links */
        FindLinks(&lem);
        
        /* Compute the follow set of every reducible configuration */
        FindFollowSets(&lem);
        
        /* Compute the action tables */
        FindActions(&lem);
        
        /* Compress the action tables */
        if( compress==0 ) CompressTables(&lem);
        
        /* Reorder and renumber the states so that states with fewer choices
         ** occur at the end. */
        ResortStates(&lem);
        
        /* Generate a report of the parser generated.  (the "y.output" file) */
        if( !quiet ) ReportOutput(&lem);
        
        /* Generate the source code for the parser */
        ReportTable(&lem, mhflag);
        
        /* Produce a header file for use by the scanner.  (This step is
         ** omitted if the "-m" option is used because makeheaders will
         ** generate the file for us.) */
        if (! mhflag && language != LANG_D)
            ReportHeader(&lem);
    }
    if( statistics ){
        LogMsg(LOGLEVEL_INFO, lem.filename, LINENO_NONE,
               "Parser statistics: %d terminals, %d nonterminals, %d rules\n",
               lem.nterminal, lem.nsymbol - lem.nterminal, lem.nrule);
        LogMsg(LOGLEVEL_INFO, lem.filename, LINENO_NONE,
               "                   %d states, %d parser table entries, %d conflicts\n",
               lem.nstate, lem.tablesize, lem.nconflict);
    }
    if( lem.nconflict ){
        LogMsg(LOGLEVEL_WARNING, lem.filename, LINENO_NONE, "%d parsing conflicts.\n", lem.nconflict);
    }
    exit(lem.errorcnt + lem.nconflict);
    return (lem.errorcnt + lem.nconflict);
}
Exemple #28
0
void JsonArrayNode::Parse( const tstring& content )
{
	Parse(content.c_str(), content.length());
}
bool TiXmlDocument::ReadFromMemory( const char* pBuf, size_t sz, TiXmlEncoding encoding)
{
    // Delete the existing data:
    Clear();
    location.Clear();

    // Get the file size, so we can pre-allocate the string. HUGE speed impact.
    long length = (long) sz;

    // Strange case, but good to handle up front.
    if ( length == 0 )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // If we have a file, assume it is all one big XML file, and read it in.
    // The document parser may decide the document ends sooner than the entire file, however.
    TIXML_STRING data;
    data.reserve( length );


    char* buf = new char[ length+1 ];
    memset(buf,0,length+1);

    memcpy(buf, pBuf, length);

    const char* lastPos = buf;
    const char* p = buf;

    buf[length] = 0;
    while( *p ) {
        assert( p < (buf+length) );
        if ( *p == 0xa ) {
            // Newline character. No special rules for this. Append all the characters
            // since the last string, and include the newline.
            data.append( lastPos, (p-lastPos+1) );  // append, include the newline
            ++p;                                    // move past the newline
            lastPos = p;                            // and point to the new buffer (may be 0)
            assert( p <= (buf+length) );
        }
        else if ( *p == 0xd ) {
            // Carriage return. Append what we have so far, then
            // handle moving forward in the buffer.
            if ( (p-lastPos) > 0 ) {
                data.append( lastPos, p-lastPos );  // do not add the CR
            }
            data += (char)0xa;                      // a proper newline

            if ( *(p+1) == 0xa ) {
                // Carriage return - new line sequence
                p += 2;
                lastPos = p;
                assert( p <= (buf+length) );
            }
            else {
                // it was followed by something else...that is presumably characters again.
                ++p;
                lastPos = p;
                assert( p <= (buf+length) );
            }
        }
        else {
            ++p;
        }
    }
    // Handle any left over characters.
    if ( p-lastPos ) {
        data.append( lastPos, p-lastPos );
    }
    delete [] buf;
    buf = 0;

    Parse( data.c_str(), 0, encoding );

    if (  Error() )
        return false;
    else
        return true;
}
Exemple #30
0
void CXmlDocument::Parse(const CString& xml_str)
{
	Parse(xml_str.GetBuffer());
}