Esempio n. 1
0
static void oaes_get_seed( char buf[RANDSIZ + 1] )
{
        #if !defined(__FreeBSD__) && !defined(__OpenBSD__)
	struct timeb timer;
	struct tm *gmTimer;
	char * _test = NULL;
	
	ftime (&timer);
	gmTimer = gmtime( &timer.time );
	_test = (char *) calloc( sizeof( char ), timer.millitm );
	sprintf( buf, "%04d%02d%02d%02d%02d%02d%03d%p%d",
		gmTimer->tm_year + 1900, gmTimer->tm_mon + 1, gmTimer->tm_mday,
		gmTimer->tm_hour, gmTimer->tm_min, gmTimer->tm_sec, timer.millitm,
		_test + timer.millitm, GETPID() );
	#else
	struct timeval timer;
	struct tm *gmTimer;
	char * _test = NULL;
	
	gettimeofday(&timer, NULL);
	gmTimer = gmtime( &timer.tv_sec );
	_test = (char *) calloc( sizeof( char ), timer.tv_usec/1000 );
	sprintf( buf, "%04d%02d%02d%02d%02d%02d%03d%p%d",
		gmTimer->tm_year + 1900, gmTimer->tm_mon + 1, gmTimer->tm_mday,
		gmTimer->tm_hour, gmTimer->tm_min, gmTimer->tm_sec, timer.tv_usec/1000,
		_test + timer.tv_usec/1000, GETPID() );
	#endif
		
	if( _test )
		free( _test );
}
Esempio n. 2
0
static uint32_t oaes_get_seed(void)
{
        #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__ANDROID__)
	struct timeb timer;
	struct tm *gmTimer;
	char * _test = NULL;
	uint32_t _ret = 0;
	
	ftime (&timer);
	gmTimer = gmtime( &timer.time );
	_test = (char *) calloc( sizeof( char ), timer.millitm );
	_ret = gmTimer->tm_year + 1900 + gmTimer->tm_mon + 1 + gmTimer->tm_mday +
			gmTimer->tm_hour + gmTimer->tm_min + gmTimer->tm_sec + timer.millitm +
			(uintptr_t) ( _test + timer.millitm ) + GETPID();
	#else
	struct timeval timer;
	struct tm *gmTimer;
	char * _test = NULL;
	uint32_t _ret = 0;
	
	gettimeofday(&timer, NULL);
	gmTimer = gmtime( &timer.tv_sec );
	_test = (char *) calloc( sizeof( char ), timer.tv_usec/1000 );
	_ret = gmTimer->tm_year + 1900 + gmTimer->tm_mon + 1 + gmTimer->tm_mday +
			gmTimer->tm_hour + gmTimer->tm_min + gmTimer->tm_sec + timer.tv_usec/1000 +
			(uintptr_t) ( _test + timer.tv_usec/1000 ) + GETPID();
	#endif

	if( _test )
		free( _test );
	
	return _ret;
}
Esempio n. 3
0
File: tls.c Progetto: mingpen/OpenNT
// Clean out thread data that we know to be obsolete (leftover from a task
// that UAE'd or didn't cleanup after itself correctly).
//
void TlsCleanupDeadTasks()
{
    PTHREAD pthread;
    TID tid;
    PID pid;

    tid = GETTID(&tid);   		// tid = caller's SS
    GETPID(pid);                        // pid = caller's process id

    DebAssert(tid != TID_EMPTY, "");

    // search for thread's tid field

    for (pthread = g_rgthread; pthread < g_pthreadEnd; pthread++) {
      // if we find an entry with our own SS, but a different process id,
      // then it must be a process that has terminated without cleaning up
      // after itself.   So we wipe out it's entry now.
      if (pthread->tid == tid && !ISEQUALPID(pthread->pid, pid)) {

	// This thread's entry contains obsolete data, since the thread has
	// terminated, and the memory pointed to by our structures is either
	// gone, or in use by somebody else.

        // Pretend this thread did TlsSetValue(itls, NULL) on all it's itls's,
	// to put us back into a stable state.
        memset (pthread->rgtls, 0, ITLS_COMPONENTS * sizeof(LPVOID));
        pthread->tid = TID_EMPTY;
        g_tidThreadCache = TID_EMPTY;
        break;
      }
    }
}
Esempio n. 4
0
/**
* Initialize MPI
*/
void PROCESSOR::init(int argc, char* argv[]) {
	int namelen,provided,requested = MPI_THREAD_MULTIPLE;
	MPI_Init_thread(&argc, &argv,requested,&provided);
	MPI_Comm_size(MPI_COMM_WORLD, &PROCESSOR::n_hosts);
	MPI_Comm_rank(MPI_COMM_WORLD, &PROCESSOR::host_id);
	MPI_Get_processor_name(PROCESSOR::host_name, &namelen);
	
	/*init thread support*/
	if(provided != requested) {
		static const char* support[] = {
			"MPI_THREAD_SINGLE","MPI_THREAD_FUNNELED",
		    "MPI_THREAD_SERIALIZED","MPI_THREAD_MULTIPLE"
		};
		print("[Warning]: %s not supported. %s provided.\n",
			support[requested],support[provided]);
		print("[Warning]: Scorpio may hang when run with multiple threads"
			" (including message polling thread).\n");
	}

	print("Process [%d/%d] on %s : pid %d\n",PROCESSOR::host_id,
		PROCESSOR::n_hosts,PROCESSOR::host_name,GETPID());
	
	/*global split point*/
	global_split = new SPLIT_MESSAGE[n_hosts];
#ifdef THREAD_POLLING
	if(n_hosts > 1)
		t_create(check_messages,0);
#endif
}
Esempio n. 5
0
 WatermarkNode(
   const std::string & input, const std::string & output, const std::string & text,
   const std::string & node_name = "watermark_node")
 : Node(node_name, true)
 {
   auto qos = rmw_qos_profile_sensor_data;
   // Create a publisher on the input topic.
   pub_ = this->create_publisher<sensor_msgs::msg::Image>(output, qos);
   std::weak_ptr<std::remove_pointer<decltype(pub_.get())>::type> captured_pub = pub_;
   // Create a subscription on the output topic.
   sub_ = this->create_subscription<sensor_msgs::msg::Image>(
     input, [captured_pub, text](sensor_msgs::msg::Image::UniquePtr msg) {
     auto pub_ptr = captured_pub.lock();
     if (!pub_ptr) {
       return;
     }
     // Create a cv::Mat from the image message (without copying).
     cv::Mat cv_mat(
       msg->width, msg->height,
       encoding2mat_type(msg->encoding),
       msg->data.data());
     // Annotate the image with the pid, pointer address, and the watermark text.
     std::stringstream ss;
     ss << "pid: " << GETPID() << ", ptr: " << msg.get() << " " << text;
     draw_on_image(cv_mat, ss.str(), 40);
     pub_ptr->publish(msg);    // Publish it along.
   }, qos);
 }
	void ApplicationBinding::_GetPID(const ValueList& args, KValueRef result)
	{
		if (this->current)
		{
			result->SetInt(GETPID());
		}
	}
