Esempio n. 1
0
void* __ctBackgroundThreadWriter(void* d)
{
    FILE* serialFile;
    char* fname = getenv("CONTECH_FE_FILE");
    unsigned int wpos = 0;
    unsigned int maxBuffersAlloc = 0, memLimitBufCount = 0;
    size_t totalWritten = 0;
    pct_serial_buffer memLimitQueue = NULL;
    pct_serial_buffer memLimitQueueTail = NULL;
    unsigned long long totalLimitTime = 0, startLimitTime, endLimitTime;
    int mpiRank = __ctGetMPIRank();
    int mpiPresent = __ctIsMPIPresent();
    // TODO: Create MPI event
    // TODO: Modify filename with MPI rank
    // TODO: Only do the above when MPI is present
    
    if (fname == NULL)
    {
        if (mpiPresent != 0)
        {
            char* fnameMPI = strdup("/tmp/contech_fe      ");
            fnameMPI[15] = '.';
            snprintf(fnameMPI + 16, 5, "%d", mpiRank);
            serialFile = fopen(fnameMPI, "wb");
            free(fnameMPI);
        }
        else
        {
            serialFile = fopen("/tmp/contech_fe", "wb");
        }
    }
    else
    {
        serialFile = fopen(fname, "wb");
    }

    if (serialFile == NULL)
    {
        fprintf(stderr, "Failure to open front-end stream for writing.\n");
        if (fname == NULL) { fprintf(stderr, "\tCONTECH_FE_FILE unspecified\n");}
        else {fprintf(stderr, "\tAttempted on %s\n", fname);}
        exit(-1);
    }
    
    {
        unsigned int id = 0;
        ct_event_id ty = ct_event_version;
        unsigned int version = CONTECH_EVENT_VERSION;
        uint8_t* bb_info = _binary_contech_bin_start;
        
        fwrite(&id, sizeof(unsigned int), 1, serialFile); 
        fwrite(&ty, sizeof(unsigned int), 1, serialFile);
        fwrite(&version, sizeof(unsigned int), 1, serialFile);
        fwrite(bb_info, sizeof(unsigned int), 1, serialFile);
        totalWritten += 4 * sizeof(unsigned int);
        
        {
            size_t tl, wl;
            unsigned int buf[2];
            buf[0] = ct_event_rank;
            buf[1] = mpiRank;
            
            tl = 0;
            do
            {
                wl = fwrite(&buf + tl, sizeof(unsigned int), 2 - tl, serialFile);
                //if (wl > 0)
                // wl is 0 on error, so it is safe to still add
                tl += wl;
            } while  (tl < 2);
            
            totalWritten += 2 * sizeof(unsigned int);
        }
        
        bb_info += 4; // skip the basic block count
        while (bb_info != _binary_contech_bin_end)
        {
            // id, len, memop_0, ... memop_len-1
            // Contech pass lays out the events in appropriate format
            size_t tl = fwrite(bb_info, sizeof(char), _binary_contech_bin_end - bb_info, serialFile);
            bb_info += tl;
            totalWritten += tl;
        }
    }
    
    // Main loop
    //   Write queued buffer to disk until program terminates
    pthread_mutex_lock(&__ctQueueBufferLock);
    do {
        struct timespec ts;
        clock_gettime(CLOCK_REALTIME, &ts);
        ts.tv_sec += 30;
        int condRetVal = 0;
        
        // Check for queued buffer, i.e. is the program generating events
        while (__ctQueuedBuffers == NULL && condRetVal == 0)
        {
            condRetVal = pthread_cond_timedwait(&__ctQueueSignal, &__ctQueueBufferLock, &ts);
        }
        if (condRetVal == 0)
        {
            pthread_mutex_unlock(&__ctQueueBufferLock);
        }
    
        // The thread writer will likely sit in this loop except when the memory limit is triggered
        while (__ctQueuedBuffers != NULL)
        {
            // Write buffer to file
            size_t tl = 0;
            size_t wl = 0;
            pct_serial_buffer qb = __ctQueuedBuffers;
            
            // First craft the marker event that indicates a new buffer in the event list
            //   This event tells eventLib which contech created the next set of bytes
            {
                unsigned int buf[3];
                buf[0] = ct_event_buffer;
                buf[1] = __ctQueuedBuffers->id;
                buf[2] = __ctQueuedBuffers->basePos;
                //fprintf(stderr, "%d, %llx, %d\n", __ctQueuedBuffers->id, totalWritten, __ctQueuedBuffers->pos);
                do
                {
                    wl = fwrite(&buf + tl, sizeof(unsigned int), 3 - tl, serialFile);
                    //if (wl > 0)
                    // wl is 0 on error, so it is safe to still add
                    tl += wl;
                } while  (tl < 3);

                totalWritten += 3 * sizeof(unsigned int);
                
            }
            
            // TODO: fully integrate into debug framework
            #if DEBUG
            if (totalWritten < 256)
            {
                int i;
                for (i = 0; i < 256; i ++)
                {
                    fprintf(stderr, "%x ", __ctQueuedBuffers->data[i]);
                }
            }
            #endif
            
            // Now write the bytes out of the buffer, until all have been written
            tl = 0;
            wl = 0;
            if (qb->pos > SERIAL_BUFFER_SIZE)
            {
                fprintf(stderr, "Illegal buffer size - %d\n", qb->pos);
            }
            while (tl < __ctQueuedBuffers->pos)
            {
                wl = fwrite(__ctQueuedBuffers->data + tl, 
                            sizeof(char), 
                            (__ctQueuedBuffers->pos) - tl, 
                            serialFile);
                // if (wl < 0)
                // {
                //     continue;
                // }
                tl += wl;
                if (qb != __ctQueuedBuffers)
                {
                    fprintf(stderr, "Tampering with __ctQueuedBuffers!\n");
                }
            }
            if (tl != __ctQueuedBuffers->pos)
            {
                fprintf(stderr, "Write quantity(%lu) is not bytes in buffer(%d)\n", tl, __ctQueuedBuffers->pos);
            }
            totalWritten += tl;
            
            // "Free" buffer
            // First move the queue pointer, as we implicitly held the first element
            // Then switch locks and put this processed buffer onto the free list
            pthread_mutex_lock(&__ctQueueBufferLock);
            {
                pct_serial_buffer t = __ctQueuedBuffers;
                __ctQueuedBuffers = __ctQueuedBuffers->next;
                if (__ctQueuedBuffers == NULL) __ctQueuedBufferTail = NULL;
                pthread_mutex_unlock(&__ctQueueBufferLock);
                
                if (t->length < SERIAL_BUFFER_SIZE)
                {
                    free(t);
                    // After the unlock is end of while loop, 
                    //  so as the buffer was free() rather than put on the list
                    //  we continue
                    continue;
                }
                //continue; // HACK: LEAK!
                
                // Switching locks, "t" is now only held locally
                pthread_mutex_lock(&__ctFreeBufferLock);
#ifdef DEBUG
                pthread_mutex_lock(&__ctPrintLock);
                fprintf(stderr, "f,%p,%d\n", t, t->id);
                fflush(stderr);
                pthread_mutex_unlock(&__ctPrintLock);
#endif
                
                if (__ctCurrentBuffers == __ctMaxBuffers)
                {
                    if (__ctQueuedBuffers == NULL)
                    {
                        // memlimit end
                        struct timeb tp;
                        ftime(&tp);
                        endLimitTime = tp.time*1000 + tp.millitm;
                        totalLimitTime += (endLimitTime - startLimitTime);
                        memLimitQueueTail->next = t;
                        t->next = __ctFreeBuffers;
                        __ctFreeBuffers = memLimitQueue;
                        maxBuffersAlloc = __ctCurrentBuffers;
                        
                        // N.B. It is possible that thread X is holding a lock L
                        //   and then attempts to queue and allocate a new buffer.
                        //   And that thread Y blocks on lock L, whereby its buffer
                        //   will not be in the queue and therefore the count should
                        //   be greater than 0.
                        __ctCurrentBuffers = __ctMaxBuffers - (memLimitBufCount + 1);
                        memLimitQueue = NULL;
                        memLimitQueueTail = NULL;
                        pthread_cond_broadcast(&__ctFreeSignal);
                    }
                    else
                    {
                        if (memLimitQueueTail == NULL)
                        {
                            memLimitBufCount = 1;
                            memLimitQueue = t;
                            memLimitQueueTail = t;
                            t->next = NULL;
                            // memlimit start
                            struct timeb tp;
                            ftime(&tp);
                            startLimitTime = tp.time*1000 + tp.millitm;
                        }
                        else
                        {
                            memLimitBufCount ++;
                            memLimitQueueTail->next = t;
                            t->next = NULL;
                            memLimitQueueTail = t;
                        }
                    }
                }
                else
                {
                    t->next = __ctFreeBuffers;
                    __ctFreeBuffers = t;
                    if (__ctCurrentBuffers > maxBuffersAlloc)
                    {
                        maxBuffersAlloc = __ctCurrentBuffers;
                    }
                    assert(__ctCurrentBuffers > 0);
                    __ctCurrentBuffers --;
#if DEBUG
                    if (__ctCurrentBuffers < 2)
                    {
                        printf("%p\n", &t->data);
                    }
#endif
                }
            }
            pthread_mutex_unlock(&__ctFreeBufferLock);
        }
        
        // Exit condition is # of threads exited = # of threads
        // N.B. Main is part of this count
        pthread_mutex_lock(&__ctQueueBufferLock);
        if (__ctThreadExitNumber == __ctThreadGlobalNumber && 
            __ctQueuedBuffers == NULL) 
        { 
            // destroy mutex, cond variable
            // TODO: free freedBuffers
            {
                struct timeb tp;
                ftime(&tp);
                printf("CT_COMP: %d.%03d\n", (unsigned int)tp.time, tp.millitm);
                printf("CT_LIMIT: %llu.%03llu\n", totalLimitTime / 1000, totalLimitTime % 1000);
            }
            printf("Total Contexts: %u\n", __ctThreadGlobalNumber);
            printf("Total Uncomp Written: %ld\n", totalWritten);
            printf("Max Buffers Alloc: %u of %lu\n", maxBuffersAlloc, sizeof(ct_serial_buffer_sized));
            {
                struct rusage use;
                if (0 == getrusage(RUSAGE_SELF, &use))
                {
                    printf("Max RSS: %ld\n", use.ru_maxrss);
                }
            }
            printQueueStats();
            fflush(stdout);
            
            fflush(serialFile);
            fclose(serialFile);
            
            pthread_mutex_unlock(&__ctQueueBufferLock);
            pthread_exit(NULL);            
        }
    } while (1);
}
Esempio n. 2
0
void *emitter(void *arg) {
  int rc;
  struct emitter_config *config = arg;
  insist(config->zmq != NULL, "zmq is NULL");
  insist(config->zmq_endpoint != NULL, "zmq_endpoint is NULL");
  insist(config->ssl_ca_path != NULL, "ssl_ca_path is NULL");
  insist(config->window_size > 0, "window_size (%d) must be positive",
         (int)config->window_size);
  insist(config->host != NULL, "host is NULL");
  insist(config->port > 0, "port (%hd) must be positive", config->port);

  void *socket = zmq_socket(config->zmq, ZMQ_PULL);
  insist(socket != NULL, "zmq_socket() failed: %s", strerror(errno));
  int64_t hwm = 100;
  //zmq_setsockopt(socket, ZMQ_HWM, &hwm, sizeof(hwm));
  zmq_compat_set_recvhwm(socket, hwm);
  rc = zmq_bind(socket, config->zmq_endpoint);
  insist(rc != -1, "zmq_bind(%s) failed: %s", config->zmq_endpoint,
         zmq_strerror(errno));

  struct timespec start;
  clock_gettime(CLOCK_MONOTONIC, &start);
  //long count = 0;

  struct backoff sleeper;
  backoff_init(&sleeper, &MIN_SLEEP, &MAX_SLEEP);

  struct lumberjack *lumberjack;
  lumberjack = lumberjack_new(config->host, config->port, config->window_size);
  insist(lumberjack != NULL, "lumberjack_new failed");
  lumberjack->ring_size = config->window_size;

  if (config->ssl_ca_path != NULL) {
    rc = lumberjack_set_ssl_ca(lumberjack, config->ssl_ca_path);
    insist(rc == 0, "lumberjack_set_ssl_ca failed, is '%s' a valid ssl cert?",
           config->ssl_ca_path);
  }

  long count = 0;
  long bytes = 0;

  zmq_pollitem_t items[1];

  items[0].socket = socket;
  items[0].events = ZMQ_POLLIN;

  int can_flush = 0;
  for (;;) {
    /* Receive an event from a harvester and put it in the queue */
    zmq_msg_t message;

    rc = zmq_msg_init(&message);
    insist(rc == 0, "zmq_msg_init failed");
    rc = zmq_poll(items, 1, 1000000 /* microseconds */);

    if (rc == 0) {
      /* poll timeout. We're idle, so let's flush and back-off. */
      if (can_flush) {
        /* only flush if there's something to flush... */
        flog(stdout, "flushing since nothing came in over zmq");
        /* We flush here to keep slow feeders closer to real-time */
        rc = lumberjack_flush(lumberjack);
        can_flush = 0;
        if (rc != 0) {
          /* write failure, reconnect (which will resend) and such */
          lumberjack_disconnect(lumberjack);
          lumberjack_ensure_connected(lumberjack);
        }
      }
      backoff(&sleeper);

      /* Restart the loop - checking to see if there's any messages */
      continue;
    } 

    /* poll successful, read a message */
    //rc = zmq_recv(socket, &message, 0);
    rc = zmq_compat_recvmsg(socket, &message, 0);
    insist(rc == 0 /*|| errno == EAGAIN */,
           "zmq_recv(%s) failed (returned %d): %s",
           config->zmq_endpoint, rc, zmq_strerror(errno));

    /* Clear the backoff timer since we received a message successfully */
    backoff_clear(&sleeper);

    /* Write the data over lumberjack. This will handle any
     * connection/reconnection/ack issues */
    lumberjack_send_data(lumberjack, zmq_msg_data(&message),
                         zmq_msg_size(&message));
    /* Since we sent data, let it be known that we can flush if idle */
    can_flush = 1;
    /* Stats for debugging */
    count++;
    bytes += zmq_msg_size(&message);

    zmq_msg_close(&message);

    if (count == 10000) {
      struct timespec now;
      clock_gettime(CLOCK_MONOTONIC, &now);
      double s = (start.tv_sec + 0.0) + (start.tv_nsec / 1000000000.0);
      double n = (now.tv_sec + 0.0) + (now.tv_nsec / 1000000000.0);
      flog(stdout, "Rate: %f (bytes: %f)\n", (count + 0.0) / (n - s), (bytes + 0.0) / (n - s));
      struct rusage rusage;
      rc = getrusage(RUSAGE_SELF, &rusage);
      insist(rc == 0, "getrusage failed: %s\n", strerror(errno));
      flog(stdout, "cpu user/system: %d.%06d / %d.%06d\n",
           (int)rusage.ru_utime.tv_sec, (int)rusage.ru_utime.tv_usec,
           (int)rusage.ru_stime.tv_sec, (int)rusage.ru_stime.tv_usec);
      clock_gettime(CLOCK_MONOTONIC, &start);
      bytes = 0;
      count = 0;
    }
  } /* forever */
} /* emitter */
Esempio n. 3
0
long long get_user_time()
{
	struct rusage rusage = { };
	getrusage(RUSAGE_SELF, &rusage);
	return rusage.ru_utime.tv_sec * 1000000 + rusage.ru_utime.tv_usec;
}
Esempio n. 4
0
int main(int argc, char* argv[])
{
  char exePath[MAXPATHLEN];

#ifdef MOZ_WIDGET_GONK
  // The first call of ProcessState::self() (per process) will register into
  // binder driver by current thread info, so the main thread is a best one to
  // do registration because it never leaves.
  android::sp<android::ProcessState> proc(android::ProcessState::self());
#endif

  nsresult rv = mozilla::BinaryPath::Get(argv[0], exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.\n");
    return 255;
  }

  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
  if (!lastSlash || ((lastSlash - exePath) + sizeof(XPCOM_DLL) + 1 > MAXPATHLEN))
    return 255;

  strcpy(++lastSlash, XPCOM_DLL);

#if defined(XP_UNIX)
  // If the b2g app is launched from adb shell, then the shell will wind
  // up being the process group controller. This means that we can't send
  // signals to the process group (useful for profiling).
  // We ignore the return value since setsid() fails if we're already the
  // process group controller (the normal situation).
  (void)setsid();
#endif

  int gotCounters;
#if defined(XP_UNIX)
  struct rusage initialRUsage;
  gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
#elif defined(XP_WIN)
  IO_COUNTERS ioCounters;
  gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
#endif

  // We do this because of data in bug 771745
  XPCOMGlueEnablePreload();

  rv = XPCOMGlueStartup(exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XPCOM.\n");
    return 255;
  }
  // Reset exePath so that it is the directory name and not the xpcom dll name
  *lastSlash = 0;

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XRE functions.\n");
    return 255;
  }

