int
main(int argc,char *argv[]){

   volatile int fd;
   volatile off_t off;

  if(argc != 3 || strcmp(argv[1],"--help")==0)
    usageExit("%s pathname offset\n",argv[0]);

  fd = open(argv[1],O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  if(fd == -1)
    errnoExit("open()");


  off = atoll(argv[2]);

  if(lseek(fd,off,SEEK_SET) == -1)
    errnoExit("lseek()");

  #define TEST_SIZE 4
  if(write(fd,"test",TEST_SIZE) != TEST_SIZE)
    errnoExit("write()");

  if(close(fd) == -1)
    errnoExit("close()");

  exit(EXIT_SUCCESS);




}
static void addMacroReplacements(MAC_HANDLE *macPvt,char *pval)
{
    char **pairs;
    long status;

    status = macParseDefns(macPvt,pval,&pairs);
    if(!status) {
        fprintf(stderr,"Error macParseDefns error\n");
        usageExit();
    }
    status = macInstallMacros(macPvt,pairs);
    if(!status) {
        fprintf(stderr,"Error macInstallMacros error\n");
        usageExit();
    }
    free((void *)pairs);
}
Example #3
0
static void parse_arguments(int argc, char* argv[], 
                            struct cloudfs_state *state) {
    // Default Values
    strcpy(state->ssd_path, "/mnt/ssd/");
    strcpy(state->fuse_path, "/mnt/fuse/");
    strcpy(state->hostname, "localhost:8888");
    state->ssd_size = 1024*1024*1024;
    state->threshold = 64*1024;

    state->no_dedup = 0;
    state->avg_seg_size = 4096;
    state->rabin_window_size = 48;

    state->no_cache = 0;
    state->cache_size = 32*1024*1024;
    state->no_compress = 0;

    // Parse args
    while (1) {
        int idx = 0;
        int c = getopt_long(argc, argv, "s:f:h:a:t:dS:w:oc:z:", longOptionsG, &idx);

        if (c == -1) {
            // End of options
            break;
        }

        switch (c) {
        case 's':
            strcpy(state->ssd_path, optarg);
            break;
        case 'f':
            strcpy(state->fuse_path, optarg);
            break;
        case 'h':
            strcpy(state->hostname, optarg);
            break;
        case 'a': 
            state->ssd_size = atoi(optarg)*1024;
            break; 
       case 't': 
            state->threshold = atoi(optarg)*1024;
            break;
       case 'd':
            state->no_dedup = 1;
            break;
       case 'S': 
            state->avg_seg_size = atoi(optarg)*1024;
            break;
       case 'w': 
            state->rabin_window_size = atoi(optarg);
            break;
       case 'o':
            state->no_cache = 1;
            break;
       case 'c':
            state->cache_size = atoi(optarg)*1024;
            break;
       case 'z':
            state->no_compress = 1;
            break;
        default:
            fprintf(stderr, "\nERROR: Unknown option: -%c\n", c);
            // Usage exit
            usageExit(stderr);
        }
    }
}
Example #4
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

  unsigned int cmd, glhandle, gltarget, direction, flags, keepmapped, ispbo;
  unsigned long nrbytes;
  void *gpuptr;
  int slot = 0;
  cudaGraphicsResource_t resource = NULL;
  struct cudaArray *mappedArray = NULL;
  void* mappedPtr = NULL;
  size_t mappedSize = 0;

  /* Be optimistic, assume success unless told otherwise: */
  cudastatus = cudaSuccess;
  
  if (firsttime) {
      firsttime = 0;

      mexPrintf("\n%s: A simple CUDA <=> OpenGL interoperation interface.\n", mexFunctionName());
      mexPrintf("(c) 2013 by Mario Kleiner. Licensed to you under the MIT license.\n\n");

      /* Reset cache clock to zero and clear the cache: */
      cacheclock = 0;
      memset(resourceCache, 0, sizeof(resourceCache[0]) * MAX_CACHE_SLOTS);

      /* Start off with an effective cache capacity of 8 slots (1 slot is blocked from use): */
      cachesize = 8 + 1;
      firstLRUCycle = 1;

      /* Make sure the cache is flushed at mex file shutdown time: */
      mexAtExit(mexExit);
  }
  
  /* Retrieve command code: Give usage info if none given. */
  if (nrhs < 1) { usageExit(0); return; }

  cmd = (unsigned int) mxGetScalar(prhs[0]);

  /* Change of verbosity? */
  if (cmd == 6) {
    if (nrhs < 2) usageExit(1);  
    verbose = (unsigned int) mxGetScalar(prhs[1]);
    if (verbose) mexPrintf("\n%s: Verbose tracing of operations enabled.\n", mexFunctionName());
    return;
  }

  /* Resizing the LRU cache requested? */
  if (cmd == 5) {
    if (nrhs < 2) usageExit(1);

    /* Reset LRU cache full warning: */
    firstLRUCycle = 1;
    
    slot = (unsigned int) mxGetScalar(prhs[1]);
    
    /* Increment request by 1 to compensate for the "lost" slot 0: */
    slot = slot + 1;
    
    /* Child protections: */
    if (slot > MAX_CACHE_SLOTS) {
      mexPrintf("%s: Requested new softlimit %i for cache exceeds compiled in maximum %i. Will clamp to maximum.\n", mexFunctionName(), slot - 1, MAX_CACHE_SLOTS - 1);
      cachesize = MAX_CACHE_SLOTS;
      return;
    }
    
    if (slot < cachesize) {
      /* Shrinking the cache requested. This implies a full cache flush: */
      mexPrintf("%s: Requested new softlimit %i for cache is smaller than old softlimit %i. Will flush the cache before shrinking it.\n", mexFunctionName(), slot - 1, cachesize - 1);
      cacheFlush();
    }
    
    /* Set new softlimit: */
    cachesize = slot;
    mexPrintf("%s: New softlimit for LRU cache set to %i slots.\n", mexFunctionName(), cachesize - 1);
    
    return;
  }

  if (cmd == 0) {
    /* Cache flush requested: */
    cacheFlush();
    return;
  }

  /* Following ops require at least object handle and target type: */
  if (nrhs < 3) usageExit(1);

  /* Time to increment the age of our cached items by a clock tick: */
  ageCache();

  /* Retrieve OpenGL object handle to our image buffer: */
  glhandle = (unsigned int) mxGetScalar(prhs[1]);

  /* Get GLEnum target: */
  gltarget = (unsigned int) mxGetScalar(prhs[2]);
  
  if (cmd == 1) {
    /* Unmap resource if it is mapped: */
    unmapResource(glhandle, gltarget);
    return;
  }

  if (cmd == 2) {
    /* Unmap and unregister resource if it is mapped and/or registered: */
    unregisterResource(glhandle, gltarget);
    return;
  }

  if (nrhs < 6) usageExit(1);

  /* Retrieve CUDA memory pointer to source/destination CUDA memory buffer: */
  gpuptr = (void*) (unsigned long) mxGetScalar(prhs[3]);
  
  /* Retrieve number of bytes to copy: */
  nrbytes = (unsigned long) mxGetScalar(prhs[4]);
  
  /* Retrieve direction: 0 = OpenGL -> CUDA, 1 = CUDA -> OpenGL : */
  direction = (unsigned int) mxGetScalar(prhs[5]);

  /* Retrieve optional 'keepmapped' flag. */
  keepmapped = 0;
  if (nrhs >= 7) keepmapped = (unsigned int) mxGetScalar(prhs[6]);

  /* Define CUDA optimization flags, depending if this is a OpenGL->CUDA or
   * CUDA->OpenGL copy operation.
   */
  if ((nrhs >= 8) && (mxGetScalar(prhs[7]) >= 0)) {
    /* Override map flags provided. Use them: */
    flags = (unsigned int) mxGetScalar(prhs[7]);
  }
  else {
    /* Use auto-selected map flags: */
    flags = (direction) ? cudaGraphicsRegisterFlagsWriteDiscard : cudaGraphicsRegisterFlagsReadOnly;
  }

  /* Is gltarget a OpenGL pixelbuffer object? Check for gltarget == GL_PACK_BUFFER or GL_UNPACK_BUFFER. */
  ispbo = (gltarget == 35051 || gltarget == 35052) ? 1 : 0;

  /* Copy of data or mapped resource access pointer requested? */
  if (cmd == 3 || cmd == 4) {
    /* Register OpenGL object with CUDA as 'resource': */
    
    /* Already in cache? This would mean it is registered already with compatible mapping flags: */
    slot = cacheInsert(glhandle, gltarget, flags);
    if (slot < 0) {
      /* Not yet in cache. This means it is not registered at this time, either because it
         wasn't registered at all, or because it was registered with incompatible 'flags',
         so it just got unregistered and expelled from the cache. In any case, we need to
         insert it into the cache and register it. -slot is the free target slot for this
         purpose.
       */
       
      /* Turn slot into something useful: */
      slot = -slot;
    
      if (ispbo) {
        /* OpenGL Pixelbuffer object (GL_PACK_BUFFER or GL_UNPACK_BUFFER): */
        cudastatus = cudaGraphicsGLRegisterBuffer(&(resourceCache[slot].resource), glhandle, flags);
      }
      else {
        /* OpenGL texture or renderbuffer object: */
        cudastatus = cudaGraphicsGLRegisterImage(&(resourceCache[slot].resource), glhandle, gltarget, flags);
      }
      
      if (cudastatus != cudaSuccess) {
        mexPrintf("\nmemcpyCudaOpenGL: ERROR in %s(): %s\n", (ispbo) ? "cudaGraphicsGLRegisterBuffer" : "cudaGraphicsGLRegisterImage", cudaGetErrorString(cudastatus));
        resourceCache[slot].resource = NULL;
        goto err_final;
      }

      if (verbose) mexPrintf("\n%s: cacheInsert(%i): CUDA resource registered (globject %i, gltarget %i, flags %i).\n", mexFunctionName(), slot, glhandle, gltarget, flags);
      
      /* Fill cache slot: */
      resourceCache[slot].glhandle = glhandle;
      resourceCache[slot].gltarget = gltarget;
      resourceCache[slot].mapflags = flags;
      resourceCache[slot].lastaccess = cacheclock;
      resourceCache[slot].ismapped = 0;
    }
      
    /* At this point, the resource is stored in slot 'slot' of the cache and registered in a compatible way: */
    
    /* Map the 'resource', unless it is already mapped: */
    if (!resourceCache[slot].ismapped) {
      /* Map it: */
      cudastatus = cudaGraphicsMapResources(1, &(resourceCache[slot].resource), 0);
      if (cudastatus != cudaSuccess) {
        mexPrintf("\nmemcpyCudaOpenGL: ERROR in cudaGraphicsMapResources(): %s\n", cudaGetErrorString(cudastatus));
        goto err_unregister;
      }

      if (verbose) mexPrintf("\n%s: CUDA resource %i mapped (globject %i, gltarget %i, flags %i).\n", mexFunctionName(), slot, glhandle, gltarget, flags);
      
      /* Successfully mapped: */
      resourceCache[slot].ismapped = 1;
    }
    
    /* Get simpler handle: */
    resource = resourceCache[slot].resource;
    
    /* Get mapped resource image array handle or PBO pointer: */
    if (ispbo) {
      cudastatus = cudaGraphicsResourceGetMappedPointer(&mappedPtr, &mappedSize, resource);
    }
    else {
      cudastatus = cudaGraphicsSubResourceGetMappedArray(&mappedArray, resource, 0, 0);
    }
    
    if (cudastatus != cudaSuccess) {
      mexPrintf("\nmemcpyCudaOpenGL: ERROR in %s(): %s\n", (ispbo) ? "cudaGraphicsResourceGetMappedPointer" : "cudaGraphicsSubResourceGetMappedArray", cudaGetErrorString(cudastatus));
      goto err_unmap;
    }
  }
  
  /* Copy of PBO data between CUDA and OpenGL requested? */
  if (cmd == 3 && ispbo) {
    /* Copy from OpenGL PBO to CUDA buffer? */
    if (direction == 0) {
        /* OpenGL -> CUDA copy: */
        cudastatus = cudaMemcpyAsync(gpuptr, (const void*) mappedPtr, (size_t) nrbytes, cudaMemcpyDeviceToDevice, 0);
        if (cudastatus != cudaSuccess) {
            mexPrintf("\nmemcpyCudaOpenGL: ERROR in cudaMemcpyAsync(): %s\n", cudaGetErrorString(cudastatus));
            goto err_unmap;
        }
    }

    if (direction == 1) {
        /* CUDA -> OpenGL copy: */
        cudastatus = cudaMemcpyAsync(mappedPtr, (const void*) gpuptr, (size_t) nrbytes, cudaMemcpyDeviceToDevice, 0);
        if (cudastatus != cudaSuccess) {
            mexPrintf("\nmemcpyCudaOpenGL: ERROR in cudaMemcpyAsync(): %s\n", cudaGetErrorString(cudastatus));
            goto err_unmap;
        }
    }
  }

  /* Copy of texture or renderbuffer data between CUDA and OpenGL requested? */
  if (cmd == 3 && !ispbo) {
    /* Copy from OpenGL object to CUDA buffer? */
    if (direction == 0) {
        /* OpenGL -> CUDA copy: */
        cudastatus = cudaMemcpyFromArrayAsync(gpuptr, (const struct cudaArray*) mappedArray, 0, 0, (size_t) nrbytes, cudaMemcpyDeviceToDevice, 0);
        if (cudastatus != cudaSuccess) {
            mexPrintf("\nmemcpyCudaOpenGL: ERROR in cudaMemcpyFromArray(): %s\n", cudaGetErrorString(cudastatus));
            goto err_unmap;
        }
    }

    if (direction == 1) {
        /* CUDA -> OpenGL copy: */
        cudastatus = cudaMemcpyToArrayAsync((struct cudaArray*) mappedArray, 0, 0, (const void*) gpuptr, (size_t) nrbytes, cudaMemcpyDeviceToDevice, 0);
        if (cudastatus != cudaSuccess) {
            mexPrintf("\nmemcpyCudaOpenGL: ERROR in cudaMemcpyToArray(): %s\n", cudaGetErrorString(cudastatus));
            goto err_unmap;
        }
    }
  }
  
  /* Return of pointers to mapped resource requested? */
  if (cmd == 4) {
    /* Yes: This implies we must not unmap the resource now, as otherwise the
     * returned pointers would be dead on arrival.
     */
    keepmapped = 1;
    
    /* Cast pointer to void* then store it in a 64-Bit unsigned integer return value: */
    plhs[0] = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
    *((unsigned long long*) mxGetData(plhs[0])) = (unsigned long long) (void*) ((ispbo) ? mappedPtr : mappedArray);
  }
  
  /* Keep resource mapped? */
  if (slot && !keepmapped) doCudaUnmap(slot);
  
  /* Successfully completed: */
  return;
  
  /* Error handling -- Unwind in reverse order: */
  
err_unmap:
  
  /* Unmap the 'resource': */
  unmapResource(glhandle, gltarget);

err_unregister:
  
  /* Unregister the 'resource': */
  unregisterResource(glhandle, gltarget);

err_final:      
      
  if (cudastatus != cudaSuccess) mexErrMsgTxt("Error in memcpyCudaOpenGL(), reason see above.");
}
int main(int argc,char **argv)
{
    void *inputPvt;
    MAC_HANDLE *macPvt;
    char *pval;
    int  narg;
    char *substitutionName=0;
    char *templateName=0;
    int  i;

    inputConstruct(&inputPvt);
    macCreateHandle(&macPvt,0);
    macSuppressWarning(macPvt,1);
    while((argc>1) && (argv[1][0] == '-')) {
	narg = (strlen(argv[1])==2) ? 2 : 1;
	pval = (narg==1) ? (argv[1]+2) : argv[2];
	if(strncmp(argv[1],"-I",2)==0) {
	    inputAddPath(inputPvt,pval);
	} else if(strncmp(argv[1],"-o",2)==0) {
	    if(freopen(pval,"w",stdout)==NULL) {
            fprintf(stderr,"Can't open %s for writing: %s\n", pval, strerror(errno));
            exit(1);
        }
	} else if(strncmp(argv[1],"-M",2)==0) {
	    addMacroReplacements(macPvt,pval);
	} else if(strncmp(argv[1],"-S",2)==0) {
	    substitutionName = calloc(strlen(pval)+1,sizeof(char));
	    strcpy(substitutionName,pval);
	} else if(strncmp(argv[1],"-V",2)==0) {
	    macSuppressWarning(macPvt,0);
	    narg = 1; /* no argument for this option */
	} else {
	    usageExit();
	}
	argc -= narg;
	for(i=1; i<argc; i++) argv[i] = argv[i + narg];
    }
    if(argc>2) {
	fprintf(stderr,"too many filename arguments\n");
	usageExit();
    }
    if(argc==2) {
        templateName = calloc(strlen(argv[1])+1,sizeof(char));
        strcpy(templateName,argv[1]);
    }
    if(!substitutionName) {
	makeSubstitutions(inputPvt,macPvt,templateName);
    } else {
	void *substitutePvt;
        char *filename = 0;

	substituteOpen(&substitutePvt,substitutionName);
        while(substituteGetNextSet(substitutePvt,&filename)) {
            if(templateName) filename = templateName;
            if(!filename) {
	        fprintf(stderr,"no template file\n");
	        usageExit();
            }
            macPushScope(macPvt);
	    while((pval = substituteGetReplacements(substitutePvt))){
	        addMacroReplacements(macPvt,pval);
	        makeSubstitutions(inputPvt,macPvt,filename);
	    }
            macPopScope(macPvt);
        }
        substituteDestruct(substitutePvt);
    }
    inputDestruct(inputPvt);
    free((void *)templateName);
    free((void *)substitutionName);
    return(exitStatus);
}
Example #6
0
static int processArgs( int argc, char **argv, 
						int *argFlags, const char **zargPtrPtr )
	{
	const char *zargPtr = NULL;
	BOOLEAN moreArgs = TRUE;

	/* Clear return value */
	*argFlags = 0;
	*zargPtrPtr = NULL;

	/* No args means test everything */
	if( argc <= 0 )
		{
		*argFlags = DO_ALL;

		return( TRUE );
		}

	/* Check for arguments */
	while( argc > 0 && *argv[ 0 ] == '-' && moreArgs )
		{
		const char *argPtr = argv[ 0 ] + 1;

		while( *argPtr )
			{
			switch( toupper( *argPtr ) )
				{
				case '-':
					moreArgs = FALSE;	/* GNU-style end-of-args flag */
					break;

				case 'B':
					*argFlags |= DO_SELFTEST;
					break;

				case 'C':
					*argFlags |= DO_CERT;
					break;

				case 'D':
					*argFlags |= DO_DEVICE;
					break;

				case 'E':
					*argFlags |= DO_ENVELOPE;
					break;

				case 'F':
					*argFlags |= DO_KEYSETFILE;
					break;

				case 'H':
					usageExit();
					break;

				case 'I':
					*argFlags |= DO_HIGHLEVEL;
					break;

				case 'K':
					*argFlags |= DO_KEYSETDBX;
					break;

				case 'L':
					*argFlags |= DO_LOWLEVEL;
					break;

				case 'M':
					*argFlags |= DO_MIDLEVEL;
					break;

				case 'O':
					*argFlags |= DO_CONFIG;
					break;

				case 'P':
					*argFlags |= DO_CERTPROCESS;
					break;

				case 'R':
					*argFlags |= DO_RANDOM;
					break;

				case 'S':
					*argFlags |= DO_SESSION;
					break;

				case 'T':
					*argFlags |= DO_SESSIONLOOPBACK;
					break;

				case 'U':
					*argFlags |= DO_USER;
					break;

				case 'Z':
					zargPtr = argPtr + 1;
					if( *zargPtr == '\0' )
						{
						puts( "Error: Missing argument for -z option." );
						return( FALSE );
						}
					while( argPtr[ 1 ] )
						argPtr++;	/* Skip rest of arg */
					*zargPtrPtr = zargPtr;
					break;

				default:
					printf( "Error: Unknown argument '%c'.\n", *argPtr );
					return( FALSE );
				}
			argPtr++;
			}
		argv++;
		argc--;
		}
	if( argc > 0 )
		{
		printf( "Error: Unknown argument '%s'.\n", argv[ 0 ] );
		return( FALSE );
		}

	return( TRUE );
	}