Esempio n. 7
0
File: tls.c Progetto: mingpen/OpenNT
LPVOID PASCAL EXPORT TlsGetValue(ITLS itls)
{
    PTHREAD pthread;
    TID tid;
#if ID_DEBUG
    PID pidTmp;
#endif  //ID_DEBUG

    tid = GETTID(&tid);   // tid = caller's SS

    DebAssert(tid != TID_EMPTY, "");
    DebAssert(itls < ITLS_COMPONENTS, "TlsGetValue err1");
    DebAssert(g_rgbSlot[itls] != 0, "TlsGetValue err2");

    if (g_tidThreadCache == tid) {
#if ID_DEBUG
      GETPID(pidTmp);
      DebAssert(ISEQUALPID(pidTmp, g_pthreadCache->pid), "bad pid");
#endif  //ID_DEBUG
      return g_pthreadCache->rgtls[itls];
    }

    // cache doesn't contain desired value
    // search for thread's tid field

    for (pthread = g_rgthread; pthread < g_pthreadEnd; pthread++) {
      if (pthread->tid == tid) {
#if ID_DEBUG
	GETPID(pidTmp);
	DebAssert(ISEQUALPID(pidTmp, pthread->pid), "bad pid");
#endif  //ID_DEBUG
        g_tidThreadCache = tid;
        g_pthreadCache = pthread;
        return pthread->rgtls[itls];
      }
    }

    // thread not found.
    // value must be NULL since TlsSetValue hasn't been called.
    //
    return NULL;
}
Esempio n. 8
0
static void NaClLogOutputTag_mu(struct Gio *s) {
  char timestamp[128];
  int  pid;

  if (timestamp_enabled && tag_output) {
    pid = GETPID();
    gprintf(s, "[%d,%u:%s] ",
            pid,
            NaClThreadId(),
            NaClTimeStampString(timestamp, sizeof timestamp));
    tag_output = 0;
  }
}
Esempio n. 9
0
void _myisam_log_record(enum myisam_log_commands command, MI_INFO *info,
			const uchar *record, my_off_t filepos, int result)
{
  uchar buff[21],*pos;
  int error,old_errno;
  uint length;
  ulong pid=(ulong) GETPID();

  old_errno=my_errno;
  if (!info->s->base.blobs)
    length=info->s->base.reclength;
  else
    length=info->s->base.reclength+ _my_calc_total_blob_length(info,record);
  buff[0]=(uchar) command;
  mi_int2store(buff+1,info->dfile);
  mi_int4store(buff+3,pid);
  mi_int2store(buff+7,result);
  mi_sizestore(buff+9,filepos);
  mi_int4store(buff+17,length);
  mysql_mutex_lock(&THR_LOCK_myisam);
  error=my_lock(myisam_log_file,F_WRLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  (void) mysql_file_write(myisam_log_file, buff, sizeof(buff), MYF(0));
  (void) mysql_file_write(myisam_log_file, record, info->s->base.reclength, MYF(0));
  if (info->s->base.blobs)
  {
    MI_BLOB *blob,*end;

    for (end=info->blobs+info->s->base.blobs, blob= info->blobs;
	 blob != end ;
	 blob++)
    {
      memcpy(&pos, record+blob->offset+blob->pack_length,
                   sizeof(char*));
      (void) mysql_file_write(myisam_log_file, pos, blob->length, MYF(0));
    }
  }
  if (!error)
    error=my_lock(myisam_log_file,F_UNLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  mysql_mutex_unlock(&THR_LOCK_myisam);
  my_errno=old_errno;
}
Esempio n. 10
0
void _nisam_log_command(enum nisam_log_commands command, N_INFO *info, const byte *buffert, uint length, int result)
{
  char buff[9];
  int error,old_errno;
  ulong pid=(ulong) GETPID();

  old_errno=my_errno;
  buff[0]=(char) command;
  int2store(buff+1,info->dfile);
  int4store(buff+3,pid);
  int2store(buff+7,result);
  pthread_mutex_lock(&THR_LOCK_isam);
  error=my_lock(nisam_log_file,F_WRLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  VOID(my_write(nisam_log_file,buff,sizeof(buff),MYF(0)));
  if (buffert)
    VOID(my_write(nisam_log_file,buffert,length,MYF(0)));
  if (!error)
    error=my_lock(nisam_log_file,F_UNLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  pthread_mutex_unlock(&THR_LOCK_isam);
  my_errno=old_errno;
}
Esempio n. 11
0
void _myisam_log_command(enum myisam_log_commands command, MI_INFO *info,
			 const uchar *buffert, uint length, int result)
{
  uchar buff[9];
  int error,old_errno;
  ulong pid=(ulong) GETPID();

  old_errno=my_errno;
  buff[0]=(char) command;
  mi_int2store(buff+1,info->dfile);
  mi_int4store(buff+3,pid);
  mi_int2store(buff+7,result);
  mysql_mutex_lock(&THR_LOCK_myisam);
  error=my_lock(myisam_log_file,F_WRLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  (void) mysql_file_write(myisam_log_file, buff, sizeof(buff), MYF(0));
  if (buffert)
    (void) mysql_file_write(myisam_log_file, buffert, length, MYF(0));
  if (!error)
    error=my_lock(myisam_log_file,F_UNLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  mysql_mutex_unlock(&THR_LOCK_myisam);
  my_errno=old_errno;
}
Esempio n. 12
0
void _nisam_log_record(enum nisam_log_commands command, N_INFO *info, const byte *record, ulong filepos, int result)
{
  char buff[17],*pos;
  int error,old_errno;
  uint length;
  ulong pid=(ulong) GETPID();

  old_errno=my_errno;
  if (!info->s->base.blobs)
    length=info->s->base.reclength;
  else
    length=info->s->base.reclength+ _calc_total_blob_length(info,record);
  buff[0]=(char) command;
  int2store(buff+1,info->dfile);
  int4store(buff+3,pid);
  int2store(buff+7,result);
  int4store(buff+9,filepos);
  int4store(buff+13,length);
  pthread_mutex_lock(&THR_LOCK_isam);
  error=my_lock(nisam_log_file,F_WRLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  VOID(my_write(nisam_log_file,buff,sizeof(buff),MYF(0)));
  VOID(my_write(nisam_log_file,(byte*) record,info->s->base.reclength,MYF(0)));
  if (info->s->base.blobs)
  {
    N_BLOB *blob,*end;

    for (end=info->blobs+info->s->base.blobs, blob= info->blobs;
	 blob != end ;
	 blob++)
    {
      bmove(&pos,record+blob->offset+blob->pack_length,sizeof(char*));
      VOID(my_write(nisam_log_file,pos,blob->length,MYF(0)));
    }
  }
  if (!error)
    error=my_lock(nisam_log_file,F_UNLCK,0L,F_TO_EOF,MYF(MY_SEEK_NOT_DONE));
  pthread_mutex_unlock(&THR_LOCK_isam);
  my_errno=old_errno;
}
Esempio n. 13
0
void msg_error(const char *fmt,...)
{
	va_list ap;

	va_start (ap, fmt);

	if (__pre_write_fn) {
		__pre_write_fn(__pre_write_ctx, fmt, ap);
	}

	if (__write_fn != NULL) {
		__write_fn(__msg_ctx, fmt, ap);
	}
	
	if (__stdout_enable) {
		printf("msg_error->pid(%d), ", GETPID());
		vprintf(fmt, ap);
		printf("\r\n");
	}

	va_end (ap);
}
Esempio n. 14
0
File: tls.c Progetto: mingpen/OpenNT
BOOL PASCAL EXPORT TlsSetValue(ITLS itls, LPVOID pvParam)
{
    TID tid;
    PTHREAD pthread, pthreadFree;
    LPVOID * ppv;
#if ID_DEBUG
    PID pidTmp;
#endif  //ID_DEBUG

    tid = GETTID(&tid);   // tid = caller's SS

    DebAssert(tid != TID_EMPTY, "");
    DebAssert(itls < ITLS_COMPONENTS, "TlsSetValue err1");
    DebAssert(g_rgbSlot[itls] != 0, "TlsSetValue err2");

    // search for thread's tid field

    pthreadFree = NULL;
    for (pthread = g_rgthread; pthread < g_pthreadEnd; pthread++) {
      if (pthread->tid == tid) {
#if ID_DEBUG
	  GETPID(pidTmp);
	  DebAssert(ISEQUALPID(pidTmp, pthread->pid), "bad pid");
#endif  //ID_DEBUG
	  goto SetValue;	// found it -- set the value
	}
      if ((pthreadFree == NULL) &&
          (pthread->tid == TID_EMPTY)) {
        // remember 1st free thread
        pthreadFree = pthread;
      }
    }
    if (pthreadFree == NULL)
      return FALSE;  // no free slots available for this thread

    // allocate a new THREAD instance
    pthread = pthreadFree;
    GETPID(pthread->pid);

SetValue:
    pthread->rgtls[itls] = pvParam;

    // WARNING: setting of tid must be AFTER the data value is set (directly
    // above).  This is required for the interrupt-driven break check, 
    // which assumes the data is valid if the tid is non-empty.
    //
    pthread->tid = tid;

#if ID_DEBUG
    pthread->rgfSlotUsed[ itls ] = -1;
#endif 
    if (pvParam != NULL)
      return TRUE;

    // See if all of this thread's slots are NULL.
    // If so, release resources occupied by the thread.

    for (ppv = &pthread->rgtls[0];
         ppv < &pthread->rgtls[ITLS_COMPONENTS];
         ppv++) {
      if (*ppv != NULL)
        return TRUE; // at least one slot is still in use by this thread
    }

    // This thread's last field is NULL - release the thread, flush cache

    pthread->tid = TID_EMPTY;
    g_tidThreadCache = TID_EMPTY;
    return TRUE;
}
Esempio n. 15
0
int SQLITE_CDECL main(int argc, char **argv){
  const char *zClient;
  int iClient;
  int n, i;
  int openFlags = SQLITE_OPEN_READWRITE;
  int rc;
  char *zScript;
  int taskId;
  const char *zTrace;
  const char *zCOption;
  const char *zJMode;
  const char *zNRep;
  int nRep = 1, iRep;
  int iTmout = 0;              /* Default: no timeout */
  const char *zTmout;

  g.argv0 = argv[0];
  g.iTrace = 1;
  if( argc<2 ) usage(argv[0]);
  g.zDbFile = argv[1];
  if( strglob("*.test", g.zDbFile) ) usage(argv[0]);
  if( strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID)!=0 ){
    fprintf(stderr, "SQLite library and header mismatch\n"
                    "Library: %s\n"
                    "Header:  %s\n",
                    sqlite3_sourceid(), SQLITE_SOURCE_ID);
    exit(1);
  }
  n = argc-2;
  sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.mptest", GETPID());
  zJMode = findOption(argv+2, &n, "journalmode", 1);
  zNRep = findOption(argv+2, &n, "repeat", 1);
  if( zNRep ) nRep = atoi(zNRep);
  if( nRep<1 ) nRep = 1;
  g.zVfs = findOption(argv+2, &n, "vfs", 1);
  zClient = findOption(argv+2, &n, "client", 1);
  g.zErrLog = findOption(argv+2, &n, "errlog", 1);
  g.zLog = findOption(argv+2, &n, "log", 1);
  zTrace = findOption(argv+2, &n, "trace", 1);
  if( zTrace ) g.iTrace = atoi(zTrace);
  if( findOption(argv+2, &n, "quiet", 0)!=0 ) g.iTrace = 0;
  zTmout = findOption(argv+2, &n, "timeout", 1);
  if( zTmout ) iTmout = atoi(zTmout);
  g.bSqlTrace = findOption(argv+2, &n, "sqltrace", 0)!=0;
  g.bSync = findOption(argv+2, &n, "sync", 0)!=0;
  if( g.zErrLog ){
    g.pErrLog = fopen(g.zErrLog, "a");
  }else{
    g.pErrLog = stderr;
  }
  if( g.zLog ){
    g.pLog = fopen(g.zLog, "a");
  }else{
    g.pLog = stdout;
  }
  
  sqlite3_config(SQLITE_CONFIG_LOG, sqlErrorCallback, 0);
  if( zClient ){
    iClient = atoi(zClient);
    if( iClient<1 ) fatalError("illegal client number: %d\n", iClient);
    sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.client%02d",
                     GETPID(), iClient);
  }else{
    int nTry = 0;
    if( g.iTrace>0 ){
      printf("BEGIN: %s", argv[0]);
      for(i=1; i<argc; i++) printf(" %s", argv[i]);
      printf("\n");
      printf("With SQLite " SQLITE_VERSION " " SQLITE_SOURCE_ID "\n" );
      for(i=0; (zCOption = sqlite3_compileoption_get(i))!=0; i++){
        printf("-DSQLITE_%s\n", zCOption);
      }
      fflush(stdout);
    }
    iClient =  0;
    do{
      if( (nTry%5)==4 ) printf("... %strying to unlink '%s'\n",
                               nTry>5 ? "still " : "", g.zDbFile);
      rc = unlink(g.zDbFile);
      if( rc && errno==ENOENT ) rc = 0;
    }while( rc!=0 && (++nTry)<60 && sqlite3_sleep(1000)>0 );
    if( rc!=0 ){
      fatalError("unable to unlink '%s' after %d attempts\n",
                 g.zDbFile, nTry);
    }
    openFlags |= SQLITE_OPEN_CREATE;
  }
  rc = sqlite3_open_v2(g.zDbFile, &g.db, openFlags, g.zVfs);
  if( rc ) fatalError("cannot open [%s]", g.zDbFile);
  if( iTmout>0 ) sqlite3_busy_timeout(g.db, iTmout);
  
  if( zJMode ){
#if defined(_WIN32)
    if( sqlite3_stricmp(zJMode,"persist")==0
     || sqlite3_stricmp(zJMode,"truncate")==0
    ){
      printf("Changing journal mode to DELETE from %s", zJMode);
      zJMode = "DELETE";
    }
#endif
    runSql("PRAGMA journal_mode=%Q;", zJMode);
  }
  if( !g.bSync ) trySql("PRAGMA synchronous=OFF");
  sqlite3_enable_load_extension(g.db, 1);
  sqlite3_busy_handler(g.db, busyHandler, 0);
  sqlite3_create_function(g.db, "vfsname", 0, SQLITE_UTF8, 0,
                          vfsNameFunc, 0, 0);
  sqlite3_create_function(g.db, "eval", 1, SQLITE_UTF8, 0,
                          evalFunc, 0, 0);
  g.iTimeout = DEFAULT_TIMEOUT;
  if( g.bSqlTrace ) sqlite3_trace(g.db, sqlTraceCallback, 0);
  if( iClient>0 ){
    if( n>0 ) unrecognizedArguments(argv[0], n, argv+2);
    if( g.iTrace ) logMessage("start-client");
    while(1){
      char *zTaskName = 0;
      rc = startScript(iClient, &zScript, &taskId, &zTaskName);
      if( rc==SQLITE_DONE ) break;
      if( g.iTrace ) logMessage("begin %s (%d)", zTaskName, taskId);
      runScript(iClient, taskId, zScript, zTaskName);
      if( g.iTrace ) logMessage("end %s (%d)", zTaskName, taskId);
      finishScript(iClient, taskId, 0);
      sqlite3_free(zTaskName);
      sqlite3_sleep(10);
    }
    if( g.iTrace ) logMessage("end-client");
  }else{
    sqlite3_stmt *pStmt;
    int iTimeout;
    if( n==0 ){
      fatalError("missing script filename");
    }
    if( n>1 ) unrecognizedArguments(argv[0], n, argv+2);
    runSql(
      "DROP TABLE IF EXISTS task;\n"
      "DROP TABLE IF EXISTS counters;\n"
      "DROP TABLE IF EXISTS client;\n"
      "CREATE TABLE task(\n"
      "  id INTEGER PRIMARY KEY,\n"
      "  name TEXT,\n"
      "  client INTEGER,\n"
      "  starttime DATE,\n"
      "  endtime DATE,\n"
      "  script TEXT\n"
      ");"
      "CREATE INDEX task_i1 ON task(client, starttime);\n"
      "CREATE INDEX task_i2 ON task(client, endtime);\n"
      "CREATE TABLE counters(nError,nTest);\n"
      "INSERT INTO counters VALUES(0,0);\n"
      "CREATE TABLE client(id INTEGER PRIMARY KEY, wantHalt);\n"
    );
    zScript = readFile(argv[2]);
    for(iRep=1; iRep<=nRep; iRep++){
      if( g.iTrace ) logMessage("begin script [%s] cycle %d\n", argv[2], iRep);
      runScript(0, 0, zScript, argv[2]);
      if( g.iTrace ) logMessage("end script [%s] cycle %d\n", argv[2], iRep);
    }
    sqlite3_free(zScript);
    waitForClient(0, 2000, "during shutdown...\n");
    trySql("UPDATE client SET wantHalt=1");
    sqlite3_sleep(10);
    g.iTimeout = 0;
    iTimeout = 1000;
    while( ((rc = trySql("SELECT 1 FROM client"))==SQLITE_BUSY
        || rc==SQLITE_ROW) && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    sqlite3_sleep(100);
    pStmt = prepareSql("SELECT nError, nTest FROM counters");
    iTimeout = 1000;
    while( (rc = sqlite3_step(pStmt))==SQLITE_BUSY && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    if( rc==SQLITE_ROW ){
      g.nError += sqlite3_column_int(pStmt, 0);
      g.nTest += sqlite3_column_int(pStmt, 1);
    }
    sqlite3_finalize(pStmt);
  }
  sqlite3_close(g.db);
  maybeClose(g.pLog);
  maybeClose(g.pErrLog);
  if( iClient==0 ){
    printf("Summary: %d errors out of %d tests\n", g.nError, g.nTest);
    printf("END: %s", argv[0]);
    for(i=1; i<argc; i++) printf(" %s", argv[i]);
    printf("\n");
  }
  return g.nError>0;
}
Esempio n. 16
0
//
// This is the LmUtility.nativeUtils method. It takes one string as
// input and produces one string as output. The output string gets
// written to the first element of the String[] array object passed in
// as the jobjectArray parameter.
//
// Although we do not document this method for customers, there is
// nothing preventing customer code from calling this method. So don't
// put anything in the method that you wouldn't want customers
// doing. Currently this function just serves as an entry point to
// various systems calls such as TMF operations and getting/setting
// environment variables. There is nothing here that customers could
// not do on their own if they wanted to.
//
JNIEXPORT void JNICALL Java_org_trafodion_sql_udr_LmUtility_nativeUtils
(JNIEnv * env, jclass jc, jstring js, jobjectArray joa)
{
  const char *input = env->GetStringUTFChars(js, NULL);
  if (input == NULL)
  {
    // OutOfMemory error already thrown
    return;
  }

  NAString action(input);
  TrimNAStringSpace(action);

  short error;
  NAString result("OK");

  static MXStatement staticStmt;

// LCOV_EXCL_START
  if (action.compareTo("GetTxName", NAString::ignoreCase) == 0)
  {
    Int64 transid;
    error = GETTRANSID((short *) &transid);
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "GETTRANSID returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result.data());
    }
    else
    {
      short actualLen;
      char text[256];
      error = TRANSIDTOTEXT(transid, text, 255, &actualLen);
      if (error)
      {
        result = "TRANSIDTOTEXT returned ";
        result += LongToNAString((Lng32) error);
        Throw(env, result);
      }
      else
      {
        text[actualLen] = 0;
        result = text;
      }
    }
  } // GetTxName

  else if (action.compareTo("BeginTx", NAString::ignoreCase) == 0)
  {
    Int32 tag;
    error = BEGINTRANSACTION(&tag);
    if (error)
    {
      result = "BEGINTRANSACTION returned ";
      result += LongToNAString((Lng32) error);
      Throw(env, result);
    }
  } // BeginTx

  else if (action.compareTo("CommitTx", NAString::ignoreCase) == 0)
  {
    error = ENDTRANSACTION();
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "ENDTRANSACTION returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result);
    }
  } // CommitTx

  else if (action.compareTo("RollbackTx", NAString::ignoreCase) == 0)
  {
    error = ABORTTRANSACTION();
    if (error)
    {
      if (error == 75)
      {
        result = "No active transaction";
      }
      else
      {
        result = "ABORTTRANSACTION returned ";
        result += LongToNAString((Lng32) error);
      }
      Throw(env, result);
    }
  } // RollbackTx

  else if (action.compareTo("GetProcessId", NAString::ignoreCase) == 0)
  {
    Lng32 pid = GETPID();
    result = LongToNAString(pid);
  } // GetProcessId

  else if (action.index("GetEnv ", 0, NAString::ignoreCase) == 0)
  {
    NAString name = action;
    name.remove(0, str_len("GetEnv "));
    TrimNAStringSpace(name);
    char *value = getenv(name.data());
    if (value != NULL)
    {
      result = value;
    }
    else
    {
      result = "";
    }
  } // GetEnv

  else if (action.index("PutEnv ", 0, NAString::ignoreCase) == 0)
  {
    NAString nameAndValue = action;
    nameAndValue.remove(0, str_len("PutEnv "));
    TrimNAStringSpace(nameAndValue);
    Int32 retcode = putenv((char *) nameAndValue.data());
    if (retcode != 0)
    {
      result = "putenv returned ";
      result += LongToNAString((Lng32) retcode);
      Throw(env, result);
    }
  } // PutEnv

  else if (action.index("LmDebug ", 0, NAString::ignoreCase) == 0)
  {
    NAString name = action;
    name.remove(0, str_len("LmDebug "));
    LM_DEBUG0(name.data());
  } // LmDebug

  else if (action.index("ExecSql ", 0, NAString::ignoreCase) == 0)
  {
    NAString stmtText = action.remove(0, str_len("ExecSql "));

    MXStatement s;
    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = s.init(status);
  
    if (retcode == 0)
    {
      retcode = s.prepare(stmtText.data());
      if (retcode != 0)
      {
        status = "PREPARE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.execute();
      if (retcode != 0)
      {
        status = "EXECUTE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.fetchEOD();
      if (retcode != 0)
      {
        status = "FETCH failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = s.close();
      if (retcode != 0)
      {
        status = "CLOSE failed";
      }
    }

    if (retcode != 0)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // ExecSql

  else if (action.index("FetchSql ", 0, NAString::ignoreCase) == 0)
  {
    // The incoming string is SQL statement text. The code below will
    // prepare and execute the statement then fetch only the first
    // row. It will build one long multi-line string containing all
    // column values, one on each line. The multi-line string can be
    // split by the Java caller into an array of Strings with the
    // split("\n") method.

    Lng32 i;
    NAString stmtText = action.remove(0, str_len("FetchSql "));

    MXStatement s;
    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = s.init(status);
  
    if (!retcode)
    {
      retcode = s.prepare(stmtText.data());
      if (retcode)
        status = "PREPARE failed";
    }
  
    if (!retcode)
    {
      retcode = s.execute();
      if (retcode)
        status = "EXECUTE failed";
    }

    Lng32 numOutColumns = s.getNumOutColumns();
    NABoolean stringsAllocated = FALSE;
    char **argv = NULL;

    if (!retcode && numOutColumns > 0)
    {
      argv = new char *[numOutColumns];
      Lng32 bufLen = 1000;
      for (i = 0; i < numOutColumns; i++)
        argv[i] = new char[bufLen + 1];

      stringsAllocated = TRUE;

      retcode = s.fetchStrings(argv, bufLen);
      if (retcode)
        status = "FETCH STRINGS failed";

      if (!retcode)
      {
        result = argv[0];
        for (i = 1; i < numOutColumns; i++)
        {
          result += "\n";
          result += argv[i];
        }
      }
    }
  
    if (!retcode)
    {
      retcode = s.fetchEOD();
      if (retcode)
        status = "FETCH EOD failed";
    }
  
    if (!retcode)
    {
      retcode = s.close();
      if (retcode)
        status = "CLOSE failed";
    }

    if (stringsAllocated)
    {
      for (i = 0; i < numOutColumns; i++)
        delete [] argv[i];
      delete [] argv;
    }

    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // FetchSql

  else if (action.index("Prepare ", 0, NAString::ignoreCase) == 0)
  {
    NAString stmtText = action.remove(0, str_len("Prepare "));

    const char *status = "OK";
    Lng32 retcode = 0;

    retcode = staticStmt.init(status);
  
    if (retcode == 0)
    {
      retcode = staticStmt.prepare(stmtText.data());
      if (retcode != 0)
      {
        status = "PREPARE failed";
      }
    }
  
    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }

  } // Prepare
  
  else if (action.index("ExecUsingString ", 0, NAString::ignoreCase) == 0)
  {
    NAString data = action.remove(0, str_len("ExecUsingString "));

    const char *status = "OK";
    Lng32 retcode = 0;

    if (retcode == 0)
    {
      retcode = staticStmt.executeUsingString(data.data(),
                                              (Lng32) data.length());
      if (retcode != 0)
      {
        status = "EXECUTE failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = staticStmt.fetchEOD();
      if (retcode != 0)
      {
        status = "FETCH failed";
      }
    }
  
    if (retcode == 0)
    {
      retcode = staticStmt.close();
      if (retcode != 0)
      {
        status = "CLOSE failed";
      }
    }

    if (retcode != 0)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // ExecUsingString

  else if (action.index("FetchUsingString ", 0, NAString::ignoreCase) == 0)
  {
    NAString data = action.remove(0, str_len("FetchUsingString "));
    const char *status = "OK";
    Lng32 retcode = 0;
    Int32 i = 0;

    if (!retcode)
    {
      retcode = staticStmt.executeUsingString(data.data(),
                                              (Lng32) data.length());
      if (retcode)
        status = "EXECUTE failed";
    }

    Lng32 numOutColumns = staticStmt.getNumOutColumns();
    NABoolean stringsAllocated = FALSE;
    char **argv = NULL;

    if (!retcode && numOutColumns > 0)
    {
      argv = new char *[numOutColumns];
      Lng32 bufLen = 1000;
      for (i = 0; i < numOutColumns; i++)
        argv[i] = new char[bufLen + 1];

      stringsAllocated = TRUE;

      retcode = staticStmt.fetchStrings(argv, bufLen);
      if (retcode)
        status = "FETCH STRINGS failed";

      if (!retcode)
      {
        result = argv[0];
        for (i = 1; i < numOutColumns; i++)
        {
          result += "\n";
          result += argv[i];
        }
      }
    }
  
    if (!retcode)
    {
      retcode = staticStmt.fetchEOD();
      if (retcode)
        status = "FETCH EOD failed";
    }
  
    if (!retcode)
    {
      retcode = staticStmt.close();
      if (retcode)
        status = "CLOSE failed";
    }

    if (stringsAllocated)
    {
      for (i = 0; i < numOutColumns; i++)
        delete [] argv[i];
      delete [] argv;
    }

    if (retcode)
    {
      char msg[256];
      sprintf(msg, "[UdrSqlException %d] %s", retcode, status);
      Throw(env, msg);
    }
  
  } // FetchUsingString

  else
  {
    //
    // Over time other operations can be supported
    //
    result = "Invalid action: ";
    result += action;
    Throw(env, result);
  }
// LCOV_EXCL_STOP

  //
  // Create the Java output string
  //
  if (env->ExceptionCheck() == JNI_FALSE)
  {
    jobject j = env->NewStringUTF(result.data());
    env->SetObjectArrayElement(joa, 0, j);
  }

}
Esempio n. 17
0
File: main.c Progetto: 1587/ltp
void *threadedMain(void *vtest)
#endif
{
#ifndef WINDOWS
	test_ll_t *test = (test_ll_t *) vtest;
#endif

	OFF_T *pVal1;
	unsigned char *data_buffer_unaligned = NULL;
	unsigned long ulRV;
	int i;
	unsigned char *sharedMem;

	extern unsigned short glb_run;
	extern int signal_action;

	test->args->pid = GETPID();

	init_gbl_data(test->env);

	if (make_assumptions(test->args) < 0) {
		TEXIT((uintptr_t) GETLASTERROR());
	}
	if (check_conclusions(test->args) < 0) {
		TEXIT((uintptr_t) GETLASTERROR());
	}
	if (test->args->flags & CLD_FLG_DUMP) {
		/*
		 * All we are doing is dumping filespec data to STDOUT, so
		 * we will do this here and be done.
		 */
		do_dump(test->args);
		TEXIT((uintptr_t) GETLASTERROR());
	} else {
		ulRV = init_data(test, &data_buffer_unaligned);
		if (ulRV != 0) {
			TEXIT(ulRV);
		}
		pVal1 = (OFF_T *) test->env->shared_mem;
	}

	pMsg(START, test->args, "Start args: %s\n", test->args->argstr);

	/*
	 * This loop takes care of passes
	 */
	do {
		test->env->pass_count++;
		test->env->start_time = time(NULL);
		if (test->args->flags & CLD_FLG_RPTYPE) {	/* force random data to be different each cycle */
			fill_buffer(test->env->data_buffer,
				    ((test->args->htrsiz * BLK_SIZE) * 2), NULL,
				    0, CLD_FLG_RPTYPE);
		}
		sharedMem = test->env->shared_mem;
		memset(sharedMem + BMP_OFFSET, 0, test->env->bmp_siz);
		if ((test->args->flags & CLD_FLG_LINEAR)
		    && !(test->args->flags & CLD_FLG_NTRLVD)) {
			linear_read_write_test(test);
		} else {
			/* we only reset the end time if not running a linear read / write test */
			test->env->end_time =
			    test->env->start_time + test->args->run_time;
			test->env->bContinue = TRUE;
			*(pVal1 + OFF_WLBA) = test->args->start_lba;
			test->args->test_state =
			    DIRCT_INC(test->args->test_state);
			test->args->test_state =
			    SET_wFST_TIME(test->args->test_state);
			test->args->test_state =
			    SET_rFST_TIME(test->args->test_state);
			if (test->args->flags & CLD_FLG_W) {
				test->env->lastAction.oper = WRITER;
				test->args->test_state =
				    SET_OPER_W(test->args->test_state);
			} else {
				test->env->lastAction.oper = READER;
				test->args->test_state =
				    SET_OPER_R(test->args->test_state);
			}
			memset(test->env->action_list, 0,
			       sizeof(action_t) * test->args->t_kids);
			test->env->action_list_entry = 0;
			test->env->wcount = 0;
			test->env->rcount = 0;

			if (test->args->flags & CLD_FLG_CYC)
				if (test->args->cycles == 0) {
					pMsg(INFO, test->args,
					     "Starting pass %lu\n",
					     (unsigned long)test->env->
					     pass_count);
				} else {
					pMsg(INFO, test->args,
					     "Starting pass %lu of %lu\n",
					     (unsigned long)test->env->
					     pass_count, test->args->cycles);
			} else {
				pMsg(INFO, test->args, "Starting pass\n");
			}

			CreateTestChild(ChildTimer, test);
			for (i = 0; i < test->args->t_kids; i++) {
				CreateTestChild(ChildMain, test);
			}
			/* Wait for the children to finish */
			cleanUpTestChildren(test);
		}

		update_cyc_stats(test->env);
		if ((test->args->flags & CLD_FLG_CYC)
		    && (test->args->flags & CLD_FLG_PCYC)) {
			print_stats(test->args, test->env, CYCLE);
		}
		update_gbl_stats(test->env);

		if (signal_action & SIGNAL_STOP) {
			break;
		}		/* user request to stop */
		if ((glb_run == 0)) {
			break;
		}
		/* global request to stop */
		if (!(test->args->flags & CLD_FLG_CYC)) {
			break;	/* leave, unless cycle testing */
		} else {
			if ((test->args->cycles > 0)
			    && (test->env->pass_count >= test->args->cycles)) {
				break;	/* leave, cycle testing complete */
			}
		}
	} while (TST_STS(test->args->test_state));
	print_stats(test->args, test->env, TOTAL);

	FREE(data_buffer_unaligned);
	FREE(test->env->shared_mem);
#ifdef WINDOWS
	CloseHandle(OpenMutex(SYNCHRONIZE, TRUE, "gbl"));
	CloseHandle(OpenMutex(SYNCHRONIZE, TRUE, "data"));
#endif

	if (TST_STS(test->args->test_state)) {
		if (signal_action & SIGNAL_STOP) {
			pMsg(END, test->args,
			     "User Interrupt: Test Done (Passed)\n");
		} else {
			pMsg(END, test->args, "Test Done (Passed)\n");
		}
	} else {
		if (signal_action & SIGNAL_STOP) {
			pMsg(END, test->args,
			     "User Interrupt: Test Done (Failed)\n");
		} else {
			pMsg(END, test->args, "Test Done (Failed)\n");
		}
	}
	TEXIT((uintptr_t) GETLASTERROR());
}
Esempio n. 18
0
int sqlite_test()
{
  const char *zClient;
  int iClient;
  int n, i;
  int openFlags = SQLITE_OPEN_READWRITE;
  int rc;
  char *zScript;
  int taskId;
  const char *zTrace;
  const char *zCOption;

  g.argv0 = argv[0];
  g.iTrace = 1;
  if( argc<2 ) usage(argv[0]);
  g.zDbFile = argv[1];
  if( strglob("*.test", g.zDbFile) ) usage(argv[0]);
  if( strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID)!=0 ){
    fprintf(stderr, "SQLite library and header mismatch\n"
                    "Library: %s\n"
                    "Header:  %s\n",
                    sqlite3_sourceid(), SQLITE_SOURCE_ID);
    exit(1);
  }
  n = argc-2;
  sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.mptest", GETPID());
  g.zVfs = findOption(argv+2, &n, "vfs", 1);
  zClient = findOption(argv+2, &n, "client", 1);
  g.zErrLog = findOption(argv+2, &n, "errlog", 1);
  g.zLog = findOption(argv+2, &n, "log", 1);
  zTrace = findOption(argv+2, &n, "trace", 1);
  if( zTrace ) g.iTrace = atoi(zTrace);
  if( findOption(argv+2, &n, "quiet", 0)!=0 ) g.iTrace = 0;
  g.bSqlTrace = findOption(argv+2, &n, "sqltrace", 0)!=0;
  g.bSync = findOption(argv+2, &n, "sync", 0)!=0;
  if( g.zErrLog ){
    g.pErrLog = fopen(g.zErrLog, "a");
  }else{
    g.pErrLog = stderr;
  }
  if( g.zLog ){
    g.pLog = fopen(g.zLog, "a");
  }else{
    g.pLog = stdout;
  }
  
  sqlite3_config(SQLITE_CONFIG_LOG, sqlErrorCallback, 0);
  if( zClient ){
    iClient = atoi(zClient);
    if( iClient<1 ) fatalError("illegal client number: %d\n", iClient);
    sqlite3_snprintf(sizeof(g.zName), g.zName, "%05d.client%02d",
                     GETPID(), iClient);
  }else{
    if( g.iTrace>0 ){
      printf("With SQLite " SQLITE_VERSION " " SQLITE_SOURCE_ID "\n" );
      for(i=0; (zCOption = sqlite3_compileoption_get(i))!=0; i++){
        printf("-DSQLITE_%s\n", zCOption);
      }
      fflush(stdout);
    }
    iClient =  0;
    unlink(g.zDbFile);
    openFlags |= SQLITE_OPEN_CREATE;
  }
  rc = sqlite3_open_v2(g.zDbFile, &g.db, openFlags, g.zVfs);
  if( rc ) fatalError("cannot open [%s]", g.zDbFile);
  sqlite3_enable_load_extension(g.db, 1);
  sqlite3_busy_handler(g.db, busyHandler, 0);
  sqlite3_create_function(g.db, "vfsname", 0, SQLITE_UTF8, 0,
                          vfsNameFunc, 0, 0);
  sqlite3_create_function(g.db, "eval", 1, SQLITE_UTF8, 0,
                          evalFunc, 0, 0);
  g.iTimeout = DEFAULT_TIMEOUT;
  if( g.bSqlTrace ) sqlite3_trace(g.db, sqlTraceCallback, 0);
  if( !g.bSync ) trySql("PRAGMA synchronous=OFF");
  if( iClient>0 ){
    if( n>0 ) unrecognizedArguments(argv[0], n, argv+2);
    if( g.iTrace ) logMessage("start-client");
    while(1){
      char *zTaskName = 0;
      rc = startScript(iClient, &zScript, &taskId, &zTaskName);
      if( rc==SQLITE_DONE ) break;
      if( g.iTrace ) logMessage("begin %s (%d)", zTaskName, taskId);
      runScript(iClient, taskId, zScript, zTaskName);
      if( g.iTrace ) logMessage("end %s (%d)", zTaskName, taskId);
      finishScript(iClient, taskId, 0);
      sqlite3_free(zTaskName);
      sqlite3_sleep(10);
    }
    if( g.iTrace ) logMessage("end-client");
  }else{
    sqlite3_stmt *pStmt;
    int iTimeout;
    if( n==0 ){
      fatalError("missing script filename");
    }
    if( n>1 ) unrecognizedArguments(argv[0], n, argv+2);
    runSql(
      "CREATE TABLE task(\n"
      "  id INTEGER PRIMARY KEY,\n"
      "  name TEXT,\n"
      "  client INTEGER,\n"
      "  starttime DATE,\n"
      "  endtime DATE,\n"
      "  script TEXT\n"
      ");"
      "CREATE INDEX task_i1 ON task(client, starttime);\n"
      "CREATE INDEX task_i2 ON task(client, endtime);\n"
      "CREATE TABLE counters(nError,nTest);\n"
      "INSERT INTO counters VALUES(0,0);\n"
      "CREATE TABLE client(id INTEGER PRIMARY KEY, wantHalt);\n"
    );
    zScript = readFile(argv[2]);
    if( g.iTrace ) logMessage("begin script [%s]\n", argv[2]);
    runScript(0, 0, zScript, argv[2]);
    sqlite3_free(zScript);
    if( g.iTrace ) logMessage("end script [%s]\n", argv[2]);
    waitForClient(0, 2000, "during shutdown...\n");
    trySql("UPDATE client SET wantHalt=1");
    sqlite3_sleep(10);
    g.iTimeout = 0;
    iTimeout = 1000;
    while( ((rc = trySql("SELECT 1 FROM client"))==SQLITE_BUSY
        || rc==SQLITE_ROW) && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    sqlite3_sleep(100);
    pStmt = prepareSql("SELECT nError, nTest FROM counters");
    iTimeout = 1000;
    while( (rc = sqlite3_step(pStmt))==SQLITE_BUSY && iTimeout>0 ){
      sqlite3_sleep(10);
      iTimeout -= 10;
    }
    if( rc==SQLITE_ROW ){
      g.nError += sqlite3_column_int(pStmt, 0);
      g.nTest += sqlite3_column_int(pStmt, 1);
    }
    sqlite3_finalize(pStmt);
  }
  sqlite3_close(g.db);  
  maybeClose(g.pLog);
  maybeClose(g.pErrLog);
  if( iClient==0 ){
    printf("Summary: %d errors in %d tests\n", g.nError, g.nTest);
  }
  return g.nError>0;
}