#ifdef XRE_HAS_DLL_BLOCKLIST
  XRE_SetupDllBlocklist();
#endif

  if (gotCounters) {
#if defined(XP_WIN)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_OPS,
                            int(ioCounters.ReadOperationCount));
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_TRANSFER,
                            int(ioCounters.ReadTransferCount / 1024));
    IO_COUNTERS newIoCounters;
    if (GetProcessIoCounters(GetCurrentProcess(), &newIoCounters)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_OPS,
                              int(newIoCounters.ReadOperationCount - ioCounters.ReadOperationCount));
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_TRANSFER,
                              int((newIoCounters.ReadTransferCount - ioCounters.ReadTransferCount) / 1024));
    }
#elif defined(XP_UNIX)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_HARD_FAULTS,
                            int(initialRUsage.ru_majflt));
    struct rusage newRUsage;
    if (!getrusage(RUSAGE_SELF, &newRUsage)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_HARD_FAULTS,
                              int(newRUsage.ru_majflt - initialRUsage.ru_majflt));
    }
#endif
  }

  int result;
  {
    ScopedLogging log;
    result = do_main(argc, argv);
  }

  XPCOMGlueShutdown();
  return result;
}
Esempio n. 5
0
void process_data(FILE *input_file) {
    // !! your code should start here.  the input_file parameter
    // is an already-open file.  you can read data from it using
    // the fgets() C library function.  close it with the fclose()
    // built-in function

    struct rusage usage;


    struct node *list = malloc(sizeof(struct node*));
    list = list->next;

    char filestream[2000000];

    if (input_file == stdin){
	printf("Input a list of numbers \n");
	while(fgets(filestream, 2000000, stdin)!= NULL){
		int slen = strlen(filestream);
		filestream[slen-1] = '\0';

		char *token = strtok(filestream, " \t\n");
    		if(token!=NULL){
			int counter = 0;
			for(int i=0; i<strlen(token); i++){
				if(i==0 && (isdigit(token[i]) || token[i]=='-')){
					counter++;
				}
				else if(isdigit(token[i])){
					counter++;
				}
			}
			if (counter == strlen(token)){
				int num = atoi(token);
				list_append(num, &list);
			}
    		}
    
    		while(token!=NULL){
			token = strtok(NULL," \t\n");
			if (token!=NULL){
				int counter = 0;
				for(int i=0; i<strlen(token); i++){
					if(i==0 && (isdigit(token[i]) || token[i]=='-')){
						counter++;
					}
					else if(isdigit(token[i])){
						counter++;
					}
				}
				if (counter == strlen(token)){
					int num = atoi(token);
				        list_append(num, &list);
				}
			}
    		}
	}
	fflush(stdout);
    }

    else{
        while(fgets(filestream, 2000000, input_file)!=NULL){
		int slen = strlen(filestream);
		filestream[slen-1] = '\0';

		char *token = strtok(filestream," \t\n");
    		if(token!=NULL){
			int counter = 0;
			for(int i=0; i<strlen(token); i++){
				if(i==0 && (isdigit(token[i]) || token[i]=='-')){
					counter++;
				}
				else if(isdigit(token[i])){
					counter++;
				}
			}
			if (counter == strlen(token)){
				int num = atoi(token);
				list_append(num, &list);
			}
                        if (token[0] == '#'){
				token = strtok(NULL, "\n");
			}
    		}
    
    		while(token!=NULL){
			token = strtok(NULL," \t\n");
			if (token!=NULL){
				int counter = 0;
				for(int i=0; i<strlen(token); i++){
					if(i==0 && (isdigit(token[i]) || token[i]=='-')){
						counter++;
					}
					if(isdigit(token[i])){
						counter++;
					}
				}
				if (counter == strlen(token)){
					int num = atoi(token);
				        list_append(num, &list);
				}
				if (token[0] == '#'){
					token = strtok(NULL, "\n");
				}
			}
    		}
	}
	fflush(stdout);
    }
    
    list_sort(&list);
    list_print(list);
    list_clear(list);
  
    getrusage(RUSAGE_SELF, &usage);
    if (getrusage(RUSAGE_SELF, &usage) == -1){
	fprintf(stderr, "Error with getrusage");
        exit(1);
    }
    printf("User time: %ld.%09ld\n", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec);
    printf("System time: %ld.%09ld\n", usage.ru_stime.tv_sec, usage.ru_utime.tv_usec);
   
}
Esempio n. 6
0
/**
 * Returns the amount of CPU time used by the current process,
 * in seconds, or -1.0 if an error occurred.
 */
double getCPUTime( )
{
#if defined(_WIN32)
	/* Windows -------------------------------------------------- */
	FILETIME createTime;
	FILETIME exitTime;
	FILETIME kernelTime;
	FILETIME userTime;
	if ( GetProcessTimes( GetCurrentProcess( ),
		&createTime, &exitTime, &kernelTime, &userTime ) != -1 )
	{
		SYSTEMTIME userSystemTime;
		if ( FileTimeToSystemTime( &userTime, &userSystemTime ) != -1 )
			return (double)userSystemTime.wHour * 3600.0 +
				(double)userSystemTime.wMinute * 60.0 +
				(double)userSystemTime.wSecond +
				(double)userSystemTime.wMilliseconds / 1000.0;
	}

#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
	/* AIX, BSD, Cygwin, HP-UX, Linux, OSX, and Solaris --------- */

#if _POSIX_TIMERS > 0
	/* Prefer high-res POSIX timers, when available. */
	{
		clockid_t id;
		struct timespec ts;
#if _POSIX_CPUTIME > 0
		/* Clock ids vary by OS.  Query the id, if possible. */
		if ( clock_getcpuclockid( 0, &id ) == -1 )
#endif
#if defined(CLOCK_PROCESS_CPUTIME_ID)
			/* Use known clock id for AIX, Linux, or Solaris. */
			id = CLOCK_PROCESS_CPUTIME_ID;
#elif defined(CLOCK_VIRTUAL)
			/* Use known clock id for BSD or HP-UX. */
			id = CLOCK_VIRTUAL;
#else
			id = (clockid_t)-1;
#endif
		if ( id != (clockid_t)-1 && clock_gettime( id, &ts ) != -1 )
			return (double)ts.tv_sec +
				(double)ts.tv_nsec / 1000000000.0;
	}
#endif

#if defined(RUSAGE_SELF)
	{
		struct rusage rusage;
		if ( getrusage( RUSAGE_SELF, &rusage ) != -1 )
			return (double)rusage.ru_utime.tv_sec +
				(double)rusage.ru_utime.tv_usec / 1000000.0;
	}
#endif

#if defined(_SC_CLK_TCK)
	{
		const double ticks = (double)sysconf( _SC_CLK_TCK );
		struct tms tms;
		if ( times( &tms ) != (clock_t)-1 )
			return (double)tms.tms_utime / ticks;
	}
#endif

#if defined(CLOCKS_PER_SEC)
	{
		clock_t cl = clock( );
		if ( cl != (clock_t)-1 )
			return (double)cl / (double)CLOCKS_PER_SEC;
	}
#endif

#endif

	return -1.0;		/* Failed. */
}
Esempio n. 7
0
int main (int	 argc,
	   char *argv[])
# endif

