Пример #1
0
bool Texture::load( Bitmap* bmp, unsigned int flags )
{
	mFlags = (flags & (~_INTERNAL_BITS));

	// set anisotropic filtering only if we've got it ... 
	if(/*doesn't support anisotropic filtering*/ false )
		mFlags = (flags & (~Anisotropic));

	//if( flags & BuildMipmaps ) 
	//	bmp->
	mBitmap = bmp;
	mFlags = mBitmap->flags()|flags;
	mWidth = mBitmap->width();
	mHeight = mBitmap->height();
	processFlags();

	if( !(mFlags & KeepLocal) )
	{
		delete mBitmap;
		mBitmap = NULL;
	}

	mFlags |= Loaded;
	return true;
}
Пример #2
0
bool Texture::load()
{
	if( mBitmap != NULL )
	{
		processFlags();
		return true;
	}
	else
		return load( mFileName, mFlags );
}
Пример #3
0
int main(int argc,char **argv){
	
	tempClausesFileGlobal = NULL;
	numClausesGlobal = 0;
	
	if(argc == 1){
		endHelp();
	}
	
	sabrDirGlobal = getDir(argv[0]);
	
	// current argument
	int a = processFlags(argc,argv);
	
	if(a >= argc || !atoi(argv[a])){
		endErrorMsg("Positive Integer Number Of Levels Must Be Input First");
	}
	
	curLineNumGlobal = 1;
	numStagesGlobal = atoi(argv[a]);
	inventNameNumGlobal = 0;
	endFileGlobal = 0;
	
	a++;
	if(a >= argc){
		endErrorMsg("Must Enter Source File");
	}
	
	char *file = argv[a];
	fileRead(file);
	
	a++;
	if(a != argc){
		endErrorMsg("Too Many Arguments");
	}
	
	initSym();

	yyparse();

	destroyLinked(symTableGlobal,freeSyms);
	// could use Malloc-L, Free-L and MemInfo to show no memory lost
	// should say: "Leak Size: 0"
	
	return 0;
}
Пример #4
0
/**
 * Process comment-embedded options, without affecting the JavaScript line count.
 * Comments are in the block directly below the she-bang, with no intervening newline.
 *
 * @param	cs		JavaScript Context
 * @param	scriptFile	Script file, with file pointer set to either first char or \n on first line,
 * @param	verbosity_p	[in,out] verbosity_p parameter from processFlags
 */
static void processInlineFlags(JSContext *cx, FILE *scriptFile, signed int *verbosity_p)
{
  char	buf[256];
  off_t	offset;
  int	c;

  offset = ftello(scriptFile);	/* File is at \n of she-bang line or at start of line */
  
  c = fgetc(scriptFile);
  if (c != '\n')
    ungetc(c, scriptFile);

  while(fgets(buf, sizeof(buf), scriptFile))
  {
    char *s, *e;

    if ((buf[0] != '/') || (buf[1] != '/'))
      break;

    for (s = buf + 2; *s == ' ' || *s == '\t'; s++);
    if (strncmp(s, "gpsee:", 6) != 0)
      continue;

    for (s = s + 6; *s == ' ' || *s == '\t'; s++);

    for (e = s; *e; e++)
    {
      switch(*e)
      {
	case '\r':
	case '\n':
	case '\t':
	case ' ':
	  *e = (char)0;
	  break;
      }
    }

    if (s[0])
      processFlags(cx, s, verbosity_p);
  }

  fseeko(scriptFile, offset, SEEK_SET);
}
Пример #5
0
		/*
		 * Make spidermonkey think the script starts with a blank line,
		 * to keep line numbers in sync.
		 */
		ungetc('\n', fp);
	    }
	}
    }

exit:

RPMJSDBG(0, (stderr, "<== %s(%p,%s,%p) fp %p\n", __FUNCTION__, js, fn, msgp, fp));

    return fp;
}