int main( int argc, char **argv )
	{
	const char *zargPtr = NULL;
	BOOLEAN doSelftest = FALSE, doLowlevel = FALSE, doRandom = FALSE;
	BOOLEAN doConfig = FALSE, doMidlevel = FALSE, doCert = FALSE;
	BOOLEAN doKeyset = FALSE, doCertprocess = FALSE, doHighlevel = FALSE;
	BOOLEAN doEnvelope = FALSE, doSession = FALSE, doSessionLoopback = FALSE;
	BOOLEAN doAll = FALSE, moreArgs = TRUE;
	BOOLEAN sessionTestError = FALSE, loopbackTestError = FALSE;
	int status;
	void testSystemSpecific1( void );
	void testSystemSpecific2( void );

	/* Print a general banner to let the user know what's going on */
	printf( "testlib - cryptlib %d-bit self-test framework.\n", 
			sizeof( long ) * 8 );
	puts( "Copyright Peter Gutmann 1995 - 2010." );
	puts( "" );

	/* Skip the program name */
	argv++; argc--;

	/* No args means test everything */
	if( argc <= 0 )
		doAll = TRUE;

	/* Check for arguments */
	while( argc > 0 && *argv[ 0 ] == '-' && moreArgs )
		{
		const char *argPtr = argv[ 0 ] + 1;

		while( *argPtr )
			{
			switch( toupper( *argPtr ) )
				{
				case '-':
					moreArgs = FALSE;	/* GNU-style end-of-args flag */
					break;

				case 'B':
					doSelftest = TRUE;
					break;

				case 'C':
					doCert = TRUE;
					break;

				case 'E':
					doEnvelope = TRUE;
					break;

				case 'F':
					doSessionLoopback = TRUE;
					break;

				case 'H':
					usageExit();
					break;

				case 'I':
					doHighlevel = TRUE;
					break;

				case 'K':
					doKeyset = TRUE;
					break;

				case 'L':
					doLowlevel = TRUE;
					break;

				case 'M':
					doMidlevel = TRUE;
					break;

				case 'O':
					doConfig = TRUE;
					break;

				case 'P':
					doCertprocess = TRUE;
					break;

				case 'R':
					doRandom = TRUE;
					break;

				case 'S':
					doSession = TRUE;
					break;

				case 'Z':
					zargPtr = argPtr + 1;
					if( *zargPtr == '\0' )
						{
						puts( "Error: Missing argument for -z option." );
						exit( EXIT_FAILURE );
						}
					while( argPtr[ 1 ] )
						argPtr++;	/* Skip rest of arg */
					break;

				default:
					printf( "Error: Unknown argument '%c'.\n", *argPtr );
					return( EXIT_FAILURE );
				}
			argPtr++;
			}
		argv++;
		argc--;
		}

#ifdef USE_TCHECK
	THREAD_DEBUG_SUSPEND();
#endif /* USE_TCHECK */

	/* Make sure that various system-specific features are set right */
	testSystemSpecific1();

	/* VisualAge C++ doesn't set the TZ correctly.  The check for this isn't
	   as simple as it would seem since most IBM compilers define the same
	   preprocessor values even though it's not documented anywhere, so we
	   have to enable the tzset() call for (effectively) all IBM compilers
	   and then disable it for ones other than VisualAge C++ */
#if ( defined( __IBMC__ ) || defined( __IBMCPP__ ) ) && !defined( __VMCMS__ )
	tzset();
#endif /* VisualAge C++ */

	/* Initialise cryptlib */
	printf( "Initialising cryptlib..." );
	status = cryptInit();
	if( cryptStatusError( status ) )
		{
		printf( "\ncryptInit() failed with error code %d, line %d.\n", 
				status, __LINE__ );
		exit( EXIT_FAILURE );
		}
	puts( "done." );

#ifndef TEST_RANDOM
	/* In order to avoid having to do a randomness poll for every test run,
	   we bypass the randomness-handling by adding some junk.  This is only
	   enabled when cryptlib is built in debug mode so it won't work with 
	   any production systems */
  #if defined( __MVS__ ) || defined( __VMCMS__ )
	#pragma convlit( resume )
	cryptAddRandom( "xyzzy", 5 );
	#pragma convlit( suspend )
  #else
	cryptAddRandom( "xyzzy", 5 );
  #endif /* Special-case EBCDIC handling */
#endif /* TEST_RANDOM */

	/* Perform a general sanity check to make sure that the self-test is
	   being run the right way */
	if( !checkFileAccess() )
		goto errorExit;

	/* Make sure that further system-specific features that require cryptlib 
	   to be initialised to check are set right */
#ifndef _WIN32_WCE
	testSystemSpecific2();
#endif /* WinCE */

#ifdef USE_TCHECK
	THREAD_DEBUG_RESUME();
#endif /* USE_TCHECK */

	/* For general testing purposes we can insert test code at this point to
	   test special cases that aren't covered in the general tests below */
	testKludge( zargPtr );

#ifdef SMOKE_TEST
	/* Perform a general smoke test of the kernel */
	smokeTest();
#endif /* SMOKE_TEST */

	/* Test each block of cryptlib functionality */
	if( ( doSelftest || doAll ) && !testSelfTest() )
		goto errorExit;
	if( ( doLowlevel || doAll ) && !testLowLevel() )
		goto errorExit;
	if( ( doRandom || doAll ) && !testRandom() )
		goto errorExit;
	if( ( doConfig || doAll ) && !testConfig() )
		goto errorExit;
	if( ( doSelftest || doAll ) && !testDevice() )
		goto errorExit;
	if( ( doMidlevel || doAll ) && !testMidLevel() )
		goto errorExit;
	if( ( doCert || doAll ) && !testCert() )
		goto errorExit;
	if( ( doKeyset || doAll ) && !testKeyset() )
		goto errorExit;
	if( ( doCertprocess || doAll ) && !testCertMgmt() )
		goto errorExit;
	if( ( doHighlevel || doAll ) && !testHighLevel() )
		goto errorExit;
	if( ( doEnvelope || doAll ) && !testEnveloping() )
		goto errorExit;
	if( ( doSession || doAll ) && !testSessions() )
		{
		sessionTestError = TRUE;
		goto errorExit;
		}
	if( ( doSessionLoopback || doAll ) && !testSessionsLoopback() )
		{
		loopbackTestError = TRUE;
		goto errorExit;
		}
	if( ( doAll ) && !testUsers() )
		goto errorExit;

	/* Shut down cryptlib */
	status = cryptEnd();
	if( cryptStatusError( status ) )
		{
		if( status == CRYPT_ERROR_INCOMPLETE )
			{
			puts( "cryptEnd() failed with error code CRYPT_ERROR_INCOMPLETE, "
				  "a code path in the\nself-test code resulted in an error "
				  "return without a full cleanup of objects.\nIf you were "
				  "running the multithreaded loopback tests this may be "
				  "because one\nor more threads lost sync with other threads "
				  "and exited without cleaning up\nits objects.  This "
				  "happens occasionally due to network timing issues or\n"
				  "thread scheduling differences." );
			}
		else
			{
			printf( "cryptEnd() failed with error code %d, line %d.\n", 
					status, __LINE__ );
			}
		goto errorExit1;
		}

	puts( "All tests concluded successfully." );
	return( EXIT_SUCCESS );

	/* All errors end up here */
errorExit:
	cryptEnd();
errorExit1:
	puts( "\nThe test was aborted due to an error being detected.  If you "
		  "want to report\nthis problem, please provide as much information "
		  "as possible to allow it to\nbe diagnosed, for example the call "
		  "stack, the location inside cryptlib where\nthe problem occurred, "
		  "and the values of any variables that might be\nrelevant." );
	if( sessionTestError )
		{
		puts( "\nThe error occurred during one of the network session tests, "
			  "if the error\nmessage indicates a network-level problem such "
			  "as ECONNREFUSED, ECONNRESET,\nor a timeout or read error then "
			  "this is either due to a transient\nnetworking problem or a "
			  "firewall interfering with network connections.  This\nisn't a "
			  "cryptlib error, and doesn't need to be reported." );
		}
#ifdef WINDOWS_THREADS
	if( loopbackTestError )
		{
		puts( "\nThe error occurred during one of the multi-threaded network "
			  "loopback\ntests, this was probably due to the different threads "
			  "losing synchronisation.\nFor the secure sessions this usually "
			  "results in read/write, timeout, or\nconnection-closed errors "
			  "when one thread is pre-empted for too long.  For the\n"
			  "certificate-management sessions it usually results in an error "
			  "related to the\nserver being pre-empted for too long by database "
			  "updates.  Since the self-\ntest exists only to exercise "
			  "cryptlib's capabilities, it doesn't bother with\ncomplex thread "
			  "synchronisation during the multi-threaded loopback tests.\nThis "
			  "type of error is non-fatal, and should disappear if the test is "
			  "re-run." );
		}
#endif /* WINDOWS_THREADS */
#if defined( __WINDOWS__ ) && !defined( NDEBUG )
	/* The pseudo-CLI VC++ output windows are closed when the program exits
	   so we have to explicitly wait to allow the user to read them */
	puts( "\nHit a key..." );
	getchar();
#endif /* __WINDOWS__ && !NDEBUG */
	return( EXIT_FAILURE );
	}