{
   int		column_num;
   long		field_len;
   int		line_num;
   char	       *msg_name;
   int		save_statement_number = 0;

# if (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX))
   		double		end_time;
   		double		start_time;
		/* char		time[20]; */
   		double		total_cpu_time;
   struct	rusage		ru;
# else

# if !defined(_HOST_OS_UNICOS)
   long		end_clock;
# endif
   		float		end_time;
   		float		start_time;
   		float		total_cpu_time;
# endif

# if defined(_HOST_OS_UNICOS) && defined(_DEBUG)
   lowmem_check();
# endif

# if defined(_TARGET32) && defined(_DEBUG)
   setbuf(stdout, NULL);
   setbuf(stderr, NULL);
# endif


# if defined(_HOST_OS_UNICOS)

   /* Lots of start up - ignore first call.  See the comment block that       */
   /* precedes procedure cif_summary_rec in fecif.c for a discussion of the   */
   /* timing methods used by the different platforms.			      */

   SECOND(&start_time);


   /* M_LOWFIT will eventually be in malloc.h. */
   /* When it is remove this definition.       */

# define M_LOWFIT	0107	 /* Use lowest-fit algorithm for allocation. */

   mallopt(M_LOWFIT, 1);

# elif defined(_HOST_OS_MAX)

   /* Use clock() on MPP's (in particular T3E's) because at the time this     */
   /* change was made, neither SECOND() nor SECONDR() worked on T3E's.        */
   /*                                                  LRR  4 Mar 1997        */

   clock();
   start_time = 0;

   /* M_LOWFIT will eventually be in malloc.h. */
   /* When it is remove this definition.       */

# define M_LOWFIT	0107	 /* Use lowest-fit algorithm for allocation. */

   mallopt(M_LOWFIT, 1);

# elif defined(_HOST_OS_SOLARIS)

   /* clock() is only semi-useful on a Sun because it rolls over in just over */
   /* 2147 seconds (about 36 minutes).  So on a Sun, we use clock() and       */
   /* time() both.  If elapsed time <= 2147 seconds, the accounting info will */
   /* show milliseconds (from clock()), else it will show seconds (because    */
   /* that is the accuracy of time()).  This resolution should be good enough */
   /* for a compilation exceeding 36 minutes.                                 */

   start_time = (float) time(NULL);
   clock();

# elif (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX))

   getrusage (RUSAGE_SELF, &ru);
   start_time = (double) ru.ru_utime.tv_sec +
                (double) ru.ru_utime.tv_usec * 1e-6 +
                (double) ru.ru_stime.tv_sec +
                (double) ru.ru_stime.tv_usec * 1e-6;

# else

   start_time = 0;

# endif


   comp_phase = Pass1_Parsing;
   stmt_start_line = 1;			/* Set in case mem problems */

   init_compiler(argc, argv);			/* init and process cmd line */

   if (on_off_flags.preprocess_only) {
      goto PREPROCESS_ONLY_SKIP;
   }

   stmt_start_line = 0;

   while (LA_CH_CLASS != Ch_Class_EOF) {

      comp_phase = Pass1_Parsing;
      num_prog_unit_errors = 0;		/* Accum errs for pgm unit */

      OUTPUT_PASS_HEADER(Syntax_Pass);

      if (save_statement_number != 0) {
         statement_number = save_statement_number;
      }

      parse_prog_unit();

      save_statement_number = statement_number;

      if (LA_CH_CLASS == Ch_Class_EOF) {
         issue_deferred_msgs();
      }

      /* get current field length and save largest value */

      field_len = (long) sbrk(0);

# if defined(_HOST_OS_MAX)
      field_len &= (1 << 32) - 1;
# endif

      if (field_len > max_field_len) {		/* Max set in init_compiler */
	 max_field_len = field_len;		/* Track max usage */
      }

      PRINT_IR_TBL;	/* If -u ir and DEBUG compiler, print ir. */

      OUTPUT_PASS_HEADER(Semantics_Pass);

      semantics_pass_driver();			/* PASS 2 */

      if (SCP_IN_ERR(curr_scp_idx)) {
         some_scp_in_err = TRUE;
      }

      PRINT_ALL_SYM_TBLS;	/* If debug print -u options */
      PRINT_FORTRAN_OUT;	/* Print ir in a fortran format */

      line_num = SH_GLB_LINE(SCP_LAST_SH_IDX(curr_scp_idx));
      column_num = SH_COL_NUM(SCP_LAST_SH_IDX(curr_scp_idx));

      if (num_prog_unit_errors == 0) {
         if (opt_flags.inline_lvl > Inline_Lvl_0) {
            comp_phase = Inlining;
            inline_processing(SCP_FIRST_SH_IDX(curr_scp_idx));
            PRINT_IR_TBL3;	
         }
      }

      insert_global_directives = TRUE;

      comp_phase = Pdg_Conversion;
      if (dump_flags.preinline) { /* Do not do a full compile */

         if (ATP_PGM_UNIT(SCP_ATTR_IDX(MAIN_SCP_IDX)) == Module ||
             ATP_PGM_UNIT(SCP_ATTR_IDX(MAIN_SCP_IDX)) == Function ||
             ATP_PGM_UNIT(SCP_ATTR_IDX(MAIN_SCP_IDX)) == Subroutine) {
            curr_scp_idx = MAIN_SCP_IDX;
#ifdef KEY /* Bug 3477 */
            if (create_mod_info_file()) {  /* Creates a name for the file. */
	      create_mod_info_tbl();        /* Creates the table. */
	      output_mod_info_file();       /* Writes the table.  */
	      }
#else
            create_mod_info_file();  /* Creates a name for the file. */
            create_mod_info_tbl();        /* Creates the table. */
            output_mod_info_file();       /* Writes the table.  */
#endif /* KEY Bug 3477 */
            free_tables();                /* Frees the tables. */
         }
      }
      else {
#ifdef KEY /* Bug 3477 */
	 int do_output_file = FALSE;
#endif /* KEY Bug 3477 */
         if (ATP_PGM_UNIT(SCP_ATTR_IDX(MAIN_SCP_IDX)) == Module) {
#ifdef KEY /* Bug 3477 */
            do_output_file = create_mod_info_file();  /* Creates a name for the file. */
#else
            create_mod_info_file();  /* Creates a name for the file. */
#endif /* KEY Bug 3477 */
         }

         if (num_prog_unit_errors == 0 && (binary_output || assembly_output)) {
            cvrt_to_pdg(compiler_gen_date);
         }
         else if (ATP_PGM_UNIT(SCP_ATTR_IDX(MAIN_SCP_IDX)) == Module) {

            if (!SCP_IN_ERR(MAIN_SCP_IDX)) {
               curr_scp_idx = MAIN_SCP_IDX;
#ifdef KEY /* Bug 3477 */
	       if (do_output_file) {
		 create_mod_info_tbl();   /* Creates the table. */
		 output_mod_info_file();  /* Writes the table.  */
		 }
#else
               create_mod_info_tbl();   /* Creates the table. */
               output_mod_info_file();  /* Writes the table.  */
#endif /* KEY Bug 3477 */
            }

            free_tables();           /* Frees the tables. */
         }
         else {
            free_tables();           /* Frees the tables. */
         }
      }

      /* ALERT - At this point, the symbol tables are invalid. */

      /* Spit out the End Unit for the current program unit.  The End Unit    */
      /* is needed if the Compiler Information File (CIF) is being produced   */
      /* and for the buffered message file.				      */

      stmt_start_line = line_num;
      stmt_start_col = column_num;

      if (scp_tbl == NULL_IDX) {                  /* Table has been freed. */
         cif_end_unit_rec(program_unit_name);
      }
      else {
         cif_end_unit_rec(AT_OBJ_NAME_PTR(SCP_ATTR_IDX(curr_scp_idx)));
      }

   }  /* while */

   clean_up_module_files();

# ifdef _NAME_SUBSTITUTION_INLINING
   if (!dump_flags.preinline)
# endif
      terminate_PDGCS();

   PRINT_GL_TBL;              /* Prints to debug_file ifdef _DEBUG and -u gl */
   PRINT_GN_TBL;              /* Prints to debug_file ifdef _DEBUG and -u gn */


PREPROCESS_ONLY_SKIP:


# if defined(_HOST_OS_UNICOS) 

   SECOND(&end_time);

# elif defined(_HOST_OS_MAX)

   end_clock = clock();
   end_time  = 0;

# elif defined(_HOST_OS_SOLARIS)

   end_time  = (float) time(NULL);
   end_clock = clock();

# elif (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX))

   getrusage(RUSAGE_SELF, &ru);
   end_time = (double) ru.ru_utime.tv_sec +
              (double) ru.ru_utime.tv_usec * 1e-6 +
              (double) ru.ru_stime.tv_sec +
              (double) ru.ru_stime.tv_usec * 1e-6;

# else

   end_time = 0;

# endif


   total_cpu_time = end_time - start_time;

   if (cif_need_unit_rec  &&  cif_first_pgm_unit) {

      /* Catastrophic errors, like a free source form program was compiled    */
      /* in fixed source form mode, so no Unit record was output.  Output     */
      /* enough records to keep libcif tools happy.  This routine needs to be */
      /* called whether or not a CIF is being written because the buffered    */
      /* message file also must have the correct format.		      */

      cif_fake_a_unit();
   }


   /* CAUTION:  The following code assumes that non-Cray platforms measure    */
   /* memory usage in terms of bytes and that there are 4 bytes per word.     */

   cif_summary_rec(release_level,
                   compiler_gen_date,
                   compiler_gen_time,
                   total_cpu_time,

# if defined(_HOST_OS_UNICOS)

                   (long) 0,
                   (some_scp_in_err) ? -3 : max_field_len);

# elif defined(_HOST_OS_MAX) 

                   end_clock,
                   (some_scp_in_err) ? -3 : max_field_len);

# elif (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX)) 

                   (long) 0,
                   (some_scp_in_err) ? -3 : max_field_len/4);

# else /* defined(_HOST_OS_SOLARIS) */

                   end_clock,
                   (some_scp_in_err) ? -3 : max_field_len/4);

# endif                         
   

   /* Output compilation summary info if the -V option was specified on the   */
   /* command line.  Also, issue the summary information if any messages were */
   /* actually issued.          					      */

   if (cmd_line_flags.verify_option || 
       num_errors > 0               || 
       num_warnings > 0             ||
       num_cautions > 0             ||
       num_notes > 0                ||
       num_comments > 0             ||
       num_ansi > 0                 ||
       (num_optz_msgs > 0  &&  opt_flags.msgs)) { 
      print_buffered_messages();
      print_id_line();

      /* Output the summary lines.  The compilation time is in seconds.       */
      /* CAUTION:  The following non-Cray code assumes a 32-bit word.         */

# if defined(_HOST_OS_UNICOS)

      PRINTMSG (0, 104, Log_Summary, 0, (double) total_cpu_time);
      msg_name	= "cf90";

# elif defined(_HOST_OS_MAX)

      PRINTMSG (0, 104, Log_Summary, 0, (double) end_clock/1000000.0);
      msg_name	= "cf90";

# elif defined(_HOST_OS_LINUX)
      msg_name	= PSC_NAME_PREFIX "f95";

# elif (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX))

      /* IRIX cannot handle the int to float change necessary to get the      */
      /* time printed correctly, so we'll convert it to a character string    */
      /* and use a different message.                                         */
      /*							    	      */
      /* LRR  4/28/97  In an email message from Rich Shapiro to me, he stated */
      /* he did not want this line in the summary lines.		      */

/*    sprintf(time, "%-1.2f", (double) total_cpu_time);
      PRINTMSG (0, 1310, Log_Summary, 0, time);             */
      msg_name	= "cf90";

# elif defined(_HOST_OS_SOLARIS)

      PRINTMSG (0, 104, Log_Summary, 0,
                (total_cpu_time <= 2147.0) ? (float) end_clock/1000000.0 :
                                             (float) total_cpu_time);
      msg_name	= "cf90";

# endif


      /* Maximum field length (maximum amount of memory used) in words        */
      /* (decimal).  							      */
      /* CAUTION:  Non-Cray platforms are assumed to measure memory usage in  */
      /* bytes and we assume 4 bytes per word.         			      */

# if defined(_HOST_OS_UNICOS)

      PRINTMSG (0, 105, Log_Summary, 0, max_field_len);

# elif ! (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX))

      /* LRR  4/28/97  In an email message from Rich Shapiro to me, he stated */
      /* he did not want this line in the summary lines.		      */

      PRINTMSG (0, 105, Log_Summary, 0, max_field_len/4);

# endif


      /* Number of source lines compiled.				      */

# if (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX)) && !defined(_TARGET_SV2)

      PRINTMSG (0, 1401, Log_Summary, 0, --curr_glb_line);

# else

      PRINTMSG (0, 106, Log_Summary, 0, --curr_glb_line);

# endif


      /* Number of messages issued.					      */

# if (defined(_HOST_OS_IRIX) || defined(_HOST_OS_LINUX)) && !defined(_TARGET_SV2)

      PRINTMSG (0, 1403, Log_Summary, 0,
                num_errors,
                num_warnings,
                (opt_flags.msgs == 0) ?
                   (num_cautions + num_notes + num_comments) :
                   (num_cautions + num_notes + num_comments + num_optz_msgs),
                num_ansi);

# else

      PRINTMSG (0, 107, Log_Summary, 0,
                num_errors,
                num_warnings,
                (opt_flags.msgs == 0) ?
                   (num_cautions + num_notes + num_comments) :
                   (num_cautions + num_notes + num_comments + num_optz_msgs),
                num_ansi);


      /* Code: in words; data: in words.				      */

      /* LRR  4/28/97  In an email message from Rich Shapiro to me, he stated */
      /* he did not want this line in the summary lines.		      */

# if !defined(_TARGET_SV2)   /* Prints blank for sv2 right now. */
      PRINTMSG (0, 108, Log_Summary, 0, code_size, data_size);
# endif

# endif

      if (num_errors > 0               || 
          num_warnings > 0             ||
          num_cautions > 0             ||
          num_notes > 0                ||
          num_comments > 0             ||
          num_ansi > 0                 ||
          (num_optz_msgs > 0  &&  opt_flags.msgs)) { 
         PRINTMSG (0, 1636, Log_Summary, 0, msg_name, msg_name);
      }
   }  /* End of summary printing. */


# ifdef _DEBUG

   /* Get memory usage reports for these global tables. */

   final_src_input();

   MEM_REPORT(file_path_tbl);
   MEM_REPORT(global_attr_tbl);
   MEM_REPORT(global_bounds_tbl);
   MEM_REPORT(global_line_tbl);
   MEM_REPORT(global_name_tbl);
   MEM_REPORT(global_type_tbl);
   MEM_REPORT(str_pool);