#ifdef	NOTYET	/* XXX FIXME */
static void processInlineFlags(rpmjs js, FILE * fp, signed int *verbosity_p)
{
    char buf[256];
    off_t offset;

    offset = ftello(fp);

    while (fgets(buf, sizeof(buf), fp)) {
	char *s, *e;

	if ((buf[0] != '/') || (buf[1] != '/'))
	    break;

	for (s = buf + 2; *s == ' ' || *s == '\t'; s++);
	if (strncmp(s, "gpsee:", 6) != 0)
	    continue;

	for (s = s + 6; *s == ' ' || *s == '\t'; s++);

	for (e = s; *e; e++) {
	    switch (*e) {
	    case '\r':
	    case '\n':
	    case '\t':
	    case ' ':
		*e = '\0';
		break;
	    }
	}

	if (s[0])
	    processFlags(gsr, s, verbosity_p);
    }

    fseeko(fp, offset, SEEK_SET);
}
Пример #6
0
void ChannelReceivingThread::run ()
{
    AppLog::detail (mLoggerName, "Starting up.");
    
    char correctMessageReceived = true;
    
    // first, receive the incoming host list
    // read up to the first occurrence of "EndHostList", allowing 10,000
    // characters
    char *readListBuffer = readStreamUpToTag (mInputStream,
                                              "EndHostList", 10000);
    if (readListBuffer != NULL)
    {
        
        AppLog::trace (mLoggerName, readListBuffer);
        
        // tokenize it
        SimpleVector < char *>*tokenVector;

        if(settings->getAcceptSeedNodes()) {
            tokenVector = tokenizeString (readListBuffer);
        }
        else {
            AppLog::detail(mLoggerName, "Host List received is ignored for user settings");
            tokenVector= new SimpleVector<char *>();
        }
        
        
        delete[]readListBuffer;
        
        
        int numTokens = tokenVector->size ();
        
        // count should be second token, so skip first two
        
        int i;
        for (i = 2; i < numTokens - 1; i += 2)
        {
            
            char *addressString = *(tokenVector->getElement (i));
            char *portString = *(tokenVector->getElement (i + 1));
            
            int port;
            
            int numRead = sscanf (portString, "%d", &port);
            
            if (numRead == 1)
            {
                HostAddress *address =
                        new HostAddress (stringDuplicate (addressString), port);
                mHostCatcher->addHost (address);
                delete address;
            }
        }
        
        for (i = 0; i < numTokens; i++)
        {
            delete[] * (tokenVector->getElement (i));
        }
        
        delete tokenVector;
    }
    else
    {
        AppLog::error (mLoggerName, "Failed to receive host list.");
        correctMessageReceived = false;
    }
    
    
    // check for an accpeted connection status
    
    char connectionAccepted = false;
    
    if (correctMessageReceived)
    {
        correctMessageReceived = false;
        
        // next, receive the connection status
        char *readStatusBuffer =
                readStreamUpToTag (mInputStream, "EndConnectionStatus", 1000);
        
        if (readStatusBuffer != NULL)
        {
            AppLog::trace (mLoggerName, readStatusBuffer);
            
            // tokenize it
            SimpleVector < char *>*tokenVector =
                    tokenizeString (readStatusBuffer);
            
            delete[]readStatusBuffer;
            

            int numTokens = tokenVector->size ();
            
            if (numTokens > 2)
            {
                // second token is status
                char *status = *(tokenVector->getElement (1));
                
                if (strcmp (status, "Accepted") == 0)
                {
                    connectionAccepted = true;
                    correctMessageReceived = true;
                    // we are actually connected now
                    AppLog::info (mLoggerName,
                                  "Connection accepted by remote host.");
                    
                    // log it, if needed
                    int logConnectionsFlag = settings->getLogConnectionsSetting();
                    
                    if (logConnectionsFlag == 1)
                    {
                        FILE *connectionLogFILE =
                                fopen ("connectionHistory.log", "a");
                        
                        if (connectionLogFILE != NULL)
                        {
                            
                            fprintf (connectionLogFILE, "%s : %d\n",
                                     mRemoteAddress, mRemotePort);
                            
                            fclose (connectionLogFILE);
                        }
                    }
                    
                }
                else if (strcmp (status, "Rejected") == 0)
                {
                    connectionAccepted = false;
                    correctMessageReceived = true;
                    
                    AppLog::info (mLoggerName,
                                  "Connection rejected by remote host.");
                }
            }
            
            for (int i = 0; i < numTokens; i++)
            {
                delete[] * (tokenVector->getElement (i));
            }
            delete tokenVector;
        }
        
        if (!correctMessageReceived)
        {
            AppLog::error (mLoggerName, "Failed to receive connection status.");
        }
    }
    
    
    
    
    // now read a series of MUTE messages
    
    mLock->lock ();
    char stopped = mStopSignal;
    mLock->unlock ();
    int badMessageReceived=0;
    while (!stopped && badMessageReceived<3 && connectionAccepted)
    {
        
        // read a message
        correctMessageReceived = false;
        
        
        
        // read up to the first occurrence of "Body:"
        char *readCharBuffer = readStreamUpToTag (mInputStream,
                                                  "Body:", 5000);
        
        if (readCharBuffer != NULL)
        {
	    const char *posBody=strstr("Body:",readCharBuffer);
	    int lenHeader;
	    if(posBody)
		lenHeader = posBody-readCharBuffer+5;
	    else
		lenHeader = strlen(readCharBuffer);
	    TotBytesReceived += lenHeader;
            mLimiter->bytesTransmitted (lenHeader);
            // buffer ends with "Body:" plus terminating character
            
            AppLog::detail (mLoggerName, "Got header");
            AppLog::trace (mLoggerName, readCharBuffer);
            
            // tokenize it
            SimpleVector < char *>*tokenVector =
                    tokenizeString (readCharBuffer);
            
            char *messageID = NULL;
            char *fromAddress = NULL;
            char *toAddress = NULL;
            char *flags = NULL;
            int utilityCounter = 0;
            int payloadLength = -1;
            char *dataPayload = NULL;
            
            int numTokens = tokenVector->size ();
            
            int i;
            for (i = 0; i < numTokens - 1; i++)
            {
                char *currentToken = *(tokenVector->getElement (i));
                char *nextToken = *(tokenVector->getElement (i + 1));
                
                if (strcmp (currentToken, "UniqueID:") == 0)
                {
                    messageID = stringDuplicate (nextToken);
                }
                else if (strcmp (currentToken, "From:") == 0)
                {
                    fromAddress = stringDuplicate (nextToken);
                }
                else if (strcmp (currentToken, "To:") == 0)
                {
                    toAddress = stringDuplicate (nextToken);
                }
                else if (strcmp (currentToken, "Flags:") == 0)
                {
                    flags = stringDuplicate (nextToken);
                }
                else if (strcmp (currentToken, "UtilityCounter:") == 0)
                {
                    sscanf (nextToken, "%d", &utilityCounter);
                }
                else if (strcmp (currentToken, "Length:") == 0)
                {
                    sscanf (nextToken, "%d", &payloadLength);
                }
            }
            
            // destroy vector
            for (i = 0; i < numTokens; i++)
            {
                delete[] * (tokenVector->getElement (i));
            }
            delete tokenVector;
            
            
            if (messageID != NULL &&
                fromAddress != NULL &&
                toAddress != NULL && flags != NULL && payloadLength > 0)
            {
                
                // all header items read correctly
                
                // make sure payload not too big
                if (payloadLength <= 32768)
                {
                    
                    dataPayload = new char[payloadLength + 1];
                    
                    int numRead =
                            mInputStream->read ((unsigned char *) dataPayload,
                                                payloadLength);
                    
		    TotBytesReceived += numRead;
                    // terminate payload string
                    if (numRead > 0 && numRead <= payloadLength)
                    {
                        dataPayload[numRead] = '\0';
                    }
                    else
                    {
                        dataPayload[payloadLength] = '\0';
                    }
                    
                    if (numRead == payloadLength)
                    {
                        // we've already traced the header
                        AppLog::trace (mLoggerName, dataPayload);
                        
                        correctMessageReceived = true;
			TotMessagesReceived ++;
                        if (strcmp (toAddress, "ALL") == 0) TotMessagesToAll++;
                        // message formatted correctly,
                        // so process it
                        
                        // obey the limit
                        // we will block here if message rate is too high
                        mLimiter->bytesTransmitted (numRead);
                        
                        
                        
                        
                        // process the message
                        //printf( "Registering received ID %s\n", messageID );
                        char fresh =
                                mMessageIDTracker->checkIfIDFresh (messageID);
                        
                        if (fresh)
                        {
                            AppLog::detail (mLoggerName, "Message fresh.");
                        }
                        else
                        {
                            AppLog::detail (mLoggerName, "Message stale.");
                        }
                        
                        // only do work of processing flags for fresh
                        // messages
                        
                        // we might drop a fresh message based on flags
                        
                        char ignoreUC = false;
                        char dropMessage = false;
                        
                        
                        if (fresh)
                        {
                            char *newFlags = processFlags (messageID,
                                                           fromAddress,
                                                           flags,
                                                           &ignoreUC,
                                                           &dropMessage,
                                                           mLoggerName);
                            
                            delete[]flags;
                            flags = newFlags;
                            
                            if (dropMessage)
                            {
                                AppLog::detail (mLoggerName,
                                                "Dropping message based on flags.");
                            }
                        }
                        
                        
                        // ignore messages that are not fresh
                        // or that should be dropped according to flags.
                        if (fresh && !dropMessage)
                        {
                            
                            
                            if (strstr (flags, "FRESH_ROUTE") != NULL)
                            {
                                // clear the routing information in both
                                // directions
                                mOutboundChannelManager->
                                        clearRoutingInformation (fromAddress);
                                mOutboundChannelManager->
                                        clearRoutingInformation (toAddress);
                            }
                            
                            // add new back-routing information
                            mOutboundChannelManager->
                                    addRoutingInformation (fromAddress,
                                                           mOutboundChannel);
                            
                            int generatedUtility = 0;
                            char receivedLocally;
                            
                            if (strstr (flags, "DROP_TTL") != NULL)
                            {
                                // don't locally-process DROP_TTL messages
                                receivedLocally = false;
                            }
                            else
                            {
                                receivedLocally =
                                        mReceiver->messageReceived (fromAddress,
                                                                    toAddress,
                                                                    dataPayload,
                                                                    &generatedUtility);
                            }
                            
                            if (receivedLocally)
                            {
                                AppLog::detail (mLoggerName,
                                                "Message consumed locally.");
                            }
                            
                            
                            // check this even if ignoring UCs
                            if (utilityCounter < -mMaxUtilityCounter)
                            {
                                // correct negative utility counters
                                utilityCounter = -mMaxUtilityCounter +
                                                 mRandSource->getRandomBoundedInt (0, 6);
                            }
                            
                            // we might generate utility for any message
                            // type, either routed or broadcast (ALL),
                            // that we do not consume locally
                            
                            if (!ignoreUC)
                            {
                                // add in our weighted, generated utility
                                utilityCounter +=
                                        mUtilityAlpha * generatedUtility;
                            }
                            
                            
                            // if we didn't consume message locally
                            // or if message is a broadcast
                            if (!receivedLocally ||
                                strcmp (toAddress, "ALL") == 0)
                            {
                                
                                
                                if (strcmp (toAddress, "ALL") == 0)
                                {
                                    
                                    if (!ignoreUC)
                                    {
                                        // for ALL messages, also add in
                                        // the weighted (beta) branching
                                        // factor at this node and the
                                        // (gamma) constant factor
                                        
                                        int numNeighbors =
                                                mOutboundChannelManager->
                                                getConnectionCount ();
                                        
                                        // we won't send to the neighbor that
                                        // sent the message to us
                                        int branchFactor = numNeighbors - 1;
                                        int deltaUtility =
                                                mUtilityBeta * branchFactor +
                                                mUtilityGamma +
                                                mRandSource->getRandomBoundedInt (-6,
                                                                                  0);
                                        if (deltaUtility < 1)
                                            deltaUtility = 1;
                                        
                                        utilityCounter += deltaUtility;
                                    }
                                }
                                
                                if (!ignoreUC &&
                                    utilityCounter > mMaxUtilityCounter)
                                {
                                    
                                    // we have pushed the UC over the top
                                    
                                    // switch the message into DROP_CHAIN
                                    // mode to start the drop tail
                                    // the OutboundChannelManager will handle
                                    // the chaining and the side DROP_TTL
                                    // trees when it sees the DROP_CHAIN flag
                                    
                                    char *tempFlags = muteAddFlag (flags,
                                                                   "DROP_CHAIN");
                                    delete[]flags;
                                    flags = tempFlags;
                                    
                                    AppLog::detail (mLoggerName,
                                                    "Message switched into DROP_CHAIN "
                                                    " mode because its"
                                                    " utility is too high.");
                                    
                                    // if we switch a message into DROP_CHAIN
                                    // mode, we should pass it to the
                                    // OutboundChannelManager even if
                                    // the number of neighbors that we send
                                    // DROP_CHAIN messages to is 0.
                                    // In these cases, we will be sending
                                    // DROP_TTL messages to all neighbors.
                                    // We must do this because we have
                                    // already processed the message above
                                    // before we decide to change it into
                                    // DROP_CHAIN mode.  If we simply
                                    // drop it at this point, our neighbors
                                    // could tell that we didn't send out
                                    // any DROP_TTL message (and therefore
                                    // that we weren't passing the DROP_CHAIN
                                    // message on to any neighbors).  They
                                    // could be sure the results they see
                                    // are coming from us.
                                }
                                
                                if (!dropMessage)
                                {
                                    // route it
                                    // this manager will pay attention
                                    // to flags when routing.
                                    mOutboundChannelManager->
                                            routeMessage (messageID, fromAddress,
                                                          toAddress, flags,
                                                          utilityCounter, dataPayload,
                                                          mOutboundChannel);
                                    
                                    AppLog::detail (mLoggerName,
                                                    "Message routed onward.");
                                }
                            }
                        }
                    }
                    else
                    {
                        AppLog::error (mLoggerName,
                                       "Failed to read message data payload");
                    }
                }
                else
                {
                    AppLog::error (mLoggerName,
                                   "Failed to read message payload too long");
                }
            }
            else
            {
              if (messageID == NULL )
                AppLog::error (mLoggerName, "No Message ID");
              else if ( fromAddress == NULL )
                AppLog::error (mLoggerName, "No From Address");
              else if ( toAddress == NULL )
                AppLog::error (mLoggerName, "No To Address");
	      else if ( flags == NULL )
                AppLog::error (mLoggerName, "No Flags");
	      else
                AppLog::error (mLoggerName, "Payload length negative");
            }
            
            
            
            // clean up, whether correct message was received or not
            if (messageID != NULL)
            {
                delete[]messageID;
            }
            if (fromAddress != NULL)
            {
                delete[]fromAddress;
            }
            if (toAddress != NULL)
            {
                delete[]toAddress;
            }
            if (flags != NULL)
            {
                delete[]flags;
            }
            if (dataPayload != NULL)
            {
                delete[]dataPayload;
            }
            
            delete[]readCharBuffer;
        }
        
        
        if (correctMessageReceived)
        {
//            AppLog::detail (mLoggerName, "Correct message received");
            badMessageReceived=0;
        }
        else
        {
            AppLog::warning (mLoggerName, "Bad message received");
            badMessageReceived++;
        }
        
        mLock->lock ();
        stopped = mStopSignal;
        mLock->unlock ();
        
    }
    
    
    // TODO
    // however we got here, we should perhaps remove the host from the catcher
    // (rejected our connection, broke the connection, sent a bad message,
    //  dropped too many messages)
    // or immediately retry connect if it was a good host....
    // HostAddress *remoteHost = new HostAddress (stringDuplicate (mRemoteAddress),
    //                                           mRemotePort);
    // mHostCatcher->noteHostBad (remoteHost);
    // delete remoteHost;
    
    
    // let channel manager know that channel has been broken
    mOutboundChannelManager->channelBroken (mOutboundChannel);
    
    // cast to true type
    ConnectionMaintainer *maintainer =
            (ConnectionMaintainer *) mConnectionMaintainer;
    maintainer->connectionBroken ();
    
    // destroy the socket using the manager
    SocketManager::destroySocket (mSocket);
    
    
    mLock->lock ();
    mFinished = true;
    mLock->unlock ();
}
Пример #7
0
PRIntn prmain(PRIntn argc, char **argv)
{
  void                  *stackBasePtr;
  gpsee_interpreter_t   *jsi;                           /* Handle describing a GPSEE/JavaScript Interpreter */
  gpsee_realm_t         *realm;                         /* Interpreter's primordial realm */
  JSContext             *cx;                            /* A context in realm */
  const char		*scriptCode = NULL;		/* String with JavaScript program in it */
  const char		*scriptFilename = NULL;		/* Filename with JavaScript program in it */
  char * const		*script_argv;			/* Becomes arguments array in JS program */
  char * const  	*script_environ = NULL;		/* Environment to pass to script */
  char			*flags = malloc(8);		/* Flags found on command line */
  int			noRunScript = 0;		/* !0 = compile but do not run */

  int			fiArg = 0;
  int			skipSheBang = 0;
  int			exitCode;
  int			verbosity;	                /* Verbosity to use before flags are processed */
#ifdef GPSEE_DEBUGGER
  JSDContext            *jsdc;          
#endif

#if defined(__SURELYNX__)
  permanent_pool = apr_initRuntime();
#endif
  gpsee_setVerbosity(isatty(STDERR_FILENO) ? GSR_PREPROGRAM_TTY_VERBOSITY : GSR_PREPROGRAM_NOTTY_VERBOSITY);
  gpsee_openlog(gpsee_basename(argv[0]));

  /* Print usage and exit if no arguments were given */
  if (argc < 2)
    usage(argv[0]);

  flags[0] = (char)0;

  fiArg = findFileToInterpret(argc, argv);

  if (fiArg == 0)	/* Not a script file interpreter (shebang) */
  {
    int 	c;
    char	*flag_p = flags;

    while ((c = getopt(argc, argv, whenSureLynx("D:r:","") "v:c:hHnf:F:aCRxSUWdeJz")) != -1)
    {
      switch(c)
      {
#if defined(__SURELYNX__)
	case 'D':
	  redirect_output(permanent_pool, optarg);
	  break;
	case 'r': /* handled by cfg_openfile() */
	  break;
#endif

	case 'c':
	  scriptCode = optarg;
	  break;

	case 'h':
	  usage(argv[0]);
	  break;

	case 'H':
	  moreHelp(argv[0]);
	  break;

	case 'n':
	  noRunScript = 1;
	  break;

	case 'F':
	  skipSheBang = 1;
	case 'f':
	  scriptFilename = optarg;
	  break;

	case 'a':
	case 'C':
	case 'd':
	case 'e':
	case 'J':
	case 'S':
	case 'R':
	case 'U':
	case 'W':
	case 'x':
	case 'z':
	{
	  char *flags_storage = realloc(flags, (flag_p - flags) + 1 + 1);
	    
	  if (flags_storage != flags)
	  {
	    flag_p = (flag_p - flags) + flags_storage;
	    flags = flags_storage;
	  }

	  *flag_p++ = c;
	  *flag_p = '\0';
	}
	break;

	case '?':
	{
	  char buf[32];

	  snprintf(buf, sizeof(buf), "Invalid option: %c\n", optopt);
	  fatal(buf);
	}

	case ':':
	{
	  char buf[32];

	  snprintf(buf, sizeof(buf), "Missing parameter to option '%c'\n", optopt);
	  fatal(buf);
	}

      }
    } /* getopt wend */

    /* Create the script's argument vector with the script name as arguments[0] */
    {
      char **nc_script_argv = malloc(sizeof(argv[0]) * (2 + (argc - optind)));
      nc_script_argv[0] = (char *)scriptFilename;
      memcpy(nc_script_argv + 1, argv + optind, sizeof(argv[0]) * ((1 + argc) - optind));
      script_argv = nc_script_argv;
    }

    *flag_p = (char)0;
  }
  else 
  {
    scriptFilename = argv[fiArg];

    if (fiArg == 2)
    {
      if (argv[1][0] != '-')
	fatal("Invalid syntax for file-interpreter flags! (Must begin with '-')");

      flags = realloc(flags, strlen(argv[1]) + 1);
      strcpy(flags, argv[1] + 1);
    }

    /* This is a file interpreter; script_argv is correct at offset fiArg. */
    script_argv = argv + fiArg;
  }

  if (strchr(flags, 'a'))
  {
#if defined(GPSEE_DARWIN_SYSTEM)
    script_environ = (char * const *)_NSGetEnviron();
#else
    extern char **environ;
    script_environ = (char * const *)environ;
#endif
  }

  loadRuntimeConfig(scriptFilename, flags, argc, argv);
  if (strchr(flags, 'U') || (cfg_bool_value(cfg, "gpsee_force_no_utf8_c_strings") == cfg_true) || getenv("GPSEE_NO_UTF8_C_STRINGS"))
  {
    JS_DestroyRuntime(JS_NewRuntime(1024));
    putenv((char *)"GPSEE_NO_UTF8_C_STRINGS=1");
  }

  jsi = gpsee_createInterpreter();
  realm = jsi->realm;
  cx = jsi->cx;
#if defined(GPSEE_DEBUGGER)
  jsdc = gpsee_initDebugger(cx, realm, DEBUGGER_JS);
#endif

  gpsee_setThreadStackLimit(cx, &stackBasePtr, strtol(cfg_default_value(cfg, "gpsee_thread_stack_limit_bytes", "0x80000"), NULL, 0));

  processFlags(cx, flags, &verbosity);
  free(flags);

#if defined(__SURELYNX__)
  sl_set_debugLevel(gpsee_verbosity(0));
  /* enableTerminalLogs(permanent_pool, gpsee_verbosity(0) > 0, NULL); */
#else
  if (verbosity < GSR_MIN_TTY_VERBOSITY && isatty(STDERR_FILENO))
    verbosity = GSR_MIN_TTY_VERBOSITY;
#endif

  if (gpsee_verbosity(0) < verbosity)
    gpsee_setVerbosity(verbosity);

  /* Run JavaScript specified with -c */
  if (scriptCode) 
  {
    jsval v;

    if (JS_EvaluateScript(cx, realm->globalObject, scriptCode, strlen(scriptCode), "command_line", 1, &v) == JS_FALSE)
    {
      v = JSVAL_NULL;
      goto out;
    }
    v = JSVAL_NULL;
  }

  if ((argv[0][0] == '/') 
#if defined(SYSTEM_GSR)
      && (strcmp(argv[0], SYSTEM_GSR) != 0) 
#endif
      && cfg_bool_value(cfg, "no_gsr_preload_script") != cfg_true)
  {
    char preloadScriptFilename[FILENAME_MAX];
    char mydir[FILENAME_MAX];
    int i;

    jsi->grt->exitType = et_unknown;

    i = snprintf(preloadScriptFilename, sizeof(preloadScriptFilename), "%s/.%s_preload", gpsee_dirname(argv[0], mydir, sizeof(mydir)), 
		 gpsee_basename(argv[0]));
    if ((i == 0) || (i == (sizeof(preloadScriptFilename) -1)))
      gpsee_log(cx, GLOG_EMERG, PRODUCT_SHORTNAME ": Unable to create preload script filename!");
    else
      errno = 0;

    if (access(preloadScriptFilename, F_OK) == 0)
    {
      jsval 		v;
      JSScript		*script;
      JSObject		*scrobj;

      if (!gpsee_compileScript(cx, preloadScriptFilename, NULL, NULL, &script, realm->globalObject, &scrobj))
      {
	jsi->grt->exitType = et_compileFailure;
	gpsee_log(cx, GLOG_EMERG, PRODUCT_SHORTNAME ": Unable to compile preload script '%s'", preloadScriptFilename);
	goto out;
      }

      if (!script || !scrobj)
	goto out;

      if (!noRunScript)
      {
        JS_AddNamedObjectRoot(cx, &scrobj, "preload_scrobj");
	jsi->grt->exitType = et_execFailure;
        if (JS_ExecuteScript(cx, realm->globalObject, script, &v) == JS_TRUE)
	  jsi->grt->exitType = et_finished;
	else
	  jsi->grt->exitType = et_exception;
        JS_RemoveObjectRoot(cx, &scrobj);
        v = JSVAL_NULL;
      }
    }

    if (jsi->grt->exitType & et_errorMask)
      goto out;
  }

  /* Setup for main-script running -- cancel preprogram verbosity and use our own error reporting system in gsr that does not use error reporter */
  gpsee_setVerbosity(verbosity);
  JS_SetOptions(cx, JS_GetOptions(cx) | JSOPTION_DONT_REPORT_UNCAUGHT);

  if (!scriptFilename)
  {
    if (!scriptCode)	/* Command-line options did not include code to run */
      usage(argv[0]);

    if (jsi->grt->exitType == et_unknown)
      jsi->grt->exitType = et_finished;
  }
  else
  {
    FILE 	*scriptFile = openScriptFile(cx, scriptFilename, skipSheBang || (fiArg != 0));

    if (!scriptFile)
    {
      gpsee_log(cx, GLOG_NOTICE, PRODUCT_SHORTNAME ": Unable to open' script '%s'! (%m)", scriptFilename);
      jsi->grt->exitType = et_compileFailure;
      goto out;
    }

    processInlineFlags(cx, scriptFile, &verbosity);
    gpsee_setVerbosity(verbosity);

    /* Just compile and exit? */
    if (noRunScript)
    {
      JSScript        *script;
      JSObject        *scrobj;

      if (!gpsee_compileScript(cx, scriptFilename, scriptFile, NULL, &script, realm->globalObject, &scrobj))
      {
	jsi->grt->exitType = et_exception;
        gpsee_reportUncaughtException(cx, JSVAL_NULL, 
				      (gpsee_verbosity(0) >= GSR_FORCE_STACK_DUMP_VERBOSITY) ||
				      ((gpsee_verbosity(0) >= GPSEE_ERROR_OUTPUT_VERBOSITY) && isatty(STDERR_FILENO)));
      }
      else
      {
	jsi->grt->exitType = et_finished;
      }
    }
    else /* noRunScript is false; run the program */
    {
      jsi->grt->exitType = et_execFailure;

      if (gpsee_runProgramModule(cx, scriptFilename, NULL, scriptFile, script_argv, script_environ) == JS_TRUE)
      {
	jsi->grt->exitType = et_finished;
      }
      else
      {
        int code;

	code = gpsee_getExceptionExitCode(cx);	
        if (code >= 0)	/** e.g. throw 6 */
        {
	  jsi->grt->exitType = et_requested;
          jsi->grt->exitCode = code;
        }
        else
        {
	  if (JS_IsExceptionPending(cx))
	  {
	    jsi->grt->exitType = et_exception;
	    gpsee_reportUncaughtException(cx, JSVAL_NULL, 
					(gpsee_verbosity(0) >= GSR_FORCE_STACK_DUMP_VERBOSITY) ||
					((gpsee_verbosity(0) >= GPSEE_ERROR_OUTPUT_VERBOSITY) && isatty(STDERR_FILENO)));
	  }
        }
      }
    }
    fclose(scriptFile);
    goto out;
  }

  out:
#ifdef GPSEE_DEBUGGER
  gpsee_finiDebugger(jsdc);
#endif

  if (jsi->grt->exitType & et_successMask)
  {
    exitCode = jsi->grt->exitCode;
  }
  else
  {
    const char *reason;

    exitCode = 1;

    switch(jsi->grt->exitType)
    {
      case et_successMask:
      case et_errorMask:
      case et_requested:
      case et_finished:
      case et_dummy:
      default:
	GPSEE_NOT_REACHED("impossible");
	reason = NULL;	/* quell compiler warning below */
	break;	
      case et_execFailure:
	reason = "execFailure - probable native module error, returning JS_FALSE without setting exception";
	break;
      case et_compileFailure:
	reason = "script could not be compiled";
        break;
      case et_unknown:
	reason = "unknown - probable native module error, returning JS_FALSE without setting exception";
	break;
      case et_exception:
	reason = NULL;
	break;
    }

    if (reason)
    {
      gpsee_log(cx, GLOG_NOTICE, "Unexpected interpreter shutdown: %s (%m)", reason);
      if (gpsee_verbosity(0) == 0)
      {
          /* not gpsee_ */ fprintf(stderr, "*** Unexpected interpreter shutdown: %s", reason);
        if (errno)
          fprintf(stderr, " (%s)\n", strerror(errno));	
        else
          fputs("\n", stderr);
      }
    }
  }

  gpsee_destroyInterpreter(jsi);
  JS_ShutDown();

  return exitCode;
}
Пример #8
0
void Texture::sendToGPU() 
{ 
	mFlags |= SendToGPU; 
	processFlags(); 
}
Пример #9
0
bool Texture::load( const char *filename, unsigned int flags )
{
	const char *extension = strrchr( filename, '.' );
	if(extension == NULL)
	{
		printf( "Texture::load - \"%s\" is not a valid filename." );
		return false;
	}

	delete mBitmap;
	//delete [] mBytes;
	//mBytes = NULL;

	// check if we need to save the name (not needed on texture resurrect)
	if( mFileName != filename )
	{
		mFileName = new char[strlen( filename )+1];
		strcpy( mFileName, filename );
	}

	// set flags, clean out internally managed bits ... 
	mFlags = (flags & (~_INTERNAL_BITS));

	// set anisotropic filtering only if we've got it ... 
	if(/*doesn't support anisotropic filtering*/ false )
		mFlags = (flags & (~Anisotropic));

	mBitmap = new Bitmap( filename, flags );
	mFlags = mBitmap->flags();
	mWidth = mBitmap->width();
	mHeight = mBitmap->height();
	/*
	extension++;

	bool loaded = false;

	FILE* fp;
	if( (fp = fopen( mFileName, "rb" )) == NULL )
	{
		printf( "Texture::load - could not open \"%s\".", mFileName );
		return false;
	}

	if( strcmp( extension, "png" ) == 0 )
	{
		// load png
		loaded = load_png( fp );
		mFlags |= PNG;
	}
	else if( strcmp( extension, "jpg" ) == 0 )
	{
		// load jpg
		loaded = load_jpg( fp );
		mFlags |= JPG;
	}
	else if( strcmp( extension, "bmp" ) == 0 )
	{
		// load bmp
		loaded = load_bmp( fp );
		mFlags |= BMP;
	}
	else
	{
		printf( "Texture::load - \"%s\" is not a supported texture file.", mFileName );
		fclose( fp );
		return false;
	}

	// allocate alpha channel if requested ...
	if( mFlags & RequestAlpha )
	{
		int dbytes = getPixelBytes();

		// allocate alpha if we don't have one
		if( mFlags & Channels1 || mFlags & Channels3 )
		{
			int new_stride = (dbytes+1);
			unsigned char* tbytes = new unsigned char[mHeight * mWidth * new_stride];
			for(int i=0; i<mHeight*mWidth; i++)
			{
				int d;
				for( d=0; d < dbytes; d++ )
					tbytes[i*new_stride+d] = mBytes[i*dbytes+d];
				tbytes[i*new_stride+d] = 255;
			}
			delete [] mBytes;
			mBytes = tbytes;

			// reset depth
			mFlags &= (~ChannelBits);

			if( dbytes == 1 )
				mFlags |= Channels2;
			else
				mFlags |= Channels4;
		}
		// if we didn't already have an alpha emit an error for an unknown/unsupported bitdepth
		else if(!(mFlags & Channels2 || mFlags & Channels4))
		{
			printf( "Texture::load - cannot allocate alpha channel on a \"%i\" bit texture.", dbytes<<3 );
		}
	}

	fclose( fp );
	*/
	//if( loaded )
	{
		processFlags();

		if( !(mFlags & KeepLocal) )
		{
			delete mBitmap;
			mBitmap = NULL;
		}
	}

//	if( loaded )
		mFlags |= Loaded;

	return true;
}