Example #8
0
int main(int argc,char **argv)
{
    char   *pval;
    double sleepSecs = 0.0;
    int	    clearEvery = 0;
    int     indValue = 1;
    int     indNumberCallback = 1;

    while((argc>1) && (argv[1][0] == '-')) {
        int i;
        char option;
        int  narg;
        option = toupper((argv[1])[1]);
        pval = argv[2];
        argc -= 1; narg = 1;
        if(option=='S') {
            sscanf(pval,"%lf",&sleepSecs);
            argc -= 1; ++narg;
        } else if(option=='C') {
            sscanf(pval,"%d",&clearEvery);
            argc -= 1; ++narg;
        } else if(option=='V') {
            verbose = 1;
        } else {
            usageExit();
        }
        for(i=1; i<argc; i++) argv[i] = argv[i + narg];
    }

    if(argc != 4) usageExit();
    pvname = argv[1];
    pvalue1 = argv[2];
    pvalue2 = argv[3];
    pevent = epicsEventCreate(epicsEventEmpty);
    SEVCHK(ca_context_create(ca_enable_preemptive_callback),
        "ca_task_initialize");
    while(1) {
        SEVCHK(ca_search(pvname,&mychid),"ca_search_and_connect");
        if(ca_pend_io(3.0)!=ECA_NORMAL) {
            epicsThreadSleep(5.0);
            continue;
        }
        while(1) {
            epicsEventWaitStatus status;
            if(indValue==0) {
                indValue = 1; pvalue = pvalue2;
            } else {
                indValue = 0; pvalue=pvalue1;
            }
            if(++indNumberCallback >= MAXnumberCallback) indNumberCallback=0;
            numberCallback[indNumberCallback] = ++expectedCallback;
            status = ca_array_put_callback(DBR_STRING,1,mychid,
                pvalue,putCallback,&numberCallback[indNumberCallback]);
            if(status!=ECA_NORMAL) {
                printf("ca_array_put_callback %s\n",ca_message(status));
                epicsThreadSleep(2.0);
                continue;
            }
            if((clearEvery>0) 
            && ((expectedCallback % clearEvery)==0)) {
                ca_flush_io();
                epicsThreadSleep(sleepSecs);
                SEVCHK(ca_clear_channel(mychid),"ca_clear_channel");
                ca_flush_io();
                expectedCallback = 0;
                epicsThreadSleep(sleepSecs);
                if(verbose) {
                    printTime();
                    printf("Issued ca_clear_channel expectedCallback %d\n",
                        expectedCallback);
                }
                break;
            }
            ca_flush_io();
            if(verbose) {
                printTime();
                printf("Issued ca_put_callback expectedCallback %d\n",
                    expectedCallback);
            }
            while(1) {
                status = epicsEventWaitWithTimeout(pevent,10.0);
                if(status==epicsEventWaitTimeout) {
                    if(verbose) {
                        printTime();
                        printf("timeout after 10 seconds\n");
                    }
                    continue;
                }
                break;
            }
            if(status!=epicsEventWaitOK) {
                int i;
                printTime();
                printf("eventWait status %d\n",status);
                for(i=0; i<MAXnumberCallback; i++) numberCallback[i]=0;
            }
            epicsThreadSleep(sleepSecs);
        }
    }
    ca_task_exit();
    return(0);
}
Example #9
0
static int processArgs( int argc, char **argv, int *testNo, 
						const char **stringArg, int *intArg, 
						BOOLEAN *isServer, BOOLEAN *sendHTTPheader )
	{
	const char *argPtr = argv[ 0 ];
	BOOLEAN moreArgs = TRUE;
	int value;

	/* Clear return values */
	*testNo = *intArg = 0;
	*stringArg = NULL;
	*isServer = *sendHTTPheader = FALSE;

	/* No args means display a usage message */
	if( argc <= 0 )
		usageExit();

	/* Process the main command */
	switch( tolower( *argPtr ) )
		{
		case 'c':
			*isServer = FALSE;
			argv++; argc--;
			break;
		
		case 's':
			*isServer = TRUE;
			argv++; argc--;
			break;

		case 'k':
			switch( tolower( argPtr[ 1 ] ) )
				{
				case 'g':
					*testNo = -1;	/* Generate key */
					break;

				case 'a':
					*testNo = -2;	/* Add certificate */
					break;

				default:
					printf( "Error: Unknown key management option '%c'.\n", 
							argPtr[ 1 ] );
					return( FALSE );
				}

			/* Get the key size */
			argv++; argc--;
			if( argc <= 0 )
				{
				puts( "Error: Missing key size." );
				return( FALSE );
				}
			argPtr = argv[ 0 ];
			value = -1;
			if( *argPtr == '2' || *argPtr == '3' )
				value = atoi( argv[ 0 ] );
			if( value != 256 && value != 384 )
				{
				puts( "Error: Key size must be '256' or '384'." );
				return( FALSE );
				}
			*intArg = value;

			/* Get the filename */
			argv++; argc--;
			if( argc <= 0 )
				{
				puts( "Error: Missing file name." );
				return( FALSE );
				}
			*stringArg = argv[ 0 ];
			if( *testNo == -2 )
				{
				FILE *filePtr;

				/* Make sure that the specified input file exists */
				filePtr = fopen( argv[ 0 ], "rb" );
				if( filePtr == NULL )
					{
					printf( "Error: Can't open '%s'.\n", argv[ 0 ] );
					return( FALSE );
					}
				fclose( filePtr );
				}

			/* Make sure that's all */
			argv++; argc--;
			if( argc != 0 )
				{
				printf( "Error: Spurious option '%s'.\n", argv[ 0 ] );
				return( FALSE );
				}
			break;

		default:
			usageExit();
		}

	/* Process any additional arguments */
	while( argc > 0 && moreArgs )
		{
		argPtr = argv[ 0 ];
		if( *argPtr == '1' || *argPtr == '2' )
			{
			/* The user has asked to run as a generic 128/256-bit client or 
			   server, map it to an equivalent test number */
			value = atoi( argPtr );
			if( value != 128 && value != 256 )
				{
				puts( "Error: Generic client/server type must be '128' "
					  "or '256'." );
				return( FALSE );
				}
			if( value == 128 )
				argPtr = "A.1.1.1";
			else
				argPtr = "A.1.2.1";
			}
		if( *argPtr == 'a' || *argPtr == 'A' )
			{
			int value;

			if( *testNo != 0 )
				usageExit();

			/* Perform a basic validity test that the argument is in the 
			   format "A.[12].[1-3]" */
			if( argPtr[ 1 ] != '.' || \
				( argPtr[ 2 ] != '1' && argPtr[ 2 ] != '2' ) || \
				argPtr[ 3 ] != '.' || \
				( argPtr[ 4 ] < '1' || argPtr[ 4 ] > '3' ) )
				usageExit();
			value = lookupTestNo( argPtr );
			if( value == 0 )
				{
				printf( "Error: Unknown test type '%s'.\n", argPtr );
				return( FALSE );
				}
			*testNo = value;
			argv++;
			argc--;
			continue;
			}
		if( *argPtr != '-' )
			{
			printf( "Error: Unknown argument '%s'.\n", argPtr );
			return( FALSE );
			}
		argPtr++;
		while( *argPtr )
			{
			switch( toupper( *argPtr ) )
				{
				case '-':
					moreArgs = FALSE;	/* GNU-style end-of-args flag */
					break;

				case 'H':
					if( *stringArg != NULL )
						usageExit();
					argv++; argc--;
					if( argc <= 0 )
						{
						puts( "Error: Missing host name" );
						return( FALSE );
						}
					*stringArg = argv[ 0 ];
					argPtr = "";
					break;

				case 'P':
					if( *intArg != 0 )
						usageExit();
					argv++; argc--;
					if( argc <= 0 )
						{
						puts( "Error: Missing port number" );
						return( FALSE );
						}
					value = atoi( argv[ 0 ] );
					if( value < 20 || value > 64000 )
						usageExit();
					*intArg = value;
					argPtr = "";
					break;

				case 'S':
					if( *sendHTTPheader != FALSE )
						usageExit();
					*sendHTTPheader = TRUE;
					argPtr++;
					break;

				default:
					printf( "Error: Unknown argument '%c'.\n", *argPtr );
					return( FALSE );
				}
			}
		argv++;
		argc--;
		}
	if( *testNo == 0 )
		{
		puts( "Error: Missing test name" );
		return( FALSE );
		}

	return( TRUE );
	}