# endif

   exit_compiler ((num_errors == 0) ? RC_OKAY : RC_USER_ERROR);

}  /* main */
Esempio n. 8
0
//!
//! Main log-printing function, which will dump a line into a log, with a prefix appropriate for
//! the log level, given that the log level is above the threshold.
//!
//! @param[in] level the log level for this message
//! @param[in] format the format string of the message
//! @param[in] ... the variable argument part of the format
//!
//! @return 0 on success, -1 on failure with this function or 1 if log_line() failed.
//!
//! @see log_line()
//!
//! @todo Chuck to evaluate if we cannot standardize the error code returned.
//!
int logprintfl(int level, const char *format, ...)
{
    int offset = 0;
    boolean custom_spec = FALSE;
    char buf[LOGLINEBUF] = { 0 };
    const char *prefix_spec = NULL;

    // return if level is invalid or below the threshold
    if (level < log_level) {
        return 0;
    } else if (level < 0 || level > EUCAOFF) {
        return -1;              // unexpected log level
    }

    if (strcmp(log_custom_prefix, USE_STANDARD_PREFIX) == 0) {
        prefix_spec = log_level_prefix[log_level];
        custom_spec = FALSE;
    } else {
        prefix_spec = log_custom_prefix;
        custom_spec = TRUE;
    }

    // go over prefix format for the log level (defined in log.h or custom)
    for (;                      // prefix_spec is initialized above
         *prefix_spec != '\0'; prefix_spec++) {

        char *s = buf + offset;
        int left = sizeof(buf) - offset - 1;
        if (left < 1) {
            return -1;          // not enough room in internal buffer for a prefix
        }
        // see if we have a formatting character or a regular one
        char c = prefix_spec[0];
        char cn = prefix_spec[1];
        if (c != '%'            // not a special formatting char
            || (c == '%' && cn == '%')  // formatting char, escaped
            || (c == '%' && cn == '\0')) {  // formatting char at the end
            s[0] = c;
            s[1] = '\0';
            offset++;
            if (c == '%' && cn == '%')
                prefix_spec++;  // swallow the one extra '%' in input
            continue;
        }
        prefix_spec++;          // move past the '%' to the formatting char

        int size = 0;
        switch (*prefix_spec) {
        case 'T':              // timestamp
            size = fill_timestamp(s, left);
            break;

        case 'L':{             // log-level
                char l[6];
                euca_strncpy(l, log_level_names[level], 6); // we want hard truncation
                size = snprintf(s, left, "%5s", l);
                break;
            }
        case 'p':{             // process ID
                char p[11];
                snprintf(p, sizeof(p), "%010d", getpid());  // 10 chars is enough for max 32-bit unsigned integer
                size = print_field_truncated(&prefix_spec, s, left, p);
                break;
            }
        case 't':{             // thread ID
                char t[21];
                snprintf(t, sizeof(t), "%020d", (pid_t) syscall(SYS_gettid));   // 20 chars is enough for max 64-bit unsigned integer
                size = print_field_truncated(&prefix_spec, s, left, t);
                break;
            }
        case 'm':              // method
            size = print_field_truncated(&prefix_spec, s, left, _log_curr_method);
            break;

        case 'F':{             // file-and-line
                char file_and_line[64];
                snprintf(file_and_line, sizeof(file_and_line), "%s:%d", _log_curr_file, _log_curr_line);
                size = print_field_truncated(&prefix_spec, s, left, file_and_line);
                break;
            }

        case 's':{             // max RSS of the process
                struct rusage u;
                bzero(&u, sizeof(struct rusage));
                getrusage(RUSAGE_SELF, &u);

                // unfortunately, many fields in 'struct rusage' aren't supported on Linux (notably: ru_ixrss, ru_idrss, ru_isrss)
                char size_str[64];
                snprintf(size_str, sizeof(size_str), "%05ld", u.ru_maxrss / 1024);
                size = print_field_truncated(&prefix_spec, s, left, size_str);
                break;
            }
        case '?':
            s[0] = '?';         // not supported currently
            s[1] = '\0';
            size = 1;
            break;

        default:
            s[0] = *prefix_spec;
            s[1] = '\0';
            size = 1;
            break;
        }

        if (size < 0) {
            logprintf("error in prefix construction in logprintfl()\n");
            return -1;          // something went wrong in the snprintf()s above
        }
        offset += size;
    }

    // add a space between the prefix and the message proper
    if (offset > 0 && ((sizeof(buf) - offset - 1) > 0)) {
        buf[offset++] = ' ';
        buf[offset] = '\0';
    }
    // append the log message passed via va_list
    va_list ap;
    va_start(ap, format);
    int rc = vsnprintf(buf + offset, sizeof(buf) - offset - 1, format, ap);
    va_end(ap);
    if (rc < 0)
        return rc;

    if (syslog_facility != -1) {
        // log to syslog, at the appropriate level
        int l = LOG_DEBUG;      // euca DEBUG, TRACE, and EXTREME use syslog's DEBUG
        if (level == EUCAERROR)
            l = LOG_ERR;
        else if (level == EUCAWARN)
            l = LOG_WARNING;
        else if (level == EUCAINFO)
            l = LOG_INFO;
        if (custom_spec)
            syslog(l, buf);
        else
            syslog(l, buf + offset);
    }

    return log_line(buf);
}
Esempio n. 9
0
int
main(int argc, char **argv)
{
	int iterations;
	struct rusage endUsage;
	struct rusage startUsage;

	/*
	 * getenv() on the existing environment.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		if (getenv(name) == NULL)
			err(EXIT_FAILURE, "getenv(name)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("getenv(name)", &startUsage.ru_utime, &endUsage.ru_utime);


	/*
	 * setenv() a variable with a large value.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		if (setenv(name, value1, 1) == -1)
			err(EXIT_FAILURE, "setenv(name, value1, 1)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("setenv(name, value1, 1)", &startUsage.ru_utime,
	    &endUsage.ru_utime);


	/*
	 * getenv() the new variable on the new environment.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		/* Set large value to variable. */
		if (getenv(name) == NULL)
			err(EXIT_FAILURE, "getenv(name)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("getenv(name)", &startUsage.ru_utime, &endUsage.ru_utime);


	/*
	 * getenv() a different variable on the new environment.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		/* Set large value to variable. */
		if (getenv(name2) == NULL)
			err(EXIT_FAILURE, "getenv(name2)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("getenv(name2)", &startUsage.ru_utime, &endUsage.ru_utime);


	/*
	 * setenv() a variable with a small value.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		if (setenv(name, value2, 1) == -1)
			err(EXIT_FAILURE, "setenv(name, value2, 1)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("setenv(name, value2, 1)", &startUsage.ru_utime,
	    &endUsage.ru_utime);


	/*
	 * getenv() a different variable on the new environment.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		/* Set large value to variable. */
		if (getenv(name2) == NULL)
			err(EXIT_FAILURE, "getenv(name)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("getenv(name)", &startUsage.ru_utime, &endUsage.ru_utime);


	/*
	 * getenv() a different variable on the new environment.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		/* Set large value to variable. */
		if (getenv(name2) == NULL)
			err(EXIT_FAILURE, "getenv(name2)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("getenv(name2)", &startUsage.ru_utime, &endUsage.ru_utime);


	/*
	 * putenv() a variable with a small value.
	 */
	getrusage(RUSAGE_SELF, &startUsage);

	/* Iterate over setting variable. */
	for (iterations = 0; iterations < MaxIterations; iterations++)
		if (putenv(nameValuePair) == -1)
			err(EXIT_FAILURE, "putenv(nameValuePair)");

	getrusage(RUSAGE_SELF, &endUsage);

	report_time("putenv(nameValuePair)", &startUsage.ru_utime,
	    &endUsage.ru_utime);


	exit(EXIT_SUCCESS);
}
Esempio n. 10
0
/*
 * time pipeline (really a statement, not a built-in command)
 */
int
timex(struct op *t, int f, volatile int *xerrok)
{
#define TF_NOARGS	BIT(0)
#define TF_NOREAL	BIT(1)		/* don't report real time */
#define TF_POSIX	BIT(2)		/* report in posix format */
	int rv = 0;
	struct rusage ru0, ru1, cru0, cru1;
	struct timeval usrtime, systime, tv0, tv1;
	int tf = 0;
	extern struct timeval j_usrtime, j_systime; /* computed by j_wait */

	gettimeofday(&tv0, NULL);
	getrusage(RUSAGE_SELF, &ru0);
	getrusage(RUSAGE_CHILDREN, &cru0);
	if (t->left) {
		/*
		 * Two ways of getting cpu usage of a command: just use t0
		 * and t1 (which will get cpu usage from other jobs that
		 * finish while we are executing t->left), or get the
		 * cpu usage of t->left. at&t ksh does the former, while
		 * pdksh tries to do the later (the j_usrtime hack doesn't
		 * really work as it only counts the last job).
		 */
		timerclear(&j_usrtime);
		timerclear(&j_systime);
		rv = execute(t->left, f | XTIME, xerrok);
		if (t->left->type == TCOM)
			tf |= t->left->str[0];
		gettimeofday(&tv1, NULL);
		getrusage(RUSAGE_SELF, &ru1);
		getrusage(RUSAGE_CHILDREN, &cru1);
	} else
		tf = TF_NOARGS;

	if (tf & TF_NOARGS) { /* ksh93 - report shell times (shell+kids) */
		tf |= TF_NOREAL;
		timeradd(&ru0.ru_utime, &cru0.ru_utime, &usrtime);
		timeradd(&ru0.ru_stime, &cru0.ru_stime, &systime);
	} else {
		timersub(&ru1.ru_utime, &ru0.ru_utime, &usrtime);
		timeradd(&usrtime, &j_usrtime, &usrtime);
		timersub(&ru1.ru_stime, &ru0.ru_stime, &systime);
		timeradd(&systime, &j_systime, &systime);
	}

	if (!(tf & TF_NOREAL)) {
		timersub(&tv1, &tv0, &tv1);
		if (tf & TF_POSIX)
			p_time(shl_out, 1, &tv1, 5, "real ", "\n");
		else
			p_time(shl_out, 0, &tv1, 5, NULL, " real ");
	}
	if (tf & TF_POSIX)
		p_time(shl_out, 1, &usrtime, 5, "user ", "\n");
	else
		p_time(shl_out, 0, &usrtime, 5, NULL, " user ");
	if (tf & TF_POSIX)
		p_time(shl_out, 1, &systime, 5, "sys  ", "\n");
	else
		p_time(shl_out, 0, &systime, 5, NULL, " system\n");
	shf_flush(shl_out);

	return rv;
}
Esempio n. 11
0
  int main (void)
  {
    int i;
  
    int allocateOK;
  
    ximg = NULL;
  
  	
    d = XOpenDisplay (NULL);
  
    if (!d)
      fputs ("Couldn't open display\n", stderr), exit (1);
  
    screen = DefaultScreen (d);
    gc = DefaultGC (d, screen);
  
    /* Find a visual */
  
    vis.screen = screen;
    vlist = XGetVisualInfo (d, VisualScreenMask, &vis, &match);
  
    if (!vlist)
      fputs ("No matched visuals\n", stderr), exit (1);
  
    vis = vlist[0];
    XFree (vlist);
		
  	// That's not a fair comparison colormap_size is depth in bits!
    // if (vis.colormap_size < COLORS)
      // printf("Colormap is too small: %i.\n",vis.colormap_size); // , exit (1);
		printf("Colour depth: %i\n",vis.colormap_size);
  
    win = XCreateSimpleWindow (d, DefaultRootWindow (d),
			       0, 0, WIN_W, WIN_H, 0,
			       WhitePixel (d, screen), BlackPixel (d, screen));
  
	  int xclass=get_xvisinfo_class(vis);
		// printf("class = %i\n",xclass);
	  stylee = ( vis.depth > 8 ? styleeTrueColor : styleePrivate );
	  // printf("stylee=%i\n",stylee);
  
    if ( get_xvisinfo_class(vis) % 2 == 1) {	/* The odd numbers can redefine colors */
  
			  // printf("%i\n",get_xvisinfo_class(vis));
	  	
      colormap = DefaultColormap (d, screen);
		  Visual *defaultVisual=DefaultVisual(d,screen);
	  	
      /* Allocate cells */
      allocateOK = (XAllocColorCells (d, colormap, 1,
							      NULL, 0, color, COLORS) != 0);

			// printf("Allocated OK? %i\n",allocateOK);
			
      if (allocateOK) {
  
			  // printf("Allocated OK\n");
        // This doesn't work for installed colormap!
  
        /* Modify the colorcells */
        for (i = 0; i < COLORS; i++)
				  xrgb[i].pixel = color[i];
  
        XStoreColors (d, colormap, xrgb, COLORS);
  
		  } else {

			  colormap = XCreateColormap(d,win,defaultVisual,AllocNone);
		  	
    	  // redocolors();
					  	
      }
  
		  // black = XBlackPixel(d,screen);
		  // white = XWhitePixel(d,screen);
  
    } else if ( get_xvisinfo_class(vis) == TrueColor) {
      colormap = DefaultColormap (d, screen);
					  // printf("TrueColor %i = %i\n",xclass,TrueColor);
      /* This will lookup the color and sets the xrgb[i].pixel value */
      // for (i = 0; i < COLORS; i++)
        // XAllocColor (d, colormap, &xrgb[i]);
    } else
      fprintf (stderr, "Not content with visual class %d.\n",
	       get_xvisinfo_class(vis) ), exit (1);
  
    /* Find out if MITSHM is supported and useable */
    printf ("MITSHM: ");
  
    if (XShmQueryVersion (d, &mitshm_major_code,
			  &mitshm_minor_code, &shared_pixmaps)) {
      int (*handler) (Display *, XErrorEvent *);
      ximg = XShmCreateImage (d, vis.visual,
			     vis.depth, XShmPixmapFormat (d),
			     NULL, &shminfo, WIN_W, WIN_H);
      shminfo.shmid = shmget (IPC_PRIVATE,
			      ximg->bytes_per_line * ximg->height,
			      IPC_CREAT | 0777);
      shminfo.shmaddr = (char *)shmat (shminfo.shmid, 0, 0);
		  ximg->data = (char *)shminfo.shmaddr;
  
      handler = XSetErrorHandler (mitshm_handler);
      XShmAttach (d, &shminfo);	/* Tell the server to attach */
      XSync (d, 0);
      XSetErrorHandler (handler);
  
      shmctl (shminfo.shmid, IPC_RMID, 0);
      /* Mark this shm segment for deletion at once. The segment will
       * automatically become released when both the server and this
       * client have detached from it.
       * (Process termination automagically detach shm segments) */
  
      if (!can_use_mitshm) {
        shmdt (shminfo.shmaddr);
        ximg = NULL;
      }
    }
  
    if (ximg == NULL) {
      can_use_mitshm = 0;
      /* XInitImage(ximg); */
      ximg = XCreateImage (d, vis.visual, vis.depth, ZPixmap,
			  0, (char *)malloc (WIN_W * WIN_H), WIN_W, WIN_H, 8, 0);
    }
  
    if (can_use_mitshm)
      printf ("YES!\n");
    else
      printf ("NO, using fallback instead.\n");
  
    // DrawFractal (ximg,xrgb);
  
    XSelectInput (d, win, ButtonPressMask | ExposureMask);
    XMapWindow (d, win);
  
  
  
  
    real_main();


  
      // XNextEvent (d, &ev);
      // switch (ev.type) {
      // case ButtonPress:
        // should_quit = 1;
        // break;
      // case Expose:
        // if (can_use_mitshm)
				  // XShmPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H, True);
        // else
				  // XPutImage (d, win, gc, img, 0, 0, 0, 0, WIN_W, WIN_H);
        // break;
      // default:
			  // break;
      // }
  
  
  
    if (get_xvisinfo_class(vis) % 2 == 1 || get_xvisinfo_class(vis) == TrueColor) {
      unsigned long color[COLORS];
  
      if (allocateOK) {
        for (i = 0; i < COLORS; i++)
				  color[i] = xrgb[i].pixel;
        XFreeColors (d, colormap, color, COLORS, 0);
      }				/* Allocated colors freed */
    } else {
      XUninstallColormap (d, colormap);
    }
  
    if (can_use_mitshm) {
      XShmDetach (d, &shminfo);	/* Server detached */
      XDestroyImage (ximg);	/* Image struct freed */
      shmdt (shminfo.shmaddr);	/* We're detached */
    } else
      XDestroyImage (ximg);	/* Image struct freed */
  
    XDestroyWindow (d, win);	/* Window removed */
    XCloseDisplay (d);		/* Display disconnected */
  
    /* So you can see how your computer compares to your friend's */
    getrusage (RUSAGE_SELF, &resource_utilization);
		float seconds=(float)resource_utilization.ru_utime.tv_sec
						     +(float)resource_utilization.ru_utime.tv_usec*0.000000001;
		printf("CPU seconds per frame: %f\n",seconds/(float)frameno);
    // printf ("CPU seconds consumed: %ds and %dµs\n",
	    // (int) resource_utilization.ru_utime.tv_sec,
	    // (int) resource_utilization.ru_utime.tv_usec);
  
    return 0;
  }
Esempio n. 12
0
 static long get_max_rss_kb() {
     struct rusage ru;
     getrusage(RUSAGE_SELF, &ru);
     return ru.ru_maxrss;
 }
Esempio n. 13
0
int main (int argc, char *argv[])
{
    extern char *optarg;
    extern int optind, optopt;
    int opt=0;
    int time_simulation = 10000;
    float **t, **t1;
    int exec_time_flag = 1;
    int* sizes;
    int sizes_length = 0;
    int actual_size;
    int problem_size;
    int print_flag = 0;
    int clock_flag;
    time_t user_t_start;
    time_t user_t_end;
    clock_t clock_debut;
    clock_t clock_end;

    float* user_times;
    float* clock_times;

    struct rusage* rusg;

while((opt = getopt(argc, argv, "i:s:t:e:amM")) != -1) {
             switch (opt) {
           case 'i':
            time_simulation = atoi(optarg);
               break;
           case 's':
           	sizes_length = strlen(optarg);
           	sizes = malloc(sizeof(int) * sizes_length);
           	for(int j = 0; j < sizes_length; j++)
           		 sizes[j] = (optarg[j] - '0');
               break;
           case 't':
               break;
           case 'e':
               break;
           case 'a':
            print_flag = 1;
               break;
           case 'm':
           clock_flag = 1;
           exec_time_flag = 10;
           clock_times = malloc(sizeof(float)*exec_time_flag);
              break;
           case 'M':
            exec_time_flag = 10;
            user_times = malloc(sizeof(float)*exec_time_flag);
              break;
               case ':':       // -f or -o without operand
                       fprintf(stderr,
                               "Option -%c requires an operand\n", optopt);

                       break;
           case '?':
                       fprintf(stderr,
                               "Unrecognised option: -%c\n", optopt);

           }
     }
     /*
     if (errflg) {
         fprintf(stderr, "usage: . . . ");
         exit(2);
     }*/


     for(int s=0;s<sizes_length;s++)
     {
      problem_size = (sizes[s]+3); // equivalent a n-1 (retrait de 1 pour decalage de bit)
      actual_size = (2<<problem_size)+2; // calcul de la taille reelle de la matrice



     for(int i=0;i<exec_time_flag;i++)
     {
       rusg = malloc(sizeof(struct rusage));

       if(exec_time_flag > 1)
         user_t_start = time(NULL);

       if(clock_flag)
         clock_debut = clock();

          t = malloc(sizeof(float*)*actual_size);
          t1 = malloc(sizeof(float*)*actual_size);


       for(int i=0;i<actual_size;i++)
       {
         t[i] = malloc(sizeof(float)*actual_size);
         t1[i] = malloc(sizeof(float)*actual_size);
       }

        if(print_flag && i == 0)
          print_matrice(sizes[s],t1);

     fill_heatzone(problem_size,TEMP_CHAUD,t);
     initialize_extern_heat_x(actual_size,TEMP_FROID,t);
     initialize_extern_heat_y(actual_size,TEMP_FROID,t);
     fill_heatzone(problem_size,TEMP_CHAUD,t1);
     initialize_extern_heat_x(actual_size,TEMP_FROID,t1);
     initialize_extern_heat_y(actual_size,TEMP_FROID,t1);
     launch_diff(TEMP_CHAUD,time_simulation,problem_size,t,t1);
    if(print_flag && i == exec_time_flag -1)
       print_matrice(sizes[s],t1);
     free(t);
     free(t1);



     if(clock_flag)
     {
       clock_end = clock();
       clock_times[i] = (float)(clock_end - clock_debut)/CLOCKS_PER_SEC;
      printf("%f\n",(float)(clock_end - clock_debut)/CLOCKS_PER_SEC);
     }
     if(exec_time_flag > 1)
     {
         user_t_end = time(NULL);
         user_times[i] = difftime(user_t_end,user_t_start);
       printf("le temps de réponse utilisateur est de %.3f secondes\n", difftime(user_t_end,user_t_start));
     }
     getrusage(RUSAGE_SELF,rusg);
     printf("memoire consomé %ld kb\n",rusg->ru_maxrss);
     free(rusg);

     }





     if(clock_flag)
        printf("temps moyen (CPU) : %f\n",average_time(clock_times));

     if(exec_time_flag > 1)
       printf("temps moyen de reponse : %f\n",average_time(user_times));

   }

   	return 0;
 }
Esempio n. 14
0
int monitor_child_process(pid_t pid, double start_time) {
  double real_time, user_time, sys_time;
  struct rusage usage;
  int res, status;

  /* Record the PID we are monitoring, for use in the signal handlers. */
  g_monitored_pid = pid;

  /* If we are running with a timeout, set up an alarm now. */
  if (g_timeout_in_seconds) {
    sigset_t masked;
    sigemptyset(&masked);
    sigaddset(&masked, SIGALRM);

    alarm(g_timeout_in_seconds);
  }

  /* Wait for the process to terminate. */
  do {
    res = waitpid(pid, &status, 0);
  } while (res < 0 && errno == EINTR);
  if (res < 0) {
    perror("waitpid");
    return EXITCODE_MONITORING_FAILURE;
  }

  /* Record the real elapsed time as soon as we can. */
  real_time = sample_wall_time() - start_time;

  /* Just in case, kill the child process group. */
  kill(-pid, SIGKILL);

  /* Collect the other resource data on the children. */
  if (getrusage(RUSAGE_CHILDREN, &usage) < 0) {
    perror("getrusage");
    return EXITCODE_MONITORING_FAILURE;
  }
  user_time = (double) usage.ru_utime.tv_sec + usage.ru_utime.tv_usec/1000000.0;
  sys_time = (double) usage.ru_stime.tv_sec + usage.ru_stime.tv_usec/1000000.0;

  /* If the process was signalled, report a more interesting status. */
  int exit_status;
  if (WIFSIGNALED(status)) {
    fprintf(stderr, "%s: error: child terminated by signal %d\n",
            g_program_name, WTERMSIG(status));

    /* Propagate the signalled status to the caller. */
    exit_status = 128 + WTERMSIG(status);
  } else if (WIFEXITED(status)) {
    exit_status = WEXITSTATUS(status);
  } else {
    /* This should never happen, but if it does assume some kind of failure. */
    exit_status = EXITCODE_MONITORING_FAILURE;
  }

  // If we are not using a summary file, report the information as /usr/bin/time
  // would.
  if (!g_summary_file) {
    if (g_posix_mode) {
      fprintf(stderr, "real %12.4f\nuser %12.4f\nsys  %12.4f\n",
              real_time, user_time, sys_time);
    } else {
      fprintf(stderr, "%12.4f real %12.4f user %12.4f sys\n",
              real_time, user_time, sys_time);
    }
  } else {
    /* Otherwise, write the summary data in a simple parsable format. */
    FILE *fp = fopen(g_summary_file, "w");
    if (!fp) {
      perror("fopen");
      return EXITCODE_MONITORING_FAILURE;
    }

    fprintf(fp, "exit %d\n", exit_status);
    fprintf(fp, "%-10s %.4f\n", "real", real_time);
    fprintf(fp, "%-10s %.4f\n", "user", user_time);
    fprintf(fp, "%-10s %.4f\n", "sys", sys_time);
    fclose(fp);
  }

  return exit_status;
}
int main(int argc, char* argv[])
{
  char exePath[MAXPATHLEN];

  nsresult rv = mozilla::BinaryPath::Get(argv[0], exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.\n");
    return 255;
  }

  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
  if (!lastSlash || (lastSlash - exePath > MAXPATHLEN - sizeof(XPCOM_DLL) - 1))
    return 255;

  strcpy(++lastSlash, XPCOM_DLL);

  int gotCounters;
#if defined(XP_UNIX)
  struct rusage initialRUsage;
  gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
#elif defined(XP_WIN)
  // GetProcessIoCounters().ReadOperationCount seems to have little to
  // do with actual read operations. It reports 0 or 1 at this stage
  // in the program. Luckily 1 coincides with when prefetch is
  // enabled. If Windows prefetch didn't happen we can do our own
  // faster dll preloading.
  IO_COUNTERS ioCounters;
  gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
  if (gotCounters && !ioCounters.ReadOperationCount)
#endif
  {
      XPCOMGlueEnablePreload();
  }


  rv = XPCOMGlueStartup(exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XPCOM.\n");
    return 255;
  }
  // Reset exePath so that it is the directory name and not the xpcom dll name
  *lastSlash = 0;

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XRE functions.\n");
    return 255;
  }

#ifdef XRE_HAS_DLL_BLOCKLIST
  XRE_SetupDllBlocklist();
#endif

  if (gotCounters) {
#if defined(XP_WIN)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_OPS,
                            int(ioCounters.ReadOperationCount));
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_TRANSFER,
                            int(ioCounters.ReadTransferCount / 1024));
    IO_COUNTERS newIoCounters;
    if (GetProcessIoCounters(GetCurrentProcess(), &newIoCounters)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_OPS,
                              int(newIoCounters.ReadOperationCount - ioCounters.ReadOperationCount));
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_TRANSFER,
                              int((newIoCounters.ReadTransferCount - ioCounters.ReadTransferCount) / 1024));
    }
#elif defined(XP_UNIX)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_HARD_FAULTS,
                            int(initialRUsage.ru_majflt));
    struct rusage newRUsage;
    if (!getrusage(RUSAGE_SELF, &newRUsage)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_HARD_FAULTS,
                              int(newRUsage.ru_majflt - initialRUsage.ru_majflt));
    }
#endif
  }

  int result;
  {
    ScopedLogging log;
    result = do_main(argc, argv);
  }

  XPCOMGlueShutdown();
  return result;
}
Esempio n. 16
0
void InspIRCd::Run()
{
#ifdef INSPIRCD_ENABLE_TESTSUITE
	/* See if we're supposed to be running the test suite rather than entering the mainloop */
	if (do_testsuite)
	{
		TestSuite* ts = new TestSuite;
		delete ts;
		return;
	}
#endif

	UpdateTime();
	time_t OLDTIME = TIME.tv_sec;

	while (true)
	{
#ifndef _WIN32
		static rusage ru;
#endif

		/* Check if there is a config thread which has finished executing but has not yet been freed */
		if (this->ConfigThread && this->ConfigThread->IsDone())
		{
			/* Rehash has completed */
			this->Logs.Log("CONFIG", LOG_DEBUG, "Detected ConfigThread exiting, tidying up...");

			this->ConfigThread->Finish();

			ConfigThread->join();
			delete ConfigThread;
			ConfigThread = NULL;
		}

		UpdateTime();

		/* Run background module timers every few seconds
		 * (the docs say modules shouldnt rely on accurate
		 * timing using this event, so we dont have to
		 * time this exactly).
		 */
		if (TIME.tv_sec != OLDTIME)
		{
#ifndef _WIN32
			getrusage(RUSAGE_SELF, &ru);
			stats.LastSampled = TIME;
			stats.LastCPU = ru.ru_utime;
#else
			if(QueryPerformanceCounter(&stats.LastSampled))
			{
				FILETIME CreationTime;
				FILETIME ExitTime;
				FILETIME KernelTime;
				FILETIME UserTime;
				GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
				stats.LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
				stats.LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
			}
#endif

			if (Config->TimeSkipWarn)
			{
				time_t timediff = TIME.tv_sec - OLDTIME;

				if (timediff > Config->TimeSkipWarn)
					SNO.WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped forwards by %lu seconds!", timediff);

				else if (timediff < -Config->TimeSkipWarn)
					SNO.WriteToSnoMask('a', "\002Performance warning!\002 Server clock jumped backwards by %lu seconds!", labs(timediff));
			}

			OLDTIME = TIME.tv_sec;

			if ((TIME.tv_sec % 3600) == 0)
			{
				FOREACH_MOD(OnGarbageCollect, ());

				// HACK: ELines are not expired properly at the moment but it can't be fixed as
				// the 2.0 XLine system is a spaghetti nightmare. Instead we skip over expired
				// ELines in XLineManager::CheckELines() and expire them here instead.
				XLines->GetAll("E");
			}

			Timers.TickTimers(TIME.tv_sec);
			Users.DoBackgroundUserStuff();

			if ((TIME.tv_sec % 5) == 0)
			{
				FOREACH_MOD(OnBackgroundTimer, (TIME.tv_sec));
				SNO.FlushSnotices();
			}
		}
Esempio n. 17
0
int main(int argc, _CONST char* argv[])
{
#ifndef MOZ_B2G_LOADER
  char exePath[MAXPATHLEN];
#endif

#ifdef MOZ_WIDGET_GONK
  // This creates a ThreadPool for binder ipc. A ThreadPool is necessary to
  // receive binder calls, though not necessary to send binder calls.
  // ProcessState::Self() also needs to be called once on the main thread to
  // register the main thread with the binder driver.
  android::ProcessState::self()->startThreadPool();
#endif

  nsresult rv;
#ifndef MOZ_B2G_LOADER
  rv = mozilla::BinaryPath::Get(argv[0], exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't calculate the application directory.\n");
    return 255;
  }

  char *lastSlash = strrchr(exePath, XPCOM_FILE_PATH_SEPARATOR[0]);
  if (!lastSlash || ((lastSlash - exePath) + sizeof(XPCOM_DLL) + 1 > MAXPATHLEN))
    return 255;

  strcpy(++lastSlash, XPCOM_DLL);
#endif // MOZ_B2G_LOADER

#if defined(XP_UNIX)
  // If the b2g app is launched from adb shell, then the shell will wind
  // up being the process group controller. This means that we can't send
  // signals to the process group (useful for profiling).
  // We ignore the return value since setsid() fails if we're already the
  // process group controller (the normal situation).
  (void)setsid();
#endif

  int gotCounters;
#if defined(XP_UNIX)
  struct rusage initialRUsage;
  gotCounters = !getrusage(RUSAGE_SELF, &initialRUsage);
#elif defined(XP_WIN)
  IO_COUNTERS ioCounters;
  gotCounters = GetProcessIoCounters(GetCurrentProcess(), &ioCounters);
#else
  #error "Unknown platform"  // having this here keeps cppcheck happy
#endif

#ifdef HAS_DLL_BLOCKLIST
  DllBlocklist_Initialize();
#endif

  // B2G loader has already initialized Gecko so we can't initialize
  // it again here.
#ifndef MOZ_B2G_LOADER
  // We do this because of data in bug 771745
  XPCOMGlueEnablePreload();

  rv = XPCOMGlueStartup(exePath);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XPCOM.\n");
    return 255;
  }
  // Reset exePath so that it is the directory name and not the xpcom dll name
  *lastSlash = 0;
#endif // MOZ_B2G_LOADER

  rv = XPCOMGlueLoadXULFunctions(kXULFuncs);
  if (NS_FAILED(rv)) {
    Output("Couldn't load XRE functions.\n");
    return 255;
  }

  if (gotCounters) {
#if defined(XP_WIN)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_OPS,
                            int(ioCounters.ReadOperationCount));
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_READ_TRANSFER,
                            int(ioCounters.ReadTransferCount / 1024));
    IO_COUNTERS newIoCounters;
    if (GetProcessIoCounters(GetCurrentProcess(), &newIoCounters)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_OPS,
                              int(newIoCounters.ReadOperationCount - ioCounters.ReadOperationCount));
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_READ_TRANSFER,
                              int((newIoCounters.ReadTransferCount - ioCounters.ReadTransferCount) / 1024));
    }
#elif defined(XP_UNIX)
    XRE_TelemetryAccumulate(mozilla::Telemetry::EARLY_GLUESTARTUP_HARD_FAULTS,
                            int(initialRUsage.ru_majflt));
    struct rusage newRUsage;
    if (!getrusage(RUSAGE_SELF, &newRUsage)) {
      XRE_TelemetryAccumulate(mozilla::Telemetry::GLUESTARTUP_HARD_FAULTS,
                              int(newRUsage.ru_majflt - initialRUsage.ru_majflt));
    }
#else
  #error "Unknown platform"  // having this here keeps cppcheck happy
#endif
  }

  int result;
  {
    ScopedLogging log;
    char **_argv;

    /*
     * Duplicate argument vector to conform non-const argv of
     * do_main() since XRE_main() is very stupid with non-const argv.
     */
    _argv = new char *[argc + 1];
    for (int i = 0; i < argc; i++) {
      size_t len = strlen(argv[i]) + 1;
      _argv[i] = new char[len];
      MOZ_ASSERT(_argv[i] != nullptr);
      memcpy(_argv[i], argv[i], len);
    }
    _argv[argc] = nullptr;

    result = do_main(argc, _argv);

    for (int i = 0; i < argc; i++) {
      delete[] _argv[i];
    }
    delete[] _argv;
  }

  return result;
}
Esempio n. 18
0
static int
getentropy_fallback(void *buf, size_t len)
{
	uint8_t results[SHA512_DIGEST_LENGTH];
	int save_errno = errno, e, pgs = getpagesize(), faster = 0, repeat;
	static int cnt;
	struct timespec ts;
	struct timeval tv;
	struct rusage ru;
	sigset_t sigset;
	struct stat st;
	SHA512_CTX ctx;
	static pid_t lastpid;
	pid_t pid;
	size_t i, ii, m;
	char *p;
	struct tcpstat tcpstat;
	struct udpstat udpstat;
	struct ipstat ipstat;
	u_int64_t mach_time;
	unsigned int idata;
	void *addr;

	pid = getpid();
	if (lastpid == pid) {
		faster = 1;
		repeat = 2;
	} else {
		faster = 0;
		lastpid = pid;
		repeat = REPEAT;
	}
	for (i = 0; i < len; ) {
		int j;
		SHA512_Init(&ctx);
		for (j = 0; j < repeat; j++) {
			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
			if (e != -1) {
				cnt += (int)tv.tv_sec;
				cnt += (int)tv.tv_usec;
			}

			mach_time = mach_absolute_time();
			HD(mach_time);

			ii = sizeof(addr);
			HX(sysctl(kmib, sizeof(kmib) / sizeof(kmib[0]),
			    &addr, &ii, NULL, 0) == -1, addr);

			ii = sizeof(idata);
			HX(sysctl(hwmib, sizeof(hwmib) / sizeof(hwmib[0]),
			    &idata, &ii, NULL, 0) == -1, idata);

			ii = sizeof(tcpstat);
			HX(sysctl(tcpmib, sizeof(tcpmib) / sizeof(tcpmib[0]),
			    &tcpstat, &ii, NULL, 0) == -1, tcpstat);

			ii = sizeof(udpstat);
			HX(sysctl(udpmib, sizeof(udpmib) / sizeof(udpmib[0]),
			    &udpstat, &ii, NULL, 0) == -1, udpstat);

			ii = sizeof(ipstat);
			HX(sysctl(ipmib, sizeof(ipmib) / sizeof(ipmib[0]),
			    &ipstat, &ii, NULL, 0) == -1, ipstat);

			HX((pid = getpid()) == -1, pid);
			HX((pid = getsid(pid)) == -1, pid);
			HX((pid = getppid()) == -1, pid);
			HX((pid = getpgid(0)) == -1, pid);
			HX((e = getpriority(0, 0)) == -1, e);

			if (!faster) {
				ts.tv_sec = 0;
				ts.tv_nsec = 1;
				(void) nanosleep(&ts, NULL);
			}

			HX(sigpending(&sigset) == -1, sigset);
			HX(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1,
			    sigset);

#if 0
			HF(main);		/* an addr in program */
#endif
			HF(getentropy);	/* an addr in this library */
			HF(printf);		/* an addr in libc */
			p = (char *)&p;
			HD(p);		/* an addr on stack */
			p = (char *)&errno;
			HD(p);		/* the addr of errno */

			if (i == 0) {
				struct sockaddr_storage ss;
				struct statvfs stvfs;
				struct termios tios;
				struct statfs stfs;
				socklen_t ssl;
				off_t off;

				/*
				 * Prime-sized mappings encourage fragmentation;
				 * thus exposing some address entropy.
				 */
				struct mm {
					size_t	npg;
					void	*p;
				} mm[] =	 {
					{ 17, MAP_FAILED }, { 3, MAP_FAILED },
					{ 11, MAP_FAILED }, { 2, MAP_FAILED },
					{ 5, MAP_FAILED }, { 3, MAP_FAILED },
					{ 7, MAP_FAILED }, { 1, MAP_FAILED },
					{ 57, MAP_FAILED }, { 3, MAP_FAILED },
					{ 131, MAP_FAILED }, { 1, MAP_FAILED },
				};

				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
					HX(mm[m].p = mmap(NULL,
					    mm[m].npg * pgs,
					    PROT_READ|PROT_WRITE,
					    MAP_PRIVATE|MAP_ANON, -1,
					    (off_t)0), mm[m].p);
					if (mm[m].p != MAP_FAILED) {
						size_t mo;

						/* Touch some memory... */
						p = mm[m].p;
						mo = cnt %
						    (mm[m].npg * pgs - 1);
						p[mo] = 1;
						cnt += (int)((long)(mm[m].p)
						    / pgs);
					}

					/* Check cnts and times... */
					mach_time = mach_absolute_time();
					HD(mach_time);
					cnt += (int)mach_time;

					HX((e = getrusage(RUSAGE_SELF,
					    &ru)) == -1, ru);
					if (e != -1) {
						cnt += (int)ru.ru_utime.tv_sec;
						cnt += (int)ru.ru_utime.tv_usec;
					}
				}

				for (m = 0; m < sizeof mm/sizeof(mm[0]); m++) {
					if (mm[m].p != MAP_FAILED)
						munmap(mm[m].p, mm[m].npg * pgs);
					mm[m].p = MAP_FAILED;
				}

				HX(stat(".", &st) == -1, st);
				HX(statvfs(".", &stvfs) == -1, stvfs);
				HX(statfs(".", &stfs) == -1, stfs);

				HX(stat("/", &st) == -1, st);
				HX(statvfs("/", &stvfs) == -1, stvfs);
				HX(statfs("/", &stfs) == -1, stfs);

				HX((e = fstat(0, &st)) == -1, st);
				if (e == -1) {
					if (S_ISREG(st.st_mode) ||
					    S_ISFIFO(st.st_mode) ||
					    S_ISSOCK(st.st_mode)) {
						HX(fstatvfs(0, &stvfs) == -1,
						    stvfs);
						HX(fstatfs(0, &stfs) == -1,
						    stfs);
						HX((off = lseek(0, (off_t)0,
						    SEEK_CUR)) < 0, off);
					}
					if (S_ISCHR(st.st_mode)) {
						HX(tcgetattr(0, &tios) == -1,
						    tios);
					} else if (S_ISSOCK(st.st_mode)) {
						memset(&ss, 0, sizeof ss);
						ssl = sizeof(ss);
						HX(getpeername(0,
						    (void *)&ss, &ssl) == -1,
						    ss);
					}
				}

				HX((e = getrusage(RUSAGE_CHILDREN,
				    &ru)) == -1, ru);
				if (e != -1) {
					cnt += (int)ru.ru_utime.tv_sec;
					cnt += (int)ru.ru_utime.tv_usec;
				}
			} else {
				/* Subsequent hashes absorb previous result */
				HD(results);
			}

			HX((e = gettimeofday(&tv, NULL)) == -1, tv);
			if (e != -1) {
				cnt += (int)tv.tv_sec;
				cnt += (int)tv.tv_usec;
			}

			HD(cnt);
		}

		SHA512_Final(results, &ctx);
		memcpy((char *)buf + i, results, min(sizeof(results), len - i));
		i += min(sizeof(results), len - i);
	}
	memset(results, 0, sizeof results);
	if (gotdata(buf, len) == 0) {
		errno = save_errno;
		return 0;		/* satisfied */
	}
	errno = EIO;
	return -1;
}
Esempio n. 19
0
int InspIRCd::Run()
{
	/* See if we're supposed to be running the test suite rather than entering the mainloop */
	if (Config->cmdline.TestSuite)
	{
		TestSuite* ts = new TestSuite;
		delete ts;
		Exit(0);
	}

	UpdateTime();
	time_t OLDTIME = TIME.tv_sec;

	while (true)
	{
#ifndef _WIN32
		static rusage ru;
#endif

		/* Check if there is a config thread which has finished executing but has not yet been freed */
		if (this->ConfigThread && this->ConfigThread->IsDone())
		{
			/* Rehash has completed */
			this->Logs->Log("CONFIG",DEBUG,"Detected ConfigThread exiting, tidying up...");

			this->ConfigThread->Finish();

			ConfigThread->join();
			delete ConfigThread;
			ConfigThread = NULL;
		}

		UpdateTime();

		/* Run background module timers every few seconds
		 * (the docs say modules shouldnt rely on accurate
		 * timing using this event, so we dont have to
		 * time this exactly).
		 */
		if (TIME.tv_sec != OLDTIME)
		{
#ifndef _WIN32
			getrusage(RUSAGE_SELF, &ru);
			stats->LastSampled = TIME;
			stats->LastCPU = ru.ru_utime;
#else
			if(QueryPerformanceCounter(&stats->LastSampled))
			{
				FILETIME CreationTime;
				FILETIME ExitTime;
				FILETIME KernelTime;
				FILETIME UserTime;
				GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime);
				stats->LastCPU.dwHighDateTime = KernelTime.dwHighDateTime + UserTime.dwHighDateTime;
				stats->LastCPU.dwLowDateTime = KernelTime.dwLowDateTime + UserTime.dwLowDateTime;
			}
#endif

			/* Allow a buffer of two seconds drift on this so that ntpdate etc dont harass admins */
			if (TIME.tv_sec < OLDTIME - 2)
			{
				SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is flowing BACKWARDS in this dimension! Clock drifted backwards %lu secs.", (unsigned long)OLDTIME-TIME.tv_sec);
			}
			else if (TIME.tv_sec > OLDTIME + 2)
			{
				SNO->WriteToSnoMask('d', "\002EH?!\002 -- Time is jumping FORWARDS! Clock skipped %lu secs.", (unsigned long)TIME.tv_sec - OLDTIME);
			}

			OLDTIME = TIME.tv_sec;

			if ((TIME.tv_sec % 3600) == 0)
			{
				Users->GarbageCollect();
				FOREACH_MOD(I_OnGarbageCollect, OnGarbageCollect());
			}

			Timers->TickTimers(TIME.tv_sec);
			this->DoBackgroundUserStuff();

			if ((TIME.tv_sec % 5) == 0)
			{
				FOREACH_MOD(I_OnBackgroundTimer,OnBackgroundTimer(TIME.tv_sec));
				SNO->FlushSnotices();
			}
		}

		/* Call the socket engine to wait on the active
		 * file descriptors. The socket engine has everything's
		 * descriptors in its list... dns, modules, users,
		 * servers... so its nice and easy, just one call.
		 * This will cause any read or write events to be
		 * dispatched to their handlers.
		 */
		this->SE->DispatchTrialWrites();
		this->SE->DispatchEvents();

		/* if any users were quit, take them out */
		GlobalCulls.Apply();
		AtomicActions.Run();

		if (this->s_signal)
		{
			this->SignalHandler(s_signal);
			this->s_signal = 0;
		}
	}

	return 0;
}
Esempio n. 20
0
 static void measure_usage(rusage& r) {
   if (-1 == getrusage(RUSAGE_SELF, &r)) throw std::runtime_error("getrusage failed");
 }
Esempio n. 21
0
/**
@details
-# Set the mode to Initialization
   Requirement [@ref r_exec_mode_0].
-# Start the cpu usage meter
-# Call the default_data jobs
-# Call the initialization jobs.
-# Record the cpu usage during initialization
-# The scheduler initializes simulation timers.
   Requirement [@ref r_exec_time_1].
-# If an exception is caught, print as much error information available based
   on execption type caught and exit.
-# If no execption is caught return 0
*/
int Trick::Executive::init() {

    double cpu_time ;

    try {

        mode = Initialization ;

        /* Start the cpu usage meter */
        struct rusage cpu_usage_buf ;
        getrusage(RUSAGE_SELF, &cpu_usage_buf);
        cpu_start =   ((double) cpu_usage_buf.ru_utime.tv_sec) + ((double) cpu_usage_buf.ru_utime.tv_usec / 1000000.0);

        call_default_data() ;

        call_input_processor() ;

        // If we are starting from a checkpoint, restart_called will be true.  Skip init routines in this case.
        if ( ! restart_called ) {
            call_initialization() ;
        }

        /* Set the initial values for the scheduler times. */
        next_frame_check_tics = software_frame_tics + time_tics ;
        job_call_time_tics = next_frame_check_tics ;
        sim_start = get_sim_time();

        /* Record the cpu usage for initialization */
        getrusage(RUSAGE_SELF, &cpu_usage_buf);
        cpu_time = ((double) cpu_usage_buf.ru_utime.tv_sec) + ((double) cpu_usage_buf.ru_utime.tv_usec / 1000000.0);
        cpu_init = cpu_time - cpu_start;

        initialization_complete = true ;

    /* Print as much error information avaiable for all exception and exit. */
    } catch (Trick::Exec_exception & ex ) {
        /* Set the exit return code, file name, and error message. Return -1 so we go to shutdown */
        except_return = ex.ret_code ;
        except_file = ex.file ;
        except_message = ex.message ;
        return(-1) ;
    } catch (const std::exception &ex) {
        if ( curr_job != NULL ) {
            except_file = curr_job->name ;
        } else {
            except_file = "somewhere in Executive::init" ;
        }
        fprintf(stderr, "\nExecutive::loop terminated with std::exception\n  ROUTINE: %s\n  DIAGNOSTIC: %s\n",
         except_file.c_str(), ex.what()) ;
        exit(-1) ;
    } catch (...) {
        if ( curr_job != NULL ) {
            except_file = curr_job->name ;
        } else {
            except_file = "somewhere in Executive::init" ;
        }
        except_message = "unknown error" ;
        fprintf(stderr, "\nExecutive::loop terminated with unknown exception\n  ROUTINE: %s\n  DIAGNOSTIC: %s\n",
         except_file.c_str() , except_message.c_str()) ;
        exit(-1) ;
    }

    /* return 0 if there are no errors. */
    return(0) ;
}
Esempio n. 22
0
DWORD CServerDef::StatGet(SERV_STAT_TYPE i) const
{
	ADDTOCALLSTACK("CServerDef::StatGet");
	ASSERT( i >= 0 && i <= SERV_STAT_QTY );
	DWORD	d = m_dwStat[i];
	EXC_TRY("StatGet");
	if ( i == SERV_STAT_MEM )	// memory information
	{
		d = 0;
		if ( m_bPmemory )
		{
#ifdef _WIN32
			if ( !m_hmPsapiDll )			// try to load psapi.dll if not loaded yet
			{
				EXC_SET("load process info");
				m_hmPsapiDll = LoadLibrary(TEXT("psapi.dll"));
				if (m_hmPsapiDll == NULL)
				{
					m_bPmemory = false;
					g_Log.EventError(("Unable to load process information PSAPI.DLL library. Memory information will be not available.\n"));
				}
				else
				{
					m_GetProcessMemoryInfo = reinterpret_cast<pGetProcessMemoryInfo>(::GetProcAddress(m_hmPsapiDll,"GetProcessMemoryInfo"));
				}
			}

			if ( m_GetProcessMemoryInfo ) {
				EXC_SET("open process");
				HANDLE hProcess = GetCurrentProcess();
				if ( hProcess ) {
					ASSERT( hProcess == (HANDLE)-1 );
					EXC_SET("get memory info");
					if ( m_GetProcessMemoryInfo(hProcess, &pcnt, sizeof(pcnt)) ) {
						EXC_SET("read memory info");
						d = pcnt.WorkingSetSize;
					}
					CloseHandle(hProcess);
				}
			}
#else
			struct rusage usage;
			int res = getrusage(RUSAGE_SELF, &usage);

			if ( res == 0 && usage.ru_idrss )
				d = usage.ru_idrss;
			else
			{
				CFileText inf;
				TCHAR * buf = Str_GetTemp(), * head;

				sprintf(buf, "/proc/%d/status", getpid());
				if ( inf.Open(buf, OF_READ|OF_TEXT) )
				{
					for (;;)
					{
						if ( !inf.ReadString(buf, SCRIPT_MAX_LINE_LEN) )
							break;

						if ( (head = strstr(buf, "VmSize:")) != NULL )
						{
							head += 7;
							GETNONWHITESPACE(head)
							d = ATOI(head) * 1000;
							break;
						}
					}
					inf.Close();
				}
			}

			if ( !d )
			{
				g_Log.EventError(("Unable to load process information from getrusage() and procfs. Memory information will be not available.\n"));
				m_bPmemory = false;
			}
#endif

			if ( d != 0 )
				d /= 1024;
		}
	}
	return d;

	EXC_CATCH;
	EXC_DEBUG_START;
	g_Log.EventDebug("stat '%d', val '%lu'\n", i, d);
	EXC_DEBUG_END;
	return 0;
}
Esempio n. 23
0
asmlinkage long sys_getrusage(int who, struct rusage __user *ru)
{
	if (who != RUSAGE_SELF && who != RUSAGE_CHILDREN)
		return -EINVAL;
	return getrusage(current, who, ru);
}
Esempio n. 24
0
static void
loadLibs(const char *apkName)
{
  chdir(getenv("GRE_HOME"));

  simple_linker_init();

  struct stat status;
  if (!stat(apkName, &status))
    apk_mtime = status.st_mtime;

  struct timeval t0, t1;
  gettimeofday(&t0, 0);
  struct rusage usage1;
  getrusage(RUSAGE_THREAD, &usage1);

  void *zip = map_file(apkName);
  struct cdir_end *dirend = (struct cdir_end *)((char *)zip + zip_size - sizeof(*dirend));
  while ((void *)dirend > zip &&
         letoh32(dirend->signature) != CDIR_END_SIG)
    dirend = (struct cdir_end *)((char *)dirend - 1);
  if (letoh32(dirend->signature) != CDIR_END_SIG) {
    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't find end of central directory record");
    return;
  }

  uint32_t cdir_offset = letoh32(dirend->cdir_offset);
  uint16_t cdir_entries = letoh16(dirend->cdir_entries);

  struct cdir_entry *cdir_start = (struct cdir_entry *)((char *)zip + cdir_offset);

  lib_mapping = (struct mapping_info *)calloc(MAX_MAPPING_INFO, sizeof(*lib_mapping));
#ifdef MOZ_CRASHREPORTER
  file_ids = (char *)extractBuf("lib.id", zip, cdir_start, cdir_entries);
#endif

#define MOZLOAD(name) mozload("lib" name ".so", zip, cdir_start, cdir_entries)
  MOZLOAD("mozalloc");
  MOZLOAD("nspr4");
  MOZLOAD("plc4");
  MOZLOAD("plds4");
  MOZLOAD("mozsqlite3");
  MOZLOAD("nssutil3");
  MOZLOAD("nss3");
  MOZLOAD("ssl3");
  MOZLOAD("smime3");
  xul_handle = MOZLOAD("xul");
  MOZLOAD("xpcom");
  MOZLOAD("nssckbi");
  MOZLOAD("freebl3");
  MOZLOAD("softokn3");
#undef MOZLOAD

  close(zip_fd);

#ifdef MOZ_CRASHREPORTER
  free(file_ids);
  file_ids = NULL;
#endif

  if (!xul_handle)
    __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Couldn't get a handle to libxul!");

#define GETFUNC(name) f_ ## name = (name ## _t) __wrap_dlsym(xul_handle, "Java_org_mozilla_gecko_GeckoAppShell_" #name)
  GETFUNC(nativeInit);
  GETFUNC(nativeRun);
  GETFUNC(notifyGeckoOfEvent);
  GETFUNC(processNextNativeEvent);
  GETFUNC(setSurfaceView);
  GETFUNC(setSoftwareLayerClient);
  GETFUNC(onResume);
  GETFUNC(onLowMemory);
  GETFUNC(callObserver);
  GETFUNC(removeObserver);
  GETFUNC(onChangeNetworkLinkStatus);
  GETFUNC(reportJavaCrash);
  GETFUNC(executeNextRunnable);
  GETFUNC(cameraCallbackBridge);
  GETFUNC(notifyUriVisited);
  GETFUNC(notifyBatteryChange);
  GETFUNC(notifySmsReceived);
#undef GETFUNC
  sStartupTimeline = (uint64_t *)__wrap_dlsym(xul_handle, "_ZN7mozilla15StartupTimeline16sStartupTimelineE");
  gettimeofday(&t1, 0);
  struct rusage usage2;
  getrusage(RUSAGE_THREAD, &usage2);
  __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Loaded libs in %dms total, %dms user, %dms system, %d faults",
                      (t1.tv_sec - t0.tv_sec)*1000 + (t1.tv_usec - t0.tv_usec)/1000, 
                      (usage2.ru_utime.tv_sec - usage1.ru_utime.tv_sec)*1000 + (usage2.ru_utime.tv_usec - usage1.ru_utime.tv_usec)/1000,
                      (usage2.ru_stime.tv_sec - usage1.ru_stime.tv_sec)*1000 + (usage2.ru_stime.tv_usec - usage1.ru_stime.tv_usec)/1000,
                      usage2.ru_majflt-usage1.ru_majflt);

  StartupTimeline_Record(LINKER_INITIALIZED, &t0);
  StartupTimeline_Record(LIBRARIES_LOADED, &t1);
}
Esempio n. 25
0
void my_end(int infoflag)
{
  /*
    this code is suboptimal to workaround a bug in
    Sun CC: Sun C++ 5.6 2004/06/02 for x86, and should not be
    optimized until this compiler is not in use anymore
  */
  FILE *info_file= DBUG_FILE;
  my_bool print_info= (info_file != stderr);

  if (!my_init_done)
    return;

  /*
    We do not use DBUG_ENTER here, as after cleanup DBUG is no longer
    operational, so we cannot use DBUG_RETURN.
  */
  DBUG_PRINT("info",("Shutting down: infoflag: %d  print_info: %d",
                     infoflag, print_info));
  if (!info_file)
  {
    info_file= stderr;
    print_info= 0;
  }

  if ((infoflag & MY_CHECK_ERROR) || print_info)

  {					/* Test if some file is left open */
    if (my_file_opened | my_stream_opened)
    {
      char ebuff[512];
      my_snprintf(ebuff, sizeof(ebuff), EE(EE_OPEN_WARNING),
                  my_file_opened, my_stream_opened);
      my_message_stderr(EE_OPEN_WARNING, ebuff, ME_BELL);
      DBUG_PRINT("error", ("%s", ebuff));
      my_print_open_files();
    }
  }
  free_charsets();
  my_error_unregister_all();
  my_once_free();

  if ((infoflag & MY_GIVE_INFO) || print_info)
  {
#ifdef HAVE_GETRUSAGE
    struct rusage rus;
#ifdef HAVE_valgrind
    /* Purify assumes that rus is uninitialized after getrusage call */
    bzero((char*) &rus, sizeof(rus));
#endif
    if (!getrusage(RUSAGE_SELF, &rus))
      fprintf(info_file,"\n\
User time %.2f, System time %.2f\n\
Maximum resident set size %ld, Integral resident set size %ld\n\
Non-physical pagefaults %ld, Physical pagefaults %ld, Swaps %ld\n\
Blocks in %ld out %ld, Messages in %ld out %ld, Signals %ld\n\
Voluntary context switches %ld, Involuntary context switches %ld\n",
	      (rus.ru_utime.tv_sec * SCALE_SEC +
	       rus.ru_utime.tv_usec / SCALE_USEC) / 100.0,
	      (rus.ru_stime.tv_sec * SCALE_SEC +
	       rus.ru_stime.tv_usec / SCALE_USEC) / 100.0,
	      rus.ru_maxrss, rus.ru_idrss,
	      rus.ru_minflt, rus.ru_majflt,
	      rus.ru_nswap, rus.ru_inblock, rus.ru_oublock,
	      rus.ru_msgsnd, rus.ru_msgrcv, rus.ru_nsignals,
	      rus.ru_nvcsw, rus.ru_nivcsw);
#endif
#if defined(__WIN__) && defined(_MSC_VER)
   _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
   _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR );
   _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
   _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
   _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );
   _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );
   _CrtCheckMemory();
   _CrtDumpMemoryLeaks();
#endif
  }

  my_thread_end();
  my_thread_global_end();

  if (!(infoflag & MY_DONT_FREE_DBUG))
    DBUG_END();                /* Must be done as late as possible */

  my_mutex_end();
#if defined(SAFE_MUTEX)
  /*
    Check on destroying of mutexes. A few may be left that will get cleaned
    up by C++ destructors
  */
  safe_mutex_end((infoflag & (MY_GIVE_INFO | MY_CHECK_ERROR)) ? stderr :
                 (FILE *) 0);
#endif /* defined(SAFE_MUTEX) */

#ifdef __WIN__
  if (have_tcpip)
    WSACleanup();
#endif /* __WIN__ */
 
  /* At very last, delete mysys key, it is used everywhere including DBUG */
  pthread_key_delete(THR_KEY_mysys);
  my_init_done=0;
} /* my_end */
Esempio n. 26
0
/**
 * This method is called once in a while by a backend to determine if it needs
 * to backoff per its current usage and target usage.
 */
static inline void
BackoffBackend()
{
	BackoffBackendLocalEntry *le = NULL;
	BackoffBackendSharedEntry *se = NULL;

	/* Try to achieve target usage! */
	struct timeval currentTime;
	struct rusage currentUsage;
	double		thisProcessTime = 0.0;
	double		totalTime = 0.0;
	double		cpuRatio = 0.0;
	double		changeFactor = 1.0;

	le = myBackoffLocalEntry();
	Assert(le);
	se = myBackoffSharedEntry();
	Assert(se);
	Assert(se->weight > 0);

	/* Provide tracing information */
	TRACE_POSTGRESQL_BACKOFF_LOCALCHECK(MyBackendId);

	if (gettimeofday(&currentTime, NULL) < 0)
	{
		elog(ERROR, "Unable to execute gettimeofday(). Please disable query prioritization.");
	}

	if (getrusage(RUSAGE_SELF, &currentUsage) < 0)
	{
		elog(ERROR, "Unable to execute getrusage(). Please disable query prioritization.");
	}

	/* If backoff can be performed by this process */
	if (se->backoff)
	{
		/*
		 * How much did the cpu work on behalf of this process - incl user and
		 * sys time
		 */
		thisProcessTime = TIMEVAL_DIFF_USEC(currentUsage.ru_utime, le->lastUsage.ru_utime)
			+ TIMEVAL_DIFF_USEC(currentUsage.ru_stime, le->lastUsage.ru_stime);

		/*
		 * Absolute cpu time since the last check. This accounts for multiple
		 * procs per segment
		 */
		totalTime = TIMEVAL_DIFF_USEC(currentTime, se->lastCheckTime);

		cpuRatio = thisProcessTime / totalTime;

		cpuRatio = Min(cpuRatio, 1.0);

		changeFactor = cpuRatio / se->targetUsage;

		le->lastSleepTime *= changeFactor;

		if (le->lastSleepTime < DEFAULT_SLEEP_TIME)
			le->lastSleepTime = DEFAULT_SLEEP_TIME;

		if (gp_debug_resqueue_priority)
		{
			elog(LOG, "thissession = %d, thisProcTime = %f, totalTime = %f, targetusage = %f, cpuRatio = %f, change factor = %f, sleeptime = %f",
				 se->statementId.sessionId, thisProcessTime, totalTime, se->targetUsage, cpuRatio, changeFactor, (double) le->lastSleepTime);
		}

		memcpy(&le->lastUsage, &currentUsage, sizeof(currentUsage));
		memcpy(&se->lastCheckTime, &currentTime, sizeof(currentTime));

		if (le->lastSleepTime > MIN_SLEEP_THRESHOLD)
		{
			/*
			 * Sleeping happens in chunks so that the backend may exit early
			 * from its sleep if the sweeper requests it to.
			 */
			int			j = 0;
			long		sleepInterval = ((long) gp_resqueue_priority_sweeper_interval) * 1000L;
			int			numIterations = (int) (le->lastSleepTime / sleepInterval);
			double		leftOver = (double) ((long) le->lastSleepTime % sleepInterval);

			for (j = 0; j < numIterations; j++)
			{
				/* Sleep a chunk */
				pg_usleep(sleepInterval);
				/* Check for early backoff exit */
				if (se->earlyBackoffExit)
				{
					le->lastSleepTime = DEFAULT_SLEEP_TIME;		/* Minimize sleep time
																 * since we may need to
																 * recompute from
																 * scratch */
					break;
				}
			}
			if (j == numIterations)
				pg_usleep(leftOver);
		}
	}
	else
	{
		/*
		 * Even if this backend did not backoff, it should record current
		 * usage and current time so that subsequent calculations are
		 * accurate.
		 */
		memcpy(&le->lastUsage, &currentUsage, sizeof(currentUsage));
		memcpy(&se->lastCheckTime, &currentTime, sizeof(currentTime));
	}

	/* Consider finding a better leader for better grouping */
	if (!groupingTimeExpired())
	{
		findBetterGroupLeader();
	}
}
Esempio n. 27
0
TRI_process_info_t TRI_ProcessInfoSelf () {
  TRI_process_info_t result;
  struct rusage used;
  int res;

  memset(&result, 0, sizeof(result));
  result._scClkTck = 1000000;

  res = getrusage(RUSAGE_SELF, &used);

  if (res == 0) {
    result._minorPageFaults = used.ru_minflt;
    result._majorPageFaults = used.ru_majflt;

    result._systemTime = TRI_MicrosecondsTv(&used.ru_stime);
    result._userTime = TRI_MicrosecondsTv(&used.ru_utime);

    // ru_maxrss is the resident set size in kilobytes. need to multiply with 1024 to get the number of bytes
    result._residentSize = used.ru_maxrss * TRI_GETRUSAGE_MAXRSS_UNIT;
  }

#ifdef TRI_HAVE_MACH
  {
    kern_return_t rc;
    thread_array_t array;
    mach_msg_type_number_t count;

    rc = task_threads(mach_task_self(), &array, &count);

    if (rc == KERN_SUCCESS) {
      unsigned int i;

      result._numberThreads = count;

      for (i = 0;  i < count;  ++i) {
        mach_port_deallocate(mach_task_self(), array[i]);
      }

      vm_deallocate(mach_task_self(), (vm_address_t)array, sizeof(thread_t) * count);
    }
  }

  {
    kern_return_t rc;
    struct task_basic_info t_info;
    mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;

    rc = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
    if (rc == KERN_SUCCESS) {
      result._virtualSize = t_info.virtual_size;
      result._residentSize = t_info.resident_size;
    }
    else {
      result._virtualSize = 0;
      result._residentSize = 0;
    }


  }
#endif

  return result;
}
// Helper function to keep code base small
void ofdmframesync_rxsymbol_bench(struct rusage *_start,
                                 struct rusage *_finish,
                                 unsigned long int *_num_iterations,
                                 unsigned int _num_subcarriers,
                                 unsigned int _cp_len)
{
    // options
    modulation_scheme ms = LIQUID_MODEM_QPSK;
    unsigned int M         = _num_subcarriers;
    unsigned int cp_len    = _cp_len;
    unsigned int taper_len = 0;

    // create synthesizer/analyzer objects
    ofdmframegen fg = ofdmframegen_create(M, cp_len, taper_len, NULL);
    //ofdmframegen_print(fg);

    modem mod = modem_create(ms);

    ofdmframesync fs = ofdmframesync_create(M,cp_len,taper_len,NULL,NULL,NULL);

    unsigned int i;
    float complex X[M];         // channelized symbol
    float complex x[M+cp_len];  // time-domain symbol

    // synchronize short sequence (first)
    ofdmframegen_write_S0a(fg, x);
    ofdmframesync_execute(fs, x, M+cp_len);

    // synchronize short sequence (second)
    ofdmframegen_write_S0b(fg, x);
    ofdmframesync_execute(fs, x, M+cp_len);

    // synchronize long sequence
    ofdmframegen_write_S1(fg, x);
    ofdmframesync_execute(fs, x, M+cp_len);

    // modulate data symbols (use same symbol, ignore pilot phase)
    unsigned int s;
    for (i=0; i<M; i++) {
        s = modem_gen_rand_sym(mod);
        modem_modulate(mod,s,&X[i]);
    }

    ofdmframegen_writesymbol(fg, X, x);

    // add noise
    for (i=0; i<M+cp_len; i++)
        x[i] += 0.02f*randnf()*cexpf(_Complex_I*2*M_PI*randf());

    // normalize number of iterations
    *_num_iterations /= M;

    // start trials
    getrusage(RUSAGE_SELF, _start);
    for (i=0; i<(*_num_iterations); i++) {
        // receive data symbols (ignoring pilots)
        ofdmframesync_execute(fs, x, M+cp_len);
        ofdmframesync_execute(fs, x, M+cp_len);
        ofdmframesync_execute(fs, x, M+cp_len);
        ofdmframesync_execute(fs, x, M+cp_len);
    }
    getrusage(RUSAGE_SELF, _finish);
    *_num_iterations *= 4;

    // destroy objects
    ofdmframegen_destroy(fg);
    ofdmframesync_destroy(fs);
    modem_destroy(mod);
}
Esempio n. 29
0
int main(int argc, char* argv[])
{
    // check for correct number of args
    if (argc != 2 && argc != 3)
    {
        printf("Usage: speller [dictionary] text\n");
        return 1;
    }

    // structs for timing data
    struct rusage before, after;

    // benchmarks
    double time_load = 0.0, time_check = 0.0, time_size = 0.0, time_unload = 0.0;

    // determine dictionary to use
    char* dictionary = (argc == 3) ? argv[1] : DICTIONARY;
  
    void print_hash(void);
    
        
    // load dictionary
    getrusage(RUSAGE_SELF, &before);
    bool loaded = load(dictionary);
    getrusage(RUSAGE_SELF, &after);


    // abort if dictionary not loaded
    if (!loaded)
    {
        printf("Could not load %s.\n", dictionary);
        return 2;
    }

    // calculate time to load dictionary
    time_load = calculate(&before, &after);

    // try to open text
    char* text = (argc == 3) ? argv[2] : argv[1];
    FILE* fp = fopen(text, "r");
    if (fp == NULL)
    {
        printf("Could not open %s.\n", text);
        unload();
        return 3; 
    }

    // prepare to report misspellings
    printf("\nMISSPELLED WORDS\n\n");

    // prepare to spell-check
    int index = 0, misspellings = 0, words = 0;
    char word[LENGTH+1];

    // spell-check each word in text
    for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
    {
        // allow only alphabetical characters and apostrophes
        if (isalpha(c) || (c == '\'' && index > 0))
        {
            // append character to word
            word[index] = c;
            index++;

            // ignore alphabetical strings too long to be words
            if (index > LENGTH)
            {
                // consume remainder of alphabetical string
                while ((c = fgetc(fp)) != EOF && isalpha(c));

                // prepare for new word
                index = 0;
            }
        }

        // ignore words with numbers (like MS Word can)
        else if (isdigit(c))
        {
            // consume remainder of alphanumeric string
            while ((c = fgetc(fp)) != EOF && isalnum(c));

            // prepare for new word
            index = 0;
        }

        // we must have found a whole word
        else if (index > 0)
        {
            // terminate current word
            word[index] = '\0';

            // update counter
            words++;

            // check word's spelling
            getrusage(RUSAGE_SELF, &before);
            bool misspelled = !check(word);
            getrusage(RUSAGE_SELF, &after);

            // update benchmark
            time_check += calculate(&before, &after);

            // print word if misspelled
            if (misspelled)
            {
                printf("%s\n", word);
                misspellings++;
            }

            // prepare for next word
            index = 0;
        }
    }

    // check whether there was an error
    if (ferror(fp))
    {
        fclose(fp);
        printf("Error reading %s.\n", text);
        unload();
        return 4;
    }

    // close text
    fclose(fp);

    // determine dictionary's size
    getrusage(RUSAGE_SELF, &before);
    unsigned int n = size();
    getrusage(RUSAGE_SELF, &after);

    // calculate time to determine dictionary's size
    time_size = calculate(&before, &after);

    // unload dictionary
    getrusage(RUSAGE_SELF, &before);
    bool unloaded = unload();
    getrusage(RUSAGE_SELF, &after);

    // abort if dictionary not unloaded
    if (!unloaded)
    {
        printf("Could not unload %s.\n", dictionary);
        return 5;
    }

    // calculate time to unload dictionary
    time_unload = calculate(&before, &after);

    // report benchmarks
    printf("\nWORDS MISSPELLED:     %d\n", misspellings);
    printf("WORDS IN DICTIONARY:  %d\n", n);
    printf("WORDS IN TEXT:        %d\n", words);
    printf("TIME IN load:         %.2f\n", time_load);
    printf("TIME IN check:        %.2f\n", time_check);
    printf("TIME IN size:         %.2f\n", time_size);
    printf("TIME IN unload:       %.2f\n", time_unload);
    printf("TIME IN TOTAL:        %.2f\n\n", 
     time_load + time_check + time_size + time_unload);

    // that's all folks
    return 0;
}
Esempio n. 30
0
size_t getPeakRSS(void)
{
    struct rusage rusage;
    getrusage( RUSAGE_SELF, &rusage );
    return (size_t)(rusage.ru_maxrss * 1024L);
}