Пример #1
0
Файл: gscr.c Проект: ICRAR/void
int main(int argc, char** argv)
{
    frequency_t frequency = {0};
    time_delta_t t0 = {0};
    time_delta_t t1 = {0};
	char* prefix = 0;
	int start = 0;
	int padding = 0;
    int i, k, s, p;
    double dt;
	
    gscr_options_t opt = {0};
    ParseOptions(&opt, argc, argv);

    if(!opt.quiet)
    {
        Info(SEPARATOR);
        Info("Loading input data from file '%s'\n", opt.input);
        Info(SEPARATOR);
    }

    frequency = GetTimerFrequencyForHost();
    t0 = t1 = GetCurrentTimeForHost();

	size_t length = strlen(opt.input);
	for(i = length-1; i >= 0 && isdigit(opt.input[i]); --i)
		padding++;
		
	prefix = malloc(length);
	snprintf(prefix, length - padding, "%s", opt.input);
	start = atoi(opt.input + (length - padding));
	
	Info("Starting prefix  '%s' at '%d' with padded index '%d' ...\n", prefix, start, padding);
	
    for(s = start; s <= opt.snapshots + start; s++)
    {
    	char digits[1024] = {0};
    	snprintf(digits, sizeof(digits), "%d", s);
    	size_t digit_len = strlen(digits);
    	
		char filename[4096] = {0};
        snprintf(filename, length + padding + digit_len, "%s_", prefix);
		for(p = 0; p < padding - digit_len; p++)
			strcat(filename, "0");
		strcat(filename, digits);

	    gs_data_t* gs = gsAllocateData();

		t0 = GetCurrentTimeForHost();
		gsLoadSnapshotData(&opt, gs, filename);
		t1 = GetCurrentTimeForHost();
	
		if(!opt.quiet)
		{
			dt = SubtractTimeInSecondsForHost(t1, t0, frequency);
			Info("Loaded snapshot  '%s' in '%.2f' ms\n", filename, 1000.0 * dt);
		}
	
		if(opt.reorder)
		{
            Info(SEPARATOR);
			t0 = GetCurrentTimeForHost();
			gsReorder(gs);
			t1 = GetCurrentTimeForHost();
	
			if(!opt.quiet)
			{
				dt = SubtractTimeInSecondsForHost(t1, t0, frequency);
				Info("Reordered '%lu' particles in '%.2f' ms\n", gs->TotalParticleCount, 1000.0 * dt);
                Info(SEPARATOR);
			}
		}
	
		if(opt.unwrap && gs->Data.Position)
		{
			t0 = GetCurrentTimeForHost();
			for(i = 0; i < gs->TotalParticleCount; i++)
			{
				for(k = 0; k < 3; k++)
					gs->Data.Position[i * 3 + k] = gsPeriodic(gs->Data.Position[i * 3 + k], gs->Header.Fields.BoxSize * 0.5f);
			}
			t1 = GetCurrentTimeForHost();
	
			if(!opt.quiet)
			{
				dt = SubtractTimeInSecondsForHost(t1, t0, frequency);
				Info("Unwrapped '%lu' particles in '%.2f' ms\n", gs->TotalParticleCount, 1000.0 * dt);
			}
		}
	
		t0 = GetCurrentTimeForHost();
		gsConvertUnits(gs);
		t1 = GetCurrentTimeForHost();
		
		t0 = GetCurrentTimeForHost();
		if(!opt.quiet) Info(SEPARATOR);
		
        gsExport(&opt, gs, filename);

		if(!opt.quiet) Info(SEPARATOR);
		t1 = GetCurrentTimeForHost();
	
		if(!opt.quiet)
		{
			dt = SubtractTimeInSecondsForHost(t1, t0, frequency);
			Info("Exported data for '%lu' particles in '%.2f' ms\n", gs->TotalParticleCount,  1000.0 * dt);
			Info(SEPARATOR);
		}
	
		gsDestroyData(gs);
	}
	
	DestroyOptions(&opt);
	free(prefix);
	
    Info("DONE!");
    exit(0);
}
Пример #2
0
int main(int argc, char **argv)
{
    ParseOptions(argc, argv);
    if (argc - optind != 2) {
        Usage(argv[0]);
        exit(1);
    }

    char *trace_filename = argv[optind++];
    char *elf_file = argv[optind++];
    TraceReader<symbol> *trace = new TraceReader<symbol>;
    trace->Open(trace_filename);
    trace->SetDemangle(demangle);
    trace->ReadKernelSymbols(elf_file);
    trace->SetRoot(root);

    BBEvent event;
    while (1) {
        BBEvent ignored;
        symbol_type *function;

        if (GetNextValidEvent(trace, &event, &ignored, &function))
            break;
        if (event.bb_num == 0)
            break;

        // Get the stack for the current thread
        CallStackType *pStack = stacks[event.pid];

        // If the stack does not exist, then allocate a new one.
        if (pStack == NULL) {
            pStack = new CallStackType(event.pid, kNumStackFrames, trace);
            stacks[event.pid] = pStack;
        }

        // Update the stack
        pStack->updateStack(&event, function);
    }

    for (int ii = 0; ii < kMaxThreads; ++ii) {
        if (stacks[ii])
            stacks[ii]->popAll(event.time);
    }

    int nsyms;
    symbol_type *syms = trace->GetSymbols(&nsyms);

    // Sort the symbols into decreasing number of calls
    qsort(syms, nsyms, sizeof(symbol_type), cmp_sym_names);

    symbol_type *psym = syms;
    for (int ii = 0; ii < nsyms; ++ii, ++psym) {
        // Ignore functions with non-zero calls
        if (psym->numCalls)
            continue;

        // Ignore some symbols
        if (strcmp(psym->name, "(end)") == 0)
            continue;
        if (strcmp(psym->name, "(unknown)") == 0)
            continue;
        if (strcmp(psym->name, ".plt") == 0)
            continue;
        const char *ksym = " ";
        if (psym->region->flags & region_type::kIsKernelRegion)
            ksym = "k";
        printf("%s %s %s\n", ksym, psym->name, psym->region->path);
#if 0
        printf("#%d %5d %s %s %s\n", ii + 1, psym->numCalls, ksym, psym->name,
               psym->region->path);
#endif
    }
    delete[] syms;
    delete trace;

    return 0;
}
int main( int argc, char *argv[] )
{
  static LALStatus                status;

  StochasticCrossCorrelationInput           input;
  REAL4WithUnits           output;

  COMPLEX8FrequencySeries  goodData1;
  COMPLEX8FrequencySeries  goodData2;
  COMPLEX8FrequencySeries  goodFilter;

  LIGOTimeGPS              epoch0 = {0,0};
  LIGOTimeGPS              epoch1 = {630720000,123456789};
  LIGOTimeGPS              epoch2 = {630720000,987654321};
  LIGOTimeGPS              epoch3 = {630722222,123456789};

  int                      result;

  CHAR                     unitString[LALUnitTextSize];
  
  UINT4 i;
  REAL4 f, x;
  INT4 code;


  ParseOptions( argc, argv );

  /* define valid parameters */

  goodFilter.f0     = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0;
  goodFilter.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;
  goodFilter.epoch  = epoch0;
  goodFilter.data   = NULL;

#ifndef LAL_NDEBUG
  COMPLEX8FrequencySeries  badFilter = goodFilter;
#endif

  goodData1 = goodFilter;

  goodData1.epoch = epoch1;
  goodData2 = goodData1;
#ifndef LAL_NDEBUG
  COMPLEX8FrequencySeries  badData1 = goodData2;
  COMPLEX8FrequencySeries  badData2 = badData1;
#endif

  LALCCreateVector(&status, &(goodData1.data),
                          STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  LALCCreateVector(&status, &(goodData2.data),
                          STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  LALCCreateVector(&status, &(goodFilter.data),
                          STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  input.hBarTildeOne  = &goodData1;
  input.hBarTildeTwo  = &goodData2;
  input.optimalFilter = &goodFilter;

#ifndef LAL_NDEBUG
  if ( ! lalNoDebug )
  {
    /* test behavior for null pointer to output structure */
    LALStochasticCrossCorrelationStatistic(&status, NULL, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
      {
        return code;
      }
    printf("  PASS: null pointer to output structure results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* test behavior for null pointer to input structure */
    LALStochasticCrossCorrelationStatistic(&status, &output, NULL, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to input structure results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* test behavior for null pointer to first data stream */
    input.hBarTildeOne = NULL;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to first data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to second data stream */
    input.hBarTildeOne = &goodData1;

    /* test behavior for null pointer to second data stream */
    input.hBarTildeTwo = NULL;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to second data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to second data stream */
    input.hBarTildeTwo = &goodData2;

    /* test behavior for null pointer to optimal filter */
    input.optimalFilter = NULL;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to optimal filter results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to optimal filter */
    input.optimalFilter = &goodFilter;

    /* test behavior for null pointer to data member of first data stream */
    input.hBarTildeOne = &badData1;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of first data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of first data stream */
    input.hBarTildeOne = &goodData1;

    /* test behavior for null pointer to data member of second data stream */
    input.hBarTildeTwo = &badData2;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of second data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of second data stream */
    input.hBarTildeTwo = &goodData2;

    /* test behavior for null pointer to data member of optimal filter */
    input.optimalFilter = &badFilter;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of optimal filter results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of optimal filter */
    input.optimalFilter = &goodFilter;

    /* Create a vector for testing null data-data pointers */
    LALCCreateVector(&status, &(badFilter.data),
                          STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
    {
      return code;
    }
    COMPLEX8                *tempPtr;
    tempPtr = badFilter.data->data;
    badFilter.data->data = NULL;
    badData1.data = badData2.data = badFilter.data;

    /* test behavior for null pointer to data member of data member of first data stream */
    input.hBarTildeOne = &badData1;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of data member of first data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of data member of first data stream */
    input.hBarTildeOne = &goodData1;

    /* test behavior for null pointer to data member of data member of second data stream */
    input.hBarTildeTwo = &badData2;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of data member of second data stream results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of data member of second data stream */
    input.hBarTildeTwo = &goodData2;

    /* test behavior for null pointer to data member of data member of optimal filter */
    input.optimalFilter = &badFilter;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
     {
      return code;
    }
    printf("  PASS: null pointer to data member of data member of optimal filter results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* assign valid pointer to data member of data member of optimal filter */
    input.optimalFilter = &goodFilter;

    /* clean up */

    badFilter.data->data = tempPtr;
    LALCDestroyVector(&status, &(badFilter.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
    {
      return code;
    }
    badData1.data = badData2.data = badFilter.data;

    /* test behavior for zero length */
    goodData1.data->length = goodData2.data->length
      = goodFilter.data->length = 0;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EZEROLEN,
			      STOCHASTICCROSSCORRELATIONH_MSGEZEROLEN,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: zero length results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGEZEROLEN);
    /* reassign valid length */
    goodData1.data->length = goodData2.data->length
      = goodFilter.data->length = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH;

    /* test behavior for negative frequency spacing */
    goodData1.deltaF = goodData2.deltaF
      = goodFilter.deltaF = -STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: negative frequency spacing results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF);

    /* test behavior for zero frequency spacing */
    goodData1.deltaF = goodData2.deltaF
      = goodFilter.deltaF = 0;
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: zero frequency spacing results in error:\n       \"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF);
    /* reassign valid frequency spacing */
    goodData1.deltaF = goodData2.deltaF
      = goodFilter.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;
   } /* if ( ! lalNoDebug ) */
#endif /* LAL_NDEBUG */

  /* test behavior for negative start frequency */
  goodData1.f0 = goodData2.f0
    = goodFilter.f0 = -20.0;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENEGFMIN,
			    STOCHASTICCROSSCORRELATIONH_MSGENEGFMIN,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: negative start frequency results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGENEGFMIN);

  /* reassign valid start frequency */
  goodData1.f0 = goodData2.f0
    = goodFilter.f0 = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0;

  /* test behavior for length mismatch
     between optimal filter and first data stream */
  goodData1.data->length = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH - 1;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMLEN,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMLEN,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: length mismatch between optimal filter and first data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMLEN);

  /* reassign correct length */
  goodData1.data->length = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH;

  /* test behavior for length mismatch
     between optimal filter and first data stream */
  goodData2.data->length = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH - 1;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMLEN,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMLEN,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: length mismatch between optimal filter and second data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMLEN);

  /* reassign correct length */
  goodData2.data->length = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH;

  /* test behavior for frequency spacing mismatch
     between optimal filter and first data stream */
  goodData1.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF * 2.0;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMDELTAF,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMDELTAF,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: frequency spacing mismatch between optimal filter and first data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMDELTAF);

  /* reassign correct frequency spacing */
  goodData1.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;

  /* test behavior for frequency spacing mismatch
     between optimal filter and second data stream */
  goodData2.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF * 2.0;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMDELTAF,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMDELTAF,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: frequency spacing mismatch between optimal filter and second data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMDELTAF);

  /* reassign correct frequency spacing */
  goodData2.deltaF = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;

  /* test behavior for start frequency mismatch
     between optimal filter and first data stream */
  goodData1.f0 = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0 + 2.0;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMFMIN,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMFMIN,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: start frequency mismatch between optimal filter and first data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMFMIN);

  /* reassign correct start frequency */
  goodData1.f0 = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0;

  /* test behavior for start frequency mismatch
     between optimal filter and second data stream */
  goodData2.f0 = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0 + 2.0;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMFMIN,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMFMIN,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: start frequency mismatch between optimal filter and second data stream results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMFMIN);

  /* reassign correct start frequency */
  goodData2.f0 = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0;

  /* test behavior for mismatch between epochs of data streams */
  goodData2.epoch = epoch2;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMTIME,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMTIME,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  goodData2.epoch = epoch3;
  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMTIME,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMTIME,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ECHK,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: mismatch between epochs of data streams results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGEMMTIME);

  /* reassign correct epoch */
  goodData2.epoch = epoch1;

  /******************** Test Valid Data Case #1 ***********************/
  goodData1.sampleUnits = lalDimensionlessUnit;
  goodData1.sampleUnits.unitNumerator[LALUnitIndexStrain] = 1;
  goodData1.sampleUnits.unitNumerator[LALUnitIndexSecond] = 1;
  goodData2.sampleUnits = goodData1.sampleUnits;
  goodFilter.sampleUnits = lalDimensionlessUnit;
  goodFilter.sampleUnits.unitNumerator[LALUnitIndexStrain] = -1;

  goodData1.f0 = goodData2.f0 = goodFilter.f0 = 0.0;

  goodData1.data->data[0] = goodData2.data->data[0] = goodFilter.data->data[0] = 0.0;

  for (i=1; i<STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH; ++i)
  {
    f = i * STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;
    x = f / (STOCHASTICCROSSCORRELATIONSTATISTICTESTC_FLIM / 2.0);
    goodData1.data->data[i] = crectf( x*x, x );
    goodData2.data->data[i] = crectf( 1.0/crealf(goodData1.data->data[i]), -1.0/cimagf(goodData1.data->data[i]) );
    goodFilter.data->data[i] = crectf( x * (2-x), 0.0 );
  }

  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  if (optVerbose) printf("Y=%g, should be 0\n",output.value);
  if (fabsf(output.value)/STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF
      > STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TOL)
  {
    printf("  FAIL: Valid data test #1\n");
    if (optVerbose)
    {
      printf("Exiting with error: %s\n",
             STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS);
    }
    return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
  }

  result = XLALUnitCompare(&(goodData1.sampleUnits), &(output.units));
  if (optVerbose)
  {
    if ( XLALUnitAsString( unitString, LALUnitTextSize, &(output.units)) == NULL ) {
      return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
    }
    printf( "Units are \"%s\", ", unitString );
    if ( XLALUnitAsString( unitString, LALUnitTextSize, &(goodData1.sampleUnits)) == NULL ) {
      return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
    }
    printf( "should be \"%s\"\n", unitString );
  }

  if (result != 0)
  {
    printf("  FAIL: Valid data test #1\n");
    if (optVerbose)
    {
      printf("Exiting with error: %s\n",
             STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS);
    }
    return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
  }

  printf("  PASS: Valid data test #1\n");


  /********************** Test Valid Data Case #2 *****************/
  goodData1.sampleUnits = lalDimensionlessUnit;
  goodData1.sampleUnits.unitNumerator[LALUnitIndexStrain] = 1;
  goodData1.sampleUnits.unitNumerator[LALUnitIndexSecond] = 1;
  goodData2.sampleUnits = lalDimensionlessUnit;
  goodData2.sampleUnits.unitNumerator[LALUnitIndexADCCount] = 1;
  goodData2.sampleUnits.unitNumerator[LALUnitIndexSecond] = 1;
  goodFilter.sampleUnits = lalDimensionlessUnit;
  goodFilter.sampleUnits.unitNumerator[LALUnitIndexStrain] = -1;
  goodFilter.sampleUnits.unitNumerator[LALUnitIndexADCCount] = -1;

  goodData1.f0 = goodData2.f0 = goodFilter.f0
    = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0;

  for (i=0; i<STOCHASTICCROSSCORRELATIONSTATISTICTESTC_LENGTH; ++i)
  {
    f = STOCHASTICCROSSCORRELATIONSTATISTICTESTC_F0
      + i * STOCHASTICCROSSCORRELATIONSTATISTICTESTC_DELTAF;
    goodData1.data->data[i] = crectf( f/STOCHASTICCROSSCORRELATIONSTATISTICTESTC_FLIM, 0.0 );
    goodData2.data->data[i] = crectf( 1 - crealf(goodData1.data->data[i]), 0.0 );
    if ( f > STOCHASTICCROSSCORRELATIONSTATISTICTESTC_WINMIN
         && f < STOCHASTICCROSSCORRELATIONSTATISTICTESTC_WINMAX )
    {
      goodFilter.data->data[i] = 1.0;
    }
    else
    {
      goodFilter.data->data[i] = 0.0;
    }
  }

  LALStochasticCrossCorrelationStatistic(&status, &output, &input, STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TRUE);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  if (optVerbose)
  {
    printf("Y=%g, should be %g\n",output.value,
           STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EXP2);
  }
  if ( fabs(output.value-STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EXP2)
       / STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EXP2
       > STOCHASTICCROSSCORRELATIONSTATISTICTESTC_TOL)
  {
    printf("  FAIL: Valid data test #2\n");
    if (optVerbose)
    {
      printf("Exiting with error: %s\n",
             STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS);
    }
    return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
  }

  result = XLALUnitCompare(&lalSecondUnit, &(output.units));
  if (optVerbose)
  {
    if ( XLALUnitAsString( unitString, LALUnitTextSize, &(output.units)) == NULL ) {
      return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
    }
    printf( "Units are \"%s\", ", unitString );
    if ( XLALUnitAsString( unitString, LALUnitTextSize, &lalSecondUnit) == NULL ) {
      return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
    }
    printf( "should be \"%s\"\n", unitString );
  }

  if (result != 0)
  {
    printf("  FAIL: Valid data test #2\n");
    if (optVerbose)
    {
      printf("Exiting with error: %s\n",
             STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS);
    }
    return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
  }

  printf("  PASS: Valid data test #2\n");


  /* clean up */
  LALCDestroyVector(&status, &(goodFilter.data));
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  LALCDestroyVector(&status, &(goodData1.data));
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  LALCDestroyVector(&status, &(goodData2.data));
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			    STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
  {
    return code;
  }

  printf("PASS: all tests\n");
  LALCheckMemoryLeaks();

  if (optData1File[0] && optData2File[0] && optFilterFile[0])
  {

    /* Allocate Memory */
    LALCCreateVector(&status, &(goodFilter.data), optLength);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALCCreateVector(&status, &(goodData1.data), optLength);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALCCreateVector(&status, &(goodData2.data), optLength);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    /* Read Data From Files */
    LALCReadFrequencySeries(&status, &(goodFilter), optFilterFile);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALCReadFrequencySeries(&status, &(goodData1), optData1File);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALCReadFrequencySeries(&status, &(goodData2), optData2File);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }
    /* Calculate CC Statistic */
    LALStochasticCrossCorrelationStatistic(&status, &output, &input, optMatch);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EUSE,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEUSE) ) )
    {
      return code;
    }

    /* Convert Unit Structure to String */
    if ( XLALUnitAsString( unitString, LALUnitTextSize, &(output.units)) == NULL ) {
      return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS;
    }

    printf("=========== Cross-Correlation Statistic for User-Specified Data Is =======\n");
    printf("     %g %s\n", output.value, unitString);

    /* Deallocate Memory */
    LALCDestroyVector(&status, &(goodFilter.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
    {
      return code;
    }
    LALCDestroyVector(&status, &(goodData1.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
    {
      return code;
    }
    LALCDestroyVector(&status, &(goodData2.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_EFLS,
			      STOCHASTICCROSSCORRELATIONSTATISTICTESTC_MSGEFLS) ) )
    {
      return code;
    }
  }


  /* normal exit */
  LALCheckMemoryLeaks();
  return STOCHASTICCROSSCORRELATIONSTATISTICTESTC_ENOM;
}
Пример #4
0
//*****************************************************************************
//
// Main entry.  Process command line options, and start the bootp_server.
//
//*****************************************************************************
int
main(int argc, char **argv)
{
    HOSTENT *pHostEnt;
    WSADATA wsaData;
    unsigned long ulLocalAddress;

    //
    // Parse the command line options.
    //
    if(argc > 1)
    {
        ParseOptions(argc, argv);
    }
    else
    {
        DisplayVersion();
        DisplayHelp();
        return(0);
    }

    //
    // Display (if needed) verbose function entry.
    //
    if(g_iOptVerbose > 1)
    {
        DisplayVersion();
    }

    //
    // Install an abort handler.
    //
	signal(SIGINT, SignalIntHandler);

    //
    // Startup winsock.
    //
    VPRINTF(("Starting WINSOCK\n"));
    if(WSAStartup(0x202, &wsaData) != 0)
    {
        EPRINTF(("Winsock Failed to Start\n"));
        WSACleanup();
        return(1);
    }

    //
    // Determine what my local IP address is.
    //
    pHostEnt = gethostbyname("");
    ulLocalAddress = ((struct in_addr *)*pHostEnt->h_addr_list)->s_addr;

    //
    // Start the BOOTP/TFTP server to perform an update.
    //
    QPRINTF(("Starting BOOTP/TFTP Server ...\n"));
    StatusCallback(0);
    StartBOOTPUpdate(g_pucRemoteMAC, ulLocalAddress, g_ulRemoteAddress,
                     g_pcFileName, StatusCallback);

    //
    // Cleanup winsock.
    //
    VPRINTF(("Closing WINSOCK\n"));
    WSACleanup();

    //
    // Clean up and return.
    //
    if(g_bAbortMain)
    {
        return(2);
    }
    return(0);
}
Пример #5
0
void Target::ParseImageOptions(char *argv[], int i, int argc)
{
	// Right now the image and file use the same parser
	ParseOptions(argv, i, argc);
}
int main ( int argc, char* argv[] )
{
	char		szProjectFilePath	[_MAX_PATH	+1];
	char		szSourceFilePath	[_MAX_PATH	+1];
	char		szDrive						[_MAX_DRIVE	+1];
	char		szDir							[_MAX_DIR		+1];
	char		szExt							[_MAX_EXT		+1];
	char		szFname						[_MAX_PATH	+1];
	char		szOldDirectory		[_MAX_PATH	+1];
	int			i;
	_OPTIONS	*pOptTarget		= sOptions,
						*pOptPlatform	= sOptions,
						*pOptOS				= sOptions,
						*pOptFile			= sOptions,
						*pOptOpt			= sOptions;

	szProjectFilePath	[0] = '\0';
	szSourceFilePath	[0] = '\0';

	BOOL		flagPrint = TRUE;
	if ( argc < 2 )
		return 0;

	for ( i=2; i< argc; i++ )
		{
		 if ( i < argc )
			 *(argv[i]-1) = ' ';
		}
	ParseOptions( argv[1], sOptions, sOptionsSubst );
	GetCurrentDirectory( MAX_PATH, szOldDirectory );
	_splitpath( argv[1], szDrive, szDir, szFname, szExt );
	_makepath( szProjectFilePath, szDrive, szDir, szFname, szExt );
	ChangeSlash( szProjectFilePath );

	if( szProjectFilePath && ! access( szProjectFilePath, 4 ) )	// if a specified file exists
	{																														// and we have read access right

		if( strlen( szDir ) )
		{
			char		szProjectDirectory[_MAX_PATH	+1];
		
			szProjectDirectory[0] = '\0';
			strcat( szProjectDirectory, szDrive );
			strcat( szProjectDirectory, szDir );
			SetCurrentDirectory( szProjectDirectory );
		}

	FILE*	file;
	if ( flagPrint )
		{
		file= fopen(LOG_FILE_NAME, "w+t");
		fprintf(file, "%s", "MakePDF\n" );
		fclose(file);
		}

	while ( stricmp(pOptTarget	->pszOptionText, "TARGET"	 ) ) pOptTarget		++;
	while ( stricmp(pOptPlatform->pszOptionText, "PLATFORM") ) pOptPlatform	++;
	while ( stricmp(pOptOS			->pszOptionText, "OS"			 ) ) pOptOS				++;
	while ( stricmp(pOptFile		->pszOptionText, "FILE"		 ) ) pOptFile			++;
	while ( stricmp(pOptOpt			->pszOptionText, "OPTIONS" ) ) pOptOpt			++;

	if ( pOptFile->bOptionOn && *(pOptFile->pszOptionVal) )
		InternalConvertFileName( pOptFile->pszOptionVal, szSourceFilePath );

	SetCommonVar( pOptOS->pszOptionVal, pOptPlatform->pszOptionVal, pOptTarget->pszOptionVal ); 

	TargetNode		Head( szProjectFilePath, NULL );
	TargetNode*		pProjectNode;
	TargetNode*		pTarget;

	Head.ProcessNMake(TARGET_PROJECT);
	pProjectNode = Head.GetFirstChildPRJ();
	while ( pProjectNode )
		{
		 pProjectNode->ProcessNMake(TARGET_FILE_C);
		 if ( *szSourceFilePath && ( pTarget=pProjectNode->FindByNameTargetC(szSourceFilePath) ) != NULL )
				{
				 OptionNode	*pOption = pTarget->GetCompileOptions();
				 if ( pOption )
					{
					 printf(" cl -n %s", szSourceFilePath);
					 while ( pOption )
							{
							 printf(" -%s", pOption->GetOptionText() );
							 pOption= pOption->GetNext();
							}
					 printf("\n" );
					}
				 break;
				}
		 pProjectNode = pProjectNode->GetNext();
		}


	if ( !pOptFile->bOptionOn )
		{
			Head.CreateProjectTree();
			Head.RaiseUpPathC();
			Head.PrintProjectTree(0);
			Head.SetProjectPath();
			Head.ProcessFileH();
			Head.RaiseUpPathH();
			Head.RaiseUpTargetH();
			if (pOptOpt->bOptionOn)
				{
					Head.RaiseUpOptions();
					Head.WritePDFOptions();
				}
			Head.Wildcards();
			Head.PullDownPath();
			Head.PrintProjectTree(0);
			Head.ConvertFileName();
			Head.WritePDF();
		}
	SetCurrentDirectory( szOldDirectory );
	}
	
	return 0;
}
Пример #7
0
/*
 * Main program to invoke Java runtime using JNI invocation API. Supports
 * setting of VM arguments through standard command line options.
 */
void main(int argc, char *argv[])
{
	bool	isJava2 = false;
    JRESettings set;
    void *handle;
    JDK1_1InitArgs vmargs;
    JavaVM *jvm;
    JNIEnv *env;
//    char *s, *name;
    jclass cls;
    jmethodID mid;
    jarray args;
    int i;



    /* First scan arguments for help and debug options */
    for (i = 1; i < argc; i++) {
	char *arg = argv[i];
	if (*arg++ != '-') {
	    break;
	}
	if (strcmp(arg, "?") == 0 || strcmp(arg, "h") == 0 ||
	    strcmp(arg, "help") == 0) {
	    PrintUsage();
	    exit(1);
	}
#ifdef JRE_DEBUG
	if (strcmp(arg, "d") == 0) {
	    debug = JNI_TRUE;
	}
#endif
    }

    /* Get runtime settings */
#ifdef VERSION
    if (JRE_GetSettings(&set, VERSION) != 0) {
#else
    if (JRE_GetCurrentSettings(&set) != 0) {
#endif
		if (JRE_GetDefaultSettings(&set) != 0) {
//	    		fprintf(stderr, "Could not locate Java runtime\n");
	    		MessageBox(NULL,"Could not locate Java runtime","",MB_OK);
	    		exit(1);
		}
    }
    short majorVers = 0;
    short minorVers = 0;
    if(set.majorVersion){
    	majorVers = atoi(set.majorVersion);
    }
    if(set.minorVersion){
    	minorVers = atoi(set.minorVersion);
    }
    isJava2 = ((majorVers > 1) || (minorVers > 1));

#ifdef JRE_DEBUG
    if (debug) {
	char *ver = JRE_MakeVersion(set.majorVersion, set.minorVersion,
				    set.microVersion);
	fprintf(stderr, "Runtime Settings:\n");
	fprintf(stderr, " javaHome   = %s\n",
		set.javaHome != 0 ? set.javaHome : "<not set>");
	fprintf(stderr, " runtimeLib = %s\n",
		set.runtimeLib != 0 ? set.runtimeLib : "<not set>");
	fprintf(stderr, " version    = %s\n", ver != 0 ? ver : "<not set>");
	fprintf(stderr, " compiler   = %s\n\n",
		set.compiler != 0 ? set.compiler : "<not set>");
    }
#endif

    /* Load runtime library */
//    char testNetscapeJVMPATH[1024];
//    strcpy(testNetscapeJVMPATH,"C:\\Program Files\\Netscape\\Communicator\\Program\\jrt3240.dll");
	
//    handle = JRE_LoadLibrary(testNetscapeJVMPATH);
    handle = JRE_LoadLibrary(set.runtimeLib);
    if (handle == 0) {
  //winerror.h
    	DWORD err = GetLastError();
//		fprintf(stderr, "Could not load runtime library: %s error %u\n",set.runtimeLib,err);
		char messageStr[1024];
		sprintf(messageStr,"Could not load runtime library: %s error %u",set.runtimeLib,err);
		MessageBox(NULL,messageStr,"",MB_OK);
		exit(1);
    }

   		/* Parse command line options */
    	--argc; argv++;
		if (ParseOptions(&argc, &argv, &vmargs) != 0) {
			PrintUsage();
			exit(1);
    	}

    	/* Get name of class */
    	if (*argv == 0) {
			PrintUsage();
			exit(1);
    	}
/*
    	name = (char *)_strdup(*argv++);
    	for (s = name; *s != '\0'; s++) {
			if (*s == '.') *s = '/';
    	}
    	--argc;
*/
		
    /*
     * The following is used to specify that we require at least
     * JNI version 1.1. Currently, this field is not checked but
     * will be starting with JDK/JRE 1.2. The value returned after
     * calling JNI_GetDefaultJavaVMInitArgs() is the actual JNI version
     * supported, and is always higher that the requested version.
     */
     
	bool	errorCreateVM = true;
    if(isJava2){
	    char *newPath = (char *)JRE_Malloc(strlen("-Djava.class.path=")+strlen(addClassPath)+strlen(set.classPath)+1);// for symbol ;
	    strcpy(newPath,"-Djava.class.path=");
		strcat(newPath,addClassPath);
	    strcat(newPath,set.classPath);
//	 	char *newLibPath = (char *)JRE_Malloc(strlen((char *)nativeLibPath)+strlen("-Djava.library.path=")+1);
	
	 	JavaVMInitArgs vm_args;
		JavaVMOption options[1];
	
	    options[0].optionString = newPath; /* user classes */
//		options[1].optionString = newLibPath;  /* set native library path */
//  	options[2].optionString = "-Djava.compiler=NONE";           /* disable JIT */
//  	options[3].optionString = "-verbose:jni";                   /* print JNI-related messages */

    	vm_args.version = JNI_VERSION_1_2;
    	vm_args.options = options;
    	vm_args.nOptions = 1;
    	vm_args.ignoreUnrecognized = JNI_FALSE;
    	errorCreateVM = (JRE_CreateJavaVM((HINSTANCE)handle, &jvm, &env, &vm_args) != 0);
  		free(newPath);
// 		free(newLibPath);
    }else{ 
    /* Add pre-defined system properties */
    	if (set.javaHome != 0) {
			char *def = (char *)JRE_Malloc(strlen(set.javaHome) + 16);
			sprintf(def, "java.home=%s", set.javaHome);
			AddProperty(def);
    	}
    	if (set.compiler != 0) {
			char *def = (char *)JRE_Malloc(strlen(set.compiler) + 16);
			sprintf(def, "java.compiler=%s", set.compiler);
			AddProperty(def);
    	}
	    vmargs.version = 0x00010001;
		char newPath[1024];
		strcpy(newPath,".;");
		strcat(newPath,addClassPath);
		strcat(newPath,set.classPath);

	    if (JRE_GetDefaultJavaVMInitArgs(handle, &vmargs) != 0) {
//			fprintf(stderr, "Could not initialize Java VM\n");
			MessageBox(NULL,"Could not initialize Java VM","",MB_OK);
			exit(1);
	    }
	    vmargs.classpath = newPath;


#ifdef JRE_DEBUG
    	if (debug) {
			fprintf(stderr, "CLASSPATH is %s\n\n", vmargs.classpath);
    	}
#endif

    	/* Set user-defined system properties for Java VM */
		if (props != 0) {
			if (numProps == maxProps) {
	    		char **tmp = (char **)JRE_Malloc((numProps + 1) * sizeof(char **));
	    		memcpy(tmp, props, numProps * sizeof(char **));
	    		free(props);
	    		props = tmp;
			}
			props[numProps] = 0;
			vmargs.properties = props;
    	}
    	/* Load and initialize Java VM */
    	errorCreateVM = (JRE_CreateJavaVM(handle, &jvm, &env, &vmargs) != 0);
    }

    if (errorCreateVM) {
//		fprintf(stderr, "Could not create Java VM\n");
		MessageBox(NULL,"Could not create Java VM","",MB_OK);
		exit(1);
   	 }

    /* Free properties */
    if (props != 0) {
		free(props);
    }

    /* Find class */
    cls = env->FindClass(mainWabaClassName);
    if (cls == 0) {
//	fprintf(stderr, "Class not found: %s\n", *--argv);
		char messageStr[1024];
		sprintf(messageStr,"Class not found: %s", *--argv);
		MessageBox(NULL,messageStr,"",MB_OK);
	exit(1);
    }

    /* Find main method of class */
    mid = env->GetStaticMethodID( cls, "main",
    				    "([Ljava/lang/String;)V");
    if (mid == 0) {
//	fprintf(stderr, "In class %s: public static void main(String args[]) is not defined\n",mainWabaClassName);
		char messageStr[1024];
		sprintf(messageStr,"In class %s: public static void main(String args[]) is not defined\n",mainWabaClassName);
		MessageBox(NULL,messageStr,"",MB_OK);
	exit(1);
    }

    /* Invoke main method */
    args = NewStringArray(env, argv, argc);

    if (args == 0) {
	JRE_FatalError(env, "Couldn't build argument list for main\n");
    }
    env->CallStaticVoidMethod(cls, mid, args);
    if (env->ExceptionOccurred()) {
	env->ExceptionDescribe();
    }

    /* Wait until we are the only user thread remaining then unload VM */
    jvm->DestroyJavaVM();

    /* Unload the runtime */
    JRE_UnloadLibrary(handle);
}

/*
 * Parses command line VM options. Returns 0 if successful otherwise
 * returns -1 if an invalid option was encountered.
 */
jint ParseOptions(int *argcp, char ***argvp, JDK1_1InitArgs *vmargs)
{
    char *arg, **argv = *argvp;

    while ((arg = *argv++) != 0 && *arg++ == '-') {
	if (strcmp(arg, "classpath") == 0) {
	    if (*argv == 0) {
//		fprintf(stderr, "No class path given for %s option\n", arg);
		char messageStr[1024];
		sprintf(messageStr,"No class path given for %s option", arg);
		MessageBox(NULL,messageStr,"",MB_OK);
		return -1;
	    }
	    vmargs->classpath = *argv++;
	} else if (strcmp(arg, "cp") == 0) {
	    char *cp = vmargs->classpath;
	    if (*argv == 0) {
//		fprintf(stderr, "No class path given for %s option\n", arg);
		char messageStr[1024];
		sprintf(messageStr,"No class path given for %s option", arg);
		MessageBox(NULL,messageStr,"",MB_OK);
		return -1;
	    }
	    vmargs->classpath = (char *)malloc(strlen(*argv) + strlen(cp) + 2);
	    if (vmargs->classpath == 0) {
		perror("malloc");
		exit(1);
	    }
	    sprintf(vmargs->classpath, "%s%c%s", *argv++, PATH_SEPARATOR, cp);
	} else if (strncmp(arg, "D", 1) == 0) {
	    AddProperty(arg + 1);
	} else if (strncmp(arg, "ss", 2) == 0) {
	    jint n = atoml(arg + 2);
	    if (n >= 1000) {
		vmargs->nativeStackSize = n;
	    }
	} else if (strncmp(arg, "oss", 3) == 0) {
	    jint n = atoml(arg + 3);
	    if (n >= 1000) {
		vmargs->javaStackSize = n;
	    }
	} else if (strncmp(arg, "ms", 2) == 0) {
	    jint n = atoml(arg + 2);
	    if (n >= 1000) {
		vmargs->minHeapSize = n;
	    }
	} else if (strncmp(arg, "mx", 2) == 0) {
	    jint n = atoml(arg + 2);
	    if (n >= 1000) {
		vmargs->maxHeapSize = n;
	    }
	} else if (strcmp(arg, "noasyncgc") == 0) {
	    vmargs->disableAsyncGC = JNI_TRUE;
	} else if (strcmp(arg, "noclassgc") == 0) {
	    vmargs->enableClassGC = JNI_FALSE;
	} else if (strcmp(arg, "verify") == 0) {
	    vmargs->verifyMode = 2;
	} else if (strcmp(arg, "verifyremote") == 0) {
	    vmargs->verifyMode = 1;
	} else if (strcmp(arg, "noverify") == 0) {
	    vmargs->verifyMode = 0;
	} else if (strcmp(arg, "nojit") == 0) {
	    /**
	     * Set the value of java.compiler equal to the empty 
	     * string.  At the jit library loading step nothing will
	     * loaded.
	     */
	    AddProperty("java.compiler=");
	} else if (strcmp(arg, "v") == 0 || strcmp(arg, "verbose") == 0) {
	    vmargs->verbose = JNI_TRUE;
#ifdef JRE_DEBUG
	} else if (strcmp(arg, "d") == 0) {
	    debug = JNI_TRUE;
#endif
	} else if (strcmp(arg, "verbosegc") == 0) {
	    vmargs->enableVerboseGC = JNI_TRUE;
	} else if (strcmp(arg, "?") == 0 || strcmp(arg, "h") == 0 ||
		   strcmp(arg, "help") == 0) {
	    return -1;
	} else {
//	    fprintf(stderr, "Illegal option: -%s\n", arg);
		char messageStr[1024];
		sprintf(messageStr,"Illegal option: -%s", arg);
		MessageBox(NULL,messageStr,"",MB_OK);
	    return -1;
	}
    }
    *argcp -= --argv - *argvp;
    *argvp = argv;
    return 0;
}
Пример #8
0
int
main(int argc, char *argv[])
{
    int		sts;
    int		nport = 0;
    char	*envstr;
#ifdef HAVE_SA_SIGINFO
    static struct sigaction act;
#endif

    umask(022);
    __pmProcessDataSize(NULL);
    __pmGetUsername(&username);
    __pmSetInternalState(PM_STATE_PMCS);
    __pmServerSetFeature(PM_SERVER_FEATURE_DISCOVERY);
    __pmServerSetFeature(PM_SERVER_FEATURE_CONTAINERS);

    if ((envstr = getenv("PMCD_PORT")) != NULL)
	nport = __pmServerAddPorts(envstr);
    ParseOptions(argc, argv, &nport);
    if (nport == 0)
	__pmServerAddPorts(TO_STRING(SERVER_PORT));

    /* Set the local socket path. A message will be generated into the log
     * if this fails, but it is not fatal, since other connection options
     * may exist. 
     */
    __pmServerSetLocalSocket(sockpath);

    /* Set the service spec. This will cause our service to be advertised on
     * the network if that is supported.
     */
    __pmServerSetServiceSpec(PM_SERVER_SERVICE_SPEC);

    if (run_daemon) {
	fflush(stderr);
	StartDaemon(argc, argv);
    }

#ifdef HAVE_SA_SIGINFO
    act.sa_sigaction = SigIntProc;
    act.sa_flags = SA_SIGINFO;
    sigaction(SIGINT, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
#else
    __pmSetSignalHandler(SIGINT, SigIntProc);
    __pmSetSignalHandler(SIGTERM, SigIntProc);
#endif
    __pmSetSignalHandler(SIGHUP, SigHupProc);
    __pmSetSignalHandler(SIGBUS, SigBad);
    __pmSetSignalHandler(SIGSEGV, SigBad);

    if ((sts = __pmServerOpenRequestPorts(&clientFds, MAXPENDING)) < 0)
	DontStart();
    maxReqPortFd = maxClientFd = sts;

    __pmOpenLog(pmProgname, logfile, stderr, &sts);
    /* close old stdout, and force stdout into same stream as stderr */
    fflush(stdout);
    close(fileno(stdout));
    sts = dup(fileno(stderr));
    /* if this fails beware of the sky falling in */
    assert(sts >= 0);

    sts = pmLoadASCIINameSpace(pmnsfile, dupok);
    if (sts < 0) {
	fprintf(stderr, "Error: pmLoadASCIINameSpace(%s, %d): %s\n",
	    (pmnsfile == PM_NS_DEFAULT) ? "DEFAULT" : pmnsfile, dupok, pmErrStr(sts));
	DontStart();
    }

    if (ParseInitAgents(configFileName) < 0) {
	/* error already reported in ParseInitAgents() */
	DontStart();
    }

    if (nAgents <= 0) {
	fprintf(stderr, "Error: No PMDAs found in the configuration file \"%s\"\n",
		configFileName);
	DontStart();
    }

    if (run_daemon) {
	if (__pmServerCreatePIDFile(PM_SERVER_SERVICE_SPEC, PM_FATAL_ERR) < 0)
	    DontStart();
	if (__pmSetProcessIdentity(username) < 0)
	    DontStart();
    }

    if (__pmSecureServerSetup(certdb, dbpassfile) < 0)
	DontStart();

    PrintAgentInfo(stderr);
    __pmAccDumpLists(stderr);
    fprintf(stderr, "\npmcd: PID = %" FMT_PID, getpid());
    fprintf(stderr, ", PDU version = %u\n", PDU_VERSION);
    __pmServerDumpRequestPorts(stderr);
    fflush(stderr);

    /* all the work is done here */
    ClientLoop();

    Shutdown();
    exit(0);
}
Пример #9
0
int main(int argc, char **argv)
{
	CUNICODE_STRING us;
	THREAD *initial_thread = NULL;
	const char *exename;


	ParseOptions( argc, argv );

	if (optind == argc)
	{
		// default to starting smss.exe
		exename = "\\??\\c:\\winnt\\system32\\smss.exe";
	}
	else
	{
		exename = argv[optind];
	}

	// Read debug channels options
	DebugInit();

	// the skas3 patch is deprecated...
	if (0) InitSkas();

	// pass our path so thread tracing can find the client stub
	InitTt( argv[0] );
	if (!pCreateAddressSpace)
		Die("no way to manage address spaces found\n");

	if (!TraceIsEnabled("core"))
	{
		// enable backtraces
		signal(SIGSEGV, SegvHandler);
		signal(SIGABRT, AbortHandler);
	}

	if (RegistryIndex >= 0)
	{
		TRACE("created registry: %s\n",registry_list[RegistryIndex].name);
		Registry = registry_list[RegistryIndex].create();
	}
	else
	{
		TRACE("created registry: xml\n");
		Registry = REGISTRY_XML::Create();
	}

	// quick sanity test
	ALLOCATION_BITMAP::Test();

	// initialize boottime
	SYSTEM_TIME_OF_DAY_INFORMATION dummy;
	GetSystemTimeOfDay( dummy );

	FIBER::FibersInit();
	InitRoot();
	CreateDirectoryObject( (PWSTR) L"\\" );
	CreateDirectoryObject( (PWSTR) L"\\??" );
	CUNICODE_STRING link_name, link_target;
	link_name.Set( L"\\DosDevices" );
	link_target.Copy( L"\\??" );
	CreateSymlink( link_name, link_target );
	CreateDirectoryObject( (PWSTR) L"\\Device" );
	CreateDirectoryObject( (PWSTR) L"\\Device\\MailSlot" );
	CreateDirectoryObject( (PWSTR) L"\\Security" );
	//create_directory_object( (PWSTR) L"\\DosDevices" );
	CreateDirectoryObject( (PWSTR) L"\\BaseNamedObjects" );
	CreateSyncEvent( (PWSTR) L"\\Security\\LSA_AUTHENTICATION_INITIALIZED" );
	CreateSyncEvent( (PWSTR) L"\\SeLsaInitEvent" );
	InitRandom();
	InitPipeDevice();
	// XP
	CreateDirectoryObject( (PWSTR) L"\\KernelObjects" );
	CreateSyncEvent( (PWSTR) L"\\KernelObjects\\CritSecOutOfMemoryEvent" );
	InitDrives();
	InitNtDLL();
	CreateKThread();

	us.Copy( exename );

	int r = CreateInitialProcess( &initial_thread, us );
	if (r < STATUS_SUCCESS)
		Die("create_initial_process() failed (%08x)\n", r);

	// run the main loop
	Schedule();

	NtGdiFini();
	r = initial_thread->Process->ExitStatus;
	//fprintf(stderr, "process exited (%08x)\n", r);
	Release( initial_thread );

	ShutdownKThread();
	DoCleanup();

	FreeRoot();
	FIBER::FibersFinish();
	FreeNtDLL();

	return r;
}
Пример #10
0
int
main(int argc, char *argv[])
{
    int		sts;
    int		nport = 0;
    int		localhost = 0;
    int		maxpending = MAXPENDING;
    char	*envstr;

    umask(022);
    __pmGetUsername(&username);
    __pmSetInternalState(PM_STATE_PMCS);
    __pmServerSetFeature(PM_SERVER_FEATURE_DISCOVERY);

    if ((envstr = getenv("PMPROXY_PORT")) != NULL)
        nport = __pmServerAddPorts(envstr);
    if ((envstr = getenv("PMPROXY_LOCAL")) != NULL)
        if ((localhost = atoi(envstr)) != 0)
            __pmServerSetFeature(PM_SERVER_FEATURE_LOCAL);
    if ((envstr = getenv("PMPROXY_MAXPENDING")) != NULL)
        maxpending = atoi(envstr);
    ParseOptions(argc, argv, &nport);
    if (localhost)
        __pmServerAddInterface("INADDR_LOOPBACK");
    if (nport == 0)
        __pmServerAddPorts(TO_STRING(PROXY_PORT));
    GetProxyHostname();

    __pmServerSetServiceSpec(PM_SERVER_PROXY_SPEC);
    if (run_daemon) {
        fflush(stderr);
        StartDaemon(argc, argv);
        __pmServerCreatePIDFile(PM_SERVER_PROXY_SPEC, 0);
    }

    __pmSetSignalHandler(SIGHUP, SIG_IGN);
    __pmSetSignalHandler(SIGINT, SigIntProc);
    __pmSetSignalHandler(SIGTERM, SigIntProc);
    __pmSetSignalHandler(SIGBUS, SigBad);
    __pmSetSignalHandler(SIGSEGV, SigBad);

    /* Open request ports for client connections */
    if ((sts = __pmServerOpenRequestPorts(&sockFds, maxpending)) < 0)
        DontStart();
    maxReqPortFd = maxSockFd = sts;

    __pmOpenLog(pmProgname, logfile, stderr, &sts);
    /* close old stdout, and force stdout into same stream as stderr */
    fflush(stdout);
    close(fileno(stdout));
    if (dup(fileno(stderr)) == -1) {
        fprintf(stderr, "Warning: dup() failed: %s\n", pmErrStr(-oserror()));
    }

    fprintf(stderr, "pmproxy: PID = %" FMT_PID, getpid());
    fprintf(stderr, ", PDU version = %u\n", PDU_VERSION);
    __pmServerDumpRequestPorts(stderr);
    fflush(stderr);

    /* lose root privileges if we have them */
    __pmSetProcessIdentity(username);

    if (__pmSecureServerSetup(certdb, dbpassfile) < 0)
        DontStart();

    /* all the work is done here */
    ClientLoop();

    Shutdown();
    exit(0);
}
Пример #11
0
int main( int argc, char *argv[] )
{
  UINT4 i, j, k;
  const REAL4 tiny = 1e-6;

  CHAR  ifoCode[][3] = { "H1", "L1" };
  INT4  calTime[] = { 729331981, 729332039, 729332040, 729332041, 729332099,
    800000000 };
  CHAR  cacheTime[][21] = { "729273600-734367600", "729273600-734367600" };
  COMPLEX8 H1AlphaBeta[] = { {0.9883124570783, 0}, {0.9883124570783, 0},
    {1.123396433694, 0}, {1.123396433694, 0}, {1.123396433694, 0}, {0, 0} };
  COMPLEX8 L1AlphaBeta[] = { {0, 0}, {0, 0}, {0.6041572088741, 0},
    {0.6041572088741, 0}, {0.6041572088741, 0}, {0, 0} };

  static LALStatus      status;
  const CHAR            calCacheName[LALNameLength];
  LALCache             *calCache = NULL;
  UINT4                 numPoints = 262144;
  UINT4                 sampleRate = 4096;
  CHAR                  outFile[LALNameLength];
  LIGOTimeGPS           duration = {0,0};

  COMPLEX8FrequencySeries       response;
  const LALUnit strainPerCount = {0,{0,0,0,0,0,1,-1},{0,0,0,0,0,0,0}};

  ParseOptions (argc, argv);

  /* clear the response function and create storage for the frequency series */
  memset( &response, 0, sizeof(COMPLEX8FrequencySeries) );
  LALCCreateVector( &status, &(response.data), numPoints / 2 + 1 );
  TESTSTATUS( &status );

  /* set the parameters of the response function to generate */
  response.deltaF = (REAL8) sampleRate / (REAL8) numPoints;
  response.sampleUnits = strainPerCount;

  /* loop over the three interferometers */
  for ( j = 0; j < sizeof(ifoCode) / sizeof(*ifoCode); ++j )
  {
    snprintf( response.name, LALNameLength * sizeof(CHAR),
        CHANNEL, ifoCode[j] );

    for ( i = 0; i < sizeof(calTime) / sizeof(*calTime); ++i )
    {
      /* set the time of the calibration and the frame cahche file to use */
      snprintf( calCacheName, LALNameLength * sizeof(CHAR), CAL_CATALOG,
          ifoCode[j], cacheTime[i % 2] );
      response.epoch.gpsSeconds = calTime[i];
      if ( verbose )
      {
        fprintf( stdout, "Calibration for GPS time %d from %s\n",
            response.epoch.gpsSeconds, calCacheName );
        fflush( stdout );
      }

      /* create the response function */
      LALExtractFrameResponse( &status, &response, calCacheName, ifoCode[j],
          &duration );
      if ( status.statusCode == -1 && status.statusPtr )
      {
        if ( status.statusPtr->statusCode == FRAMESTREAMH_EDONE &&
            calTime[i] == 800000000 )
        {
          /* no calibration for this time */
          if ( verbose )
          {
            fprintf( stderr, "OK: No calibration for 800000000\n" );
            LALPrintError( "OK: %s\n", status.statusPtr->statusDescription );
          }
          CLEARSTATUS( status );
        }
        else if ( status.statusPtr->statusCode == CALIBRATIONH_EZERO &&
            ! strncmp( ifoCode[j], "L1", 2 * sizeof(CHAR) ) &&
            (calTime[i] == 729331981 || calTime[i] == 729332039) )
        {
          /* alpha is zero at this time */
          if ( verbose )
          {
            fprintf( stderr, "OK: Cal is zero for L1 at 729332039\n" );
            LALPrintError( "OK: %s\n", status.statusPtr->statusDescription );
          }
          CLEARSTATUS( status );
        }
        else
        {
          /* some other error */
          TESTSTATUS( &status );
        }
      }
      else
      {
        TESTSTATUS( &status );

        /* FIXME check that the values match the expected ones          */
        /* H1AlphaBeta[i] and L1AlphaBeta[i] give the correct values    */
        /* for this i, so we need to check that the returned values     */
        /* match the expected ones up to tiny. Need to if on j to get   */
        /* the correct ifo                                              */

        /* test that the response does not contain NaN or Inf */
        for ( k = 0; k < response.data->length; ++k )
        {
          if ( (! finite( response.data->data[k].re )) ||
              (! finite( response.data->data[k].im )) )
          {
            fprintf( stderr, "ERROR: non-finite value found in response "
                "at k = %d (%e,%e)\n",
                k, response.data->data[k].re, response.data->data[k].im );
            exit( 1 );
          }
        }

        /* print out the response function */
        if ( verbose )
        {
          fprintf( stdout, "Calibration updated\n" );
          fflush( stdout );
        }
        if ( output )
        {
          snprintf( outFile, LALNameLength * sizeof(CHAR),
              "Response-%s-%d.txt", ifoCode[j], response.epoch.gpsSeconds );
          LALCPrintFrequencySeries( &response, outFile );
        }
      }
    }
  }

  /* free memory */
  LALCDestroyVector( &status, &(response.data) );
  TESTSTATUS( &status );

  LALCheckMemoryLeaks();
  return 0;
}
Пример #12
0
int
main (int argc, char *argv[])
{
  static LALStatus  status;
  SFindRootIn    sinput;
  DFindRootIn    dinput;
  REAL4          y_0;
  REAL4          sroot;
  REAL8          yy0;
  REAL8          droot;


  /*
   *
   * Parse the command line options
   *
   */


  ParseOptions (argc, argv);


  /*
   *
   * Set up input structure and function parameter y_0.
   *
   */


  y_0             = -1;
  sinput.function = F;
  sinput.xmin     = 1e-3;
  sinput.xmax     = 2e-3;
  sinput.xacc     = 1e-6;
  yy0             = -1;
  dinput.function = FF;
  dinput.xmin     = 1e-3;
  dinput.xmax     = 2e-3;
  dinput.xacc     = 1e-15;


  /*
   *
   * Check to see if bracketing and root finding work.
   *
   */


  if (verbose)
  {
    printf ("\n===== Check Root Finding =====\n\n");
  }

  if (verbose)
  {
    printf ("Initial domain: [%e,%e]\n", dinput.xmin, dinput.xmax);
  }

  LALSBracketRoot (&status, &sinput, &y_0);
  TestStatus (&status, CODES(0), 1);

  if (verbose)
  {
    printf ("Bracket domain: [%e,%e]\n", sinput.xmin, sinput.xmax);
  }

  if (sinput.xmin > 1 || sinput.xmax < 1)
  {
    fprintf (stderr, "Root not bracketed correctly\n");
    return 1;
  }

  LALDBracketRoot (&status, &dinput, &yy0);
  TestStatus (&status, CODES(0), 1);

  if (verbose)
  {
    printf ("Bracket domain: [%e,%e]\n", dinput.xmin, dinput.xmax);
  }

  if (dinput.xmin > 1 || dinput.xmax < 1)
  {
    fprintf (stderr, "Root not bracketed correctly\n");
    return 1;
  }


  LALSBisectionFindRoot (&status, &sroot, &sinput, &y_0);
  TestStatus (&status, CODES(0), 1);

  if (verbose)
  {
    printf ("Root = %e (acc = %e)\n", sroot, sinput.xacc);
  }

  if (fabs(sroot - 1) > sinput.xacc)
  {
    fprintf (stderr, "Root not found to correct accuracy\n");
    return 1;
  }


  LALDBisectionFindRoot (&status, &droot, &dinput, &yy0);
  TestStatus (&status, CODES(0), 1);

  if (verbose)
  {
    printf ("Root = %.15e (acc = %e)\n", droot, dinput.xacc);
  }

  if (fabs(droot - 1) > dinput.xacc)
  {
    fprintf (stderr, "Root not found to correct accuracy\n");
    return 1;
  }


  /*
   *
   * Check to make sure that correct error codes are generated.
   *
   */

#ifndef LAL_NDEBUG

  if ( ! lalNoDebug )
  {

    if (verbose || lalDebugLevel)
    {
      printf ("\n===== Check Errors =====\n");
    }

    /* recursive error from an error occurring in the function */

    if (verbose)
    {
      printf ("\n----- Recursive Error: Code -1 (2 times)\n");
    }

    LALSBracketRoot (&status, &sinput, NULL);
    TestStatus  (&status, CODES(-1), 1);
    ClearStatus (&status);
    LALDBracketRoot (&status, &dinput, NULL);
    TestStatus  (&status, CODES(-1), 1);
    ClearStatus (&status);

    /* one of the arguments is a null pointer */

    if (verbose)
    {
      printf ("\n----- Null Pointer Error: Code 1 (10 times)\n");
    }

    LALSBracketRoot (&status, NULL, &y_0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);
    LALDBracketRoot (&status, NULL, &yy0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);

    LALSBisectionFindRoot (&status, NULL, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);
    LALDBisectionFindRoot (&status, NULL, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);

    LALSBisectionFindRoot (&status, &sroot, NULL, &y_0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);
    LALDBisectionFindRoot (&status, &droot, NULL, &yy0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);

    sinput.function = NULL;
    dinput.function = NULL;

    LALSBracketRoot (&status, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);
    LALDBracketRoot (&status, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);

    LALSBisectionFindRoot (&status, &sroot, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);
    LALDBisectionFindRoot (&status, &droot, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_ENULL), 1);

    /* invalid initial domain error for BracketRoot() */

    if (verbose)
    {
      printf ("\n----- Invalid Initial Domain: Code 2 (2 times)\n");
    }

    sinput.function = F;
    sinput.xmin     = 5;
    sinput.xmax     = 5;
    dinput.function = FF;
    dinput.xmin     = 5;
    dinput.xmax     = 5;

    LALSBracketRoot (&status, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_EIDOM), 1);
    LALDBracketRoot (&status, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_EIDOM), 1);

    /* maximum iterations exceeded error */

    if (verbose)
    {
      printf ("\n----- Maximum Iteration Exceeded: Code 4 (4 times)\n");
    }

    y_0             = 1; /* there is no root when y_0 > 0 */
    sinput.xmin     = -1e-18;
    sinput.xmax     = 1e-18;
    yy0             = 1; /* there is no root when y_0 > 0 */
    dinput.xmin     = -1e-18;
    dinput.xmax     = 1e-18;

    LALSBracketRoot (&status, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_EMXIT), 1);
    LALDBracketRoot (&status, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_EMXIT), 1);

    y_0             = -1;
    sinput.xmin     = 0;
    sinput.xmax     = 1e19;
    sinput.xacc     = 2e-38;
    yy0             = -1;
    dinput.xmin     = 0;
    dinput.xmax     = 1e19;
    dinput.xacc     = 2e-38;

    LALSBisectionFindRoot (&status, &sroot, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_EMXIT), 1);
    LALDBisectionFindRoot (&status, &droot, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_EMXIT), 1);

    /* root not bracketed error in BisectionFindRoot() */

    if (verbose)
    {
      printf ("\n----- Root Not Bracketed: Code 8 (2 times)\n");
    }

    sinput.xmin     = -5;
    sinput.xmax     = -3;
    sinput.xacc     = 1e-6;
    dinput.xmin     = -5;
    dinput.xmax     = -3;
    dinput.xacc     = 1e-6;

    LALSBisectionFindRoot (&status, &sroot, &sinput, &y_0);
    TestStatus (&status, CODES(FINDROOTH_EBRKT), 1);
    LALDBisectionFindRoot (&status, &droot, &dinput, &yy0);
    TestStatus (&status, CODES(FINDROOTH_EBRKT), 1);

  }

#endif

  return 0;
}
Пример #13
0
int main(int argc, char *argv[])
{
    int err = -1;
    TestArgs testArgs;

    CaptureInputHandle handle;

    NvMediaVideoCapture *vipCapture = NULL;
    NvMediaDevice *device = NULL;
    NvMediaVideoMixer *vipMixer = NULL;
    NvMediaVideoOutput *vipOutput[2] = {NULL, NULL};
    NvMediaVideoOutput *nullOutputList[1] = {NULL};
    FILE *vipFile = NULL;

    NvSemaphore *vipStartSem = NULL, *vipDoneSem = NULL;
    NvThread *vipThread = NULL;

    CaptureContext vipCtx;
    NvMediaBool deviceEnabled = NVMEDIA_FALSE;
    unsigned int displayId;

    pthread_t cntThread;

    signal(SIGINT, SignalHandler);

    memset(&testArgs, 0, sizeof(TestArgs));
    if(!ParseOptions(argc, argv, &testArgs))
        return -1;

    printf("1. Create NvMedia capture \n");
    // Create NvMedia capture(s)
    switch (testArgs.vipDeviceInUse)
    {
        case AnalogDevices_ADV7180:
            break;
        case AnalogDevices_ADV7182:
        {
            CaptureInputConfigParams params;

            params.width = testArgs.vipInputWidth;
            params.height = testArgs.vipInputHeight;
            params.vip.std = testArgs.vipInputtVideoStd;

            if(testutil_capture_input_open(testArgs.i2cDevice, testArgs.vipDeviceInUse, NVMEDIA_TRUE, &handle) < 0)
            {
                MESSAGE_PRINTF("Failed to open VIP device\n");
                goto fail;
            }

            if(testutil_capture_input_configure(handle, &params) < 0)
            {
                MESSAGE_PRINTF("Failed to configure VIP device\n");
                goto fail;
            }

            break;
        }
        default:
            MESSAGE_PRINTF("Bad VIP device\n");
            goto fail;
    }


    if(!(vipCapture = NvMediaVideoCaptureCreate(testArgs.vipInputtVideoStd, // interfaceFormat
                                                NULL, // settings
                                                VIP_BUFFER_SIZE)))// numBuffers
    {
        MESSAGE_PRINTF("NvMediaVideoCaptureCreate() failed for vipCapture\n");
        goto fail;
    }


    printf("2. Create NvMedia device \n");
    // Create NvMedia device
    if(!(device = NvMediaDeviceCreate()))
    {
        MESSAGE_PRINTF("NvMediaDeviceCreate() failed\n");
        goto fail;
    }

    printf("3. Create NvMedia mixer(s) and output(s) and bind them \n");
    // Create NvMedia mixer(s) and output(s) and bind them
    unsigned int features = 0;


    features |= NVMEDIA_VIDEO_MIXER_FEATURE_VIDEO_SURFACE_TYPE_YV16X2;
    features |= NVMEDIA_VIDEO_MIXER_FEATURE_PRIMARY_VIDEO_DEINTERLACING; // Bob the 16x2 format by default
    if(testArgs.vipOutputType != NvMediaVideoOutputType_OverlayYUV)
        features |= NVMEDIA_VIDEO_MIXER_FEATURE_DVD_MIXING_MODE;

    if(!(vipMixer = NvMediaVideoMixerCreate(device, // device
                                            testArgs.vipMixerWidth, // mixerWidth
                                            testArgs.vipMixerHeight, // mixerHeight
                                            testArgs.vipAspectRatio, //sourceAspectRatio
                                            testArgs.vipInputWidth, // primaryVideoWidth
                                            testArgs.vipInputHeight, // primaryVideoHeight
                                            0, // secondaryVideoWidth
                                            0, // secondaryVideoHeight
                                            0, // graphics0Width
                                            0, // graphics0Height
                                            0, // graphics1Width
                                            0, // graphics1Height
                                            features , // features
                                            nullOutputList))) // outputList
    {
        MESSAGE_PRINTF("NvMediaVideoMixerCreate() failed for vipMixer\n");
        goto fail;
    }

    printf("4. Check that the device is enabled (initialized) \n");
    // Check that the device is enabled (initialized)
    CheckDisplayDevice(
        testArgs.vipOutputDevice[0],
        &deviceEnabled,
        &displayId);

    if((vipOutput[0] = NvMediaVideoOutputCreate(testArgs.vipOutputType, // outputType
                                                testArgs.vipOutputDevice[0], // outputDevice
                                                NULL, // outputPreference
                                                deviceEnabled, // alreadyCreated
                                                displayId, // displayId
                                                NULL))) // displayHandle
    {
        if(NvMediaVideoMixerBindOutput(vipMixer, vipOutput[0], NVMEDIA_OUTPUT_DEVICE_0) != NVMEDIA_STATUS_OK)
        {
            MESSAGE_PRINTF("Failed to bind VIP output to mixer\n");
            goto fail;
        }
    }
    else
    {
        MESSAGE_PRINTF("NvMediaVideoOutputCreate() failed for vipOutput\n");
        goto fail;
    }



    printf("5. Open output file(s) \n");
    // Open output file(s)
    if(testArgs.vipFileDumpEnabled)
    {
        vipFile = fopen(testArgs.vipOutputFileName, "w");
        if(!vipFile || ferror(vipFile))
        {
            MESSAGE_PRINTF("Error opening output file for VIP\n");
            goto fail;
        }
    }

    printf("6. Create vip pool(s), queue(s), fetch threads and stream start/done semaphores \n");
    // Create vip pool(s), queue(s), fetch threads and stream start/done semaphores
    if(NvSemaphoreCreate(&vipStartSem, 0, 1) != RESULT_OK)
    {
        MESSAGE_PRINTF("NvSemaphoreCreate() failed for vipStartSem\n");
        goto fail;
    }

    if(NvSemaphoreCreate(&vipDoneSem, 0, 1) != RESULT_OK)
    {
        MESSAGE_PRINTF("NvSemaphoreCreate() failed for vipDoneSem\n");
        goto fail;
    }

    vipCtx.name = VIP_NAME;

    vipCtx.semStart = vipStartSem;
    vipCtx.semDone = vipDoneSem;

    vipCtx.capture = vipCapture;
    vipCtx.mixer = vipMixer;
    vipCtx.fout = vipFile;

    vipCtx.inputWidth = testArgs.vipInputWidth;
    vipCtx.inputHeight = testArgs.vipInputHeight;

    vipCtx.timeout = VIP_FRAME_TIMEOUT_MS;

    vipCtx.displayEnabled = testArgs.vipDisplayEnabled;
    vipCtx.fileDumpEnabled = testArgs.vipFileDumpEnabled;

    if(testArgs.vipCaptureTime)
    {
        vipCtx.timeNotCount = NVMEDIA_TRUE;
        vipCtx.last = testArgs.vipCaptureTime;
    }
    else
    {
        vipCtx.timeNotCount = NVMEDIA_FALSE;
        vipCtx.last = testArgs.vipCaptureCount;
    }


    if(NvThreadCreate(&vipThread, CaptureThread, &vipCtx, NV_THREAD_PRIORITY_NORMAL) != RESULT_OK)
    {
        MESSAGE_PRINTF("NvThreadCreate() failed for vipThread\n");
        goto fail;
    }

    printf("wait for ADV7182 ... one second\n");
    sleep(1);

    printf("7. Kickoff \n");
    // Kickoff
    NvMediaVideoCaptureStart(vipCapture);
    NvSemaphoreIncrement(vipStartSem);

    printf("8. Control Thread\n");
    YUV2RGVtableInit();
    pthread_create(&cntThread, NULL, &ControlThread, NULL);

    printf("9. Wait for completion \n");
    // Wait for completion
    NvSemaphoreDecrement(vipDoneSem, NV_TIMEOUT_INFINITE);


    err = 0;

fail: // Run down sequence
    // Destroy vip threads and stream start/done semaphores
    if(vipThread)
        NvThreadDestroy(vipThread);
    if(vipDoneSem)
        NvSemaphoreDestroy(vipDoneSem);
    if(vipStartSem)
        NvSemaphoreDestroy(vipStartSem);

    printf("10. Close output file(s) \n");
    // Close output file(s)
    if(vipFile)
        fclose(vipFile);

    // Unbind NvMedia mixer(s) and output(s) and destroy them
    if(vipOutput[0])
    {
        NvMediaVideoMixerUnbindOutput(vipMixer, vipOutput[0], NULL);
        NvMediaVideoOutputDestroy(vipOutput[0]);
    }
    if(vipOutput[1])
    {
        NvMediaVideoMixerUnbindOutput(vipMixer, vipOutput[1], NULL);
        NvMediaVideoOutputDestroy(vipOutput[1]);
    }
    if(vipMixer)
        NvMediaVideoMixerDestroy(vipMixer);


    // Destroy NvMedia device
    if(device)
        NvMediaDeviceDestroy(device);

    // Destroy NvMedia capture(s)
    if(vipCapture)
    {
        NvMediaVideoCaptureDestroy(vipCapture);

        // Reset VIP settings of the board
        switch (testArgs.vipDeviceInUse)
        {
            case AnalogDevices_ADV7180: // TBD
                break;
            case AnalogDevices_ADV7182: // TBD
                //testutil_capture_input_close(handle);
                break;
            default:
                break;
        }
    }

    return err;
}
int main( int argc, char *argv[] )
{
  static LALStatus status;

  RealFFTPlan    *fwd = NULL;
  RealFFTPlan    *rev = NULL;
  REAL4Vector    *dat = NULL;
  REAL4Vector    *rfft = NULL;
  REAL4Vector    *ans = NULL;
  COMPLEX8Vector *dft = NULL;
  COMPLEX8Vector *fft = NULL;
#if LAL_CUDA_ENABLED
  /* The test itself should pass at 1e-4, but it might fail at
   * some rare cases where accuracy is bad for some numbers. */
  REAL8           eps = 3e-4;
#else
  /* very conservative floating point precision */
  REAL8           eps = 1e-6;
#endif
  REAL8           lbn;
  REAL8           ssq;
  REAL8           var;
  REAL8           tol;

  UINT4 nmax;
  UINT4 m;
  UINT4 n;
  UINT4 i;
  UINT4 j;
  UINT4 k;
  UINT4 s = 0;

  FILE *fp;


  ParseOptions( argc, argv );
  m = m_;
  n = n_;

  fp = verbose ? stdout : NULL ;

  if ( n == 0 )
  {
    nmax = 65536;
  }
  else
  {
    nmax = n--;
  }

  while ( n < nmax )
  {
    if ( n < 128 )
    {
      ++n;
    }
    else
    {
      n *= 2;
    }

    LALSCreateVector( &status, &dat, n );
    TestStatus( &status, CODES( 0 ), 1 );
    LALSCreateVector( &status, &rfft, n );
    TestStatus( &status, CODES( 0 ), 1 );
    LALSCreateVector( &status, &ans, n );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCCreateVector( &status, &dft, n / 2 + 1 );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCCreateVector( &status, &fft, n / 2 + 1 );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCreateForwardRealFFTPlan( &status, &fwd, n, 0 );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCreateReverseRealFFTPlan( &status, &rev, n, 0 );
    TestStatus( &status, CODES( 0 ), 1 );

    /*
     *
     * Do m trials of random data.
     *
     */
    for ( i = 0; i < m; ++i )
    {
      srand( s++ ); /* seed the random number generator */

      /*
       *
       * Create data and compute error tolerance.
       *
       * Reference: Kaneko and Liu,
       * "Accumulation of round-off error in fast fourier tranforms"
       * J. Asssoc. Comp. Mach, Vol 17 (No 4) 637-654, October 1970.
       *
       */
      srand( i ); /* seed the random number generator */
      ssq = 0;
      for ( j = 0; j < n; ++j )
      {
        dat->data[j] = 20.0 * rand() / (REAL4)( RAND_MAX + 1.0 ) - 10.0;
        ssq += dat->data[j] * dat->data[j];
        fp ? fprintf( fp, "%e\n", dat->data[j] ) : 0;
      }
      lbn = log( n ) / log( 2 );
      var = 2.5 * lbn * eps * eps * ssq / n;
      tol = 5 * sqrt( var ); /* up to 5 sigma excursions */
      fp ? fprintf( fp, "\neps = %e \ntol = %e\n", eps, tol ) : 0;

      /*
       *
       * Perform forward FFT and DFT (only if n < 100).
       *
       */
      LALForwardRealFFT( &status, fft, dat, fwd );
      TestStatus( &status, CODES( 0 ), 1 );
      LALREAL4VectorFFT( &status, rfft, dat, fwd );
      TestStatus( &status, CODES( 0 ), 1 );
      LALREAL4VectorFFT( &status, ans, rfft, rev );
      TestStatus( &status, CODES( 0 ), 1 );
      fp ?  fprintf( fp, "rfft()\t\trfft(rfft())\trfft(rfft())\n\n"  ) : 0;
      for ( j = 0; j < n; ++j )
      {
        fp ? fprintf( fp, "%e\t%e\t%e\n",
            rfft->data[j], ans->data[j], ans->data[j] / n ) : 0;
      }
      if ( n < 128 )
      {
        LALForwardRealDFT( &status, dft, dat );
        TestStatus( &status, CODES( 0 ), 1 );

        /*
         *
         * Check accuracy of FFT vs DFT.
         *
         */
        fp ? fprintf( fp, "\nfftre\t\tfftim\t\t" ) : 0;
        fp ? fprintf( fp, "dtfre\t\tdftim\n" ) : 0;
        for ( k = 0; k <= n / 2; ++k )
        {
          REAL8 fftre = creal(fft->data[k]);
          REAL8 fftim = cimag(fft->data[k]);
          REAL8 dftre = creal(dft->data[k]);
          REAL8 dftim = cimag(dft->data[k]);
          REAL8 errre = fabs( dftre - fftre );
          REAL8 errim = fabs( dftim - fftim );
          REAL8 avere = fabs( dftre + fftre ) / 2 + eps;
          REAL8 aveim = fabs( dftim + fftim ) / 2 + eps;
          REAL8 ferre = errre / avere;
          REAL8 ferim = errim / aveim;
          fp ? fprintf( fp, "%e\t%e\t", fftre, fftim ) : 0;
          fp ? fprintf( fp, "%e\t%e\n", dftre, dftim ) : 0;
          /* fp ? fprintf( fp, "%e\t%e\t", errre, errim ) : 0; */
          /* fp ? fprintf( fp, "%e\t%e\n", ferre, ferim ) : 0; */
          if ( ferre > eps && errre > tol )
          {
            fputs( "FAIL: Incorrect result from forward transform\n", stderr );
            fprintf( stderr, "\tdifference = %e\n", errre );
            fprintf( stderr, "\ttolerance  = %e\n", tol );
            fprintf( stderr, "\tfrac error = %e\n", ferre );
            fprintf( stderr, "\tprecision  = %e\n", eps );
            return 1;
          }
          if ( ferim > eps && errim > tol )
          {
            fputs( "FAIL: Incorrect result from forward transform\n", stderr );
            fprintf( stderr, "\tdifference = %e\n", errim );
            fprintf( stderr, "\ttolerance  = %e\n", tol );
            fprintf( stderr, "\tfrac error = %e\n", ferim );
            fprintf( stderr, "\tprecision  = %e\n", eps );
            return 1;
          }
        }
      }

      /*
       *
       * Perform reverse FFT and check accuracy vs original data.
       *
       */
      LALReverseRealFFT( &status, ans, fft, rev );
      TestStatus( &status, CODES( 0 ), 1 );
      fp ? fprintf( fp, "\ndat->data[j]\tans->data[j] / n\n" ) : 0;
      for ( j = 0; j < n; ++j )
      {
        REAL8 err = fabs( dat->data[j] - ans->data[j] / n );
        REAL8 ave = fabs( dat->data[j] + ans->data[j] / n ) / 2 + eps;
        REAL8 fer = err / ave;
        fp ? fprintf( fp, "%e\t%e\n", dat->data[j], ans->data[j] / n ) : 0;
        /* fp ? fprintf( fp, "%e\t%e\n", err, fer ) : 0; */
        if ( fer > eps && err > tol )
        {
          fputs( "FAIL: Incorrect result after reverse transform\n", stderr );
          fprintf( stderr, "\tdifference = %e\n", err );
          fprintf( stderr, "\ttolerance  = %e\n", tol );
          fprintf( stderr, "\tfrac error = %e\n", fer );
          fprintf( stderr, "\tprecision  = %e\n", eps );
          return 1;
        }
      }
    }

    LALSDestroyVector( &status, &dat );
    TestStatus( &status, CODES( 0 ), 1 );
    LALSDestroyVector( &status, &rfft );
    TestStatus( &status, CODES( 0 ), 1 );
    LALSDestroyVector( &status, &ans );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCDestroyVector( &status, &dft );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCDestroyVector( &status, &fft );
    TestStatus( &status, CODES( 0 ), 1 );
    LALDestroyRealFFTPlan( &status, &fwd );
    TestStatus( &status, CODES( 0 ), 1 );
    LALDestroyRealFFTPlan( &status, &rev );
    TestStatus( &status, CODES( 0 ), 1 );
  }

  LALCheckMemoryLeaks();
  return 0;
}
Пример #15
0
int
main(int argc,          // IN
     char *argv[])      // IN
{
#ifdef VM_HAVE_MTAB
   Bool doMtab = TRUE;
#endif
   char c;
   int i;
   int result = EXIT_FAILURE;
   int flags = 0;
   int mntRes = -1;
   char *optionString = NULL;
   const char *shareNameHost = NULL;
   const char *shareNameDir = NULL;
   struct stat statBuf;
   HgfsMountInfo mountInfo;
   char *canonicalizedPath = NULL;
   size_t pathMax;

   thisProgram = argv[0];

   /* Compute the base name of the program, too. */
   thisProgramBase = strrchr(thisProgram, '/');
   if (thisProgramBase != NULL) {
      thisProgramBase++;
   } else {
      thisProgramBase = thisProgram;
   }
   setpwent();

   if (argc < 3) {
      PrintUsage();
   }

   while ((c = getopt(argc, argv, "hno:vV")) != -1) {
      switch (c) {
      case '?':
      case 'h':
         PrintUsage();
#ifdef VM_HAVE_MTAB
      case 'n':
         doMtab = FALSE;
         break;
#endif
      case 'o':
         if (optionString == NULL) {
            optionString = strdup(optarg);
         } else {
            size_t newLength;
            char *savedString = optionString;
            newLength = strlen(optionString) + strlen(",") +
                        strlen(optarg) + sizeof '\0';
            optionString = realloc(optionString, newLength);
            if (optionString != NULL) {
               Str_Strcat(optionString, ",", newLength);
               Str_Strcat(optionString, optarg, newLength);
            } else {
               free(savedString);
            }
         }
         if (optionString == NULL) {
            printf("Error: could not allocate memory for options\n");
            goto out;
         }
         break;
      case 'v':
         beVerbose = TRUE;
         break;
      case 'V':
         PrintVersion();
      default:
         printf("Error: unknown mount option %c\n", c);
         PrintUsage();
      }
   }

   LOG("Original command line: \"%s", thisProgram);
   for (i = 1; i < argc; i++) {
      LOG(" %s", argv[i]);
   }
   LOG("\"\n");

   /* After getopt_long(3), optind is the first non-option argument. */
   shareName = argv[optind];
   mountPoint = argv[optind + 1];

   /*
    * We canonicalize the mount point to avoid any discrepancies between the actual mount
    * point and the listed mount point in /etc/mtab (such discrepancies could prevent
    * umount(8) from removing the mount point from /etc/mtab).
    */
   pathMax = GetPathMax(mountPoint);
   canonicalizedPath = malloc(pathMax * sizeof *canonicalizedPath);
   if (canonicalizedPath == NULL) {
      printf("Error: cannot allocate memory for canonicalized path, "
             "aborting mount\n");
      goto out;
   } else if (!realpath(mountPoint, canonicalizedPath)) {
      perror("Error: cannot canonicalize mount point");
      goto out;
   }
   mountPoint = canonicalizedPath;

   if (!ParseShareName(shareName, &shareNameHost, &shareNameDir)) {
      printf("Error: share name is invalid, aborting mount\n");
      goto out;
   }

   mountInfo.magicNumber = HGFS_SUPER_MAGIC;
   mountInfo.infoSize = sizeof mountInfo;
   mountInfo.version = HGFS_PROTOCOL_VERSION;

#ifndef sun
   mountInfo.fmask = 0;
   mountInfo.dmask = 0;
   mountInfo.uidSet = FALSE;
   mountInfo.gidSet = FALSE;
   mountInfo.ttl = HGFS_DEFAULT_TTL;
#if defined(__APPLE__)
   strlcpy(mountInfo.shareNameHost, shareNameHost, MAXPATHLEN);
   strlcpy(mountInfo.shareNameDir, shareNameDir, MAXPATHLEN);
#else
   mountInfo.shareNameHost = shareNameHost;
   mountInfo.shareNameDir = shareNameDir;
#endif
#endif
   /*
    * Default flags which maybe modified by user passed options.
    */
   mountInfo.flags = HGFS_MNTINFO_SERVER_INO;

   /*
    * This'll write the rest of the options into HgfsMountInfo and possibly
    * modify the flags.
    */
   if (optionString && !ParseOptions(optionString, &mountInfo, &flags)) {
      printf("Error: could not parse options string\n");
      goto out;
   }

   /* Do some sanity checks on our desired mount point. */
   if (stat(mountPoint, &statBuf)) {
      perror("Error: cannot stat mount point");
      goto out;
   }
   if (S_ISDIR(statBuf.st_mode) == 0) {
      printf("Error: mount point \"%s\" is not a directory\n", mountPoint);
      goto out;
   }

   /*
    * Must be root in one flavor or another. If we're suid root, only proceed
    * if the user owns the mountpoint.
    */
   if (geteuid() != 0) {
      printf("Error: either you're not root, or %s isn't installed SUID\n",
             thisProgram);
      goto out;
   } else if (getuid() != 0 && (getuid() != statBuf.st_uid ||
                                (statBuf.st_mode & S_IRWXU) != S_IRWXU)) {
      printf("Error: for user mounts, user must own the mount point\n");
      goto out;
   }

   /* Go! */
#if defined(linux)
   mntRes = mount(shareName, mountPoint, HGFS_NAME, flags, &mountInfo);
#elif defined(__FreeBSD__)
   {
      struct iovec iov[] = {{"fstype", sizeof("fstype")},
                            {HGFS_NAME, sizeof(HGFS_NAME)},
                            {"target", sizeof("target")},
                            {shareName, strlen(shareName) + 1},
                            {"fspath", sizeof("fspath")},
                            {(void *)mountPoint, strlen(mountPoint) + 1},
                            {"uidSet", sizeof("uidSet")},
                            {&mountInfo.uidSet, sizeof(mountInfo.uidSet)},
                            {"uid", sizeof("uid")},
                            {&mountInfo.uid, sizeof(mountInfo.uid)},
                            {"gidSet", sizeof("gidSet")},
                            {&mountInfo.gidSet, sizeof(mountInfo.gidSet)},
                            {"gid", sizeof("gid")},
                            {&mountInfo.gid, sizeof(mountInfo.gid)}};

      mntRes = nmount(iov, ARRAYSIZE(iov), flags);
   }
#elif defined(__APPLE__)
   mntRes = mount(HGFS_NAME, mountPoint, flags, &mountInfo);
#elif defined(sun)
   mntRes = mount(mountPoint, mountPoint, MS_DATA | flags, HGFS_NAME,
                  &mountInfo, sizeof mountInfo);
#endif
   if (mntRes) {
      perror("Error: cannot mount filesystem");
      goto out;
   }
   result = EXIT_SUCCESS;

#ifdef VM_HAVE_MTAB
   if (doMtab) {
      UpdateMtab(&mountInfo, flags);
   }
#endif

  out:
   free(optionString);
   free(canonicalizedPath);
   return result;
}
Пример #16
0
int
main(int argc, char** argv)
{
    eid_t e5_file_id;
    eid_t e5_group_id;
    estatus_t status;
    
    /* Parse the command line options
     */
    options_t options = {0};
    ParseOptions(&options, argc, argv);

    /* Open the E5 file and main group
     */
    e5_set_notify_func(E5_DEFAULT, notify_func, E5_NOTIFY_LEVEL_MIN, E5_NOTIFY_LEVEL_MAX);
    e5_file_id = e5_open_file(options.filename);

    /* Read the grid dimensionality and type info
     */
    if(options.type == OPT_GRID)
    {
        e5_grid_dataset grid = { 0 };
        grid.name = options.location;
        status = e5_read_data_info(e5_file_id, grid.name, grid.dim, &grid.type, &grid.scale);
        E5_EXIT_ON_ERROR(status);
        
        /* Allocate memory and read the grid data
         */
        grid.data = malloc(e5_sizeof(grid.type) * grid.dim[0] * grid.dim[1] * grid.dim[2]);
        status = e5_read_grid(e5_file_id, grid.name, grid.data, grid.dim, &grid.type, &grid.scale);
        E5_EXIT_ON_ERROR(status);
        
        e5_dump_grid(&grid);
        free(grid.data);
    }
    else if (options.type == OPT_ATTR)
    {
        int* data = malloc(sizeof(int));

        const char* base_name = e5_basename(options.location);
        size_t offset = base_name - options.location;
        char* group_name = malloc(offset + 2);
        snprintf(group_name, offset, "%s", options.location);
    
        e5_group_id = e5_open_group(e5_file_id, group_name);           
        e5_attr attr[] = { {base_name, data, E5_TYPE_INT, 0}, {0} };
        status = e5_read_attr_list(e5_group_id, attr);
        E5_EXIT_ON_ERROR(status);
        
        printf("ATTR: '%s' -> '%d'\n", options.location, *data);

        free(data);
        free(group_name);
        e5_close_group(e5_group_id);
    }

    /* Close the group and the file 
     */
    status = e5_close_file(e5_file_id);
    E5_EXIT_ON_ERROR(status);
    
    /* Free the command line options
     */
    free(options.filename);
    free(options.location);
    return 0;
}
Пример #17
0
int main(
    _In_ int argc,
    _In_ TCHAR * argv[]
    ) {
    DWORD i = 0;

    LOG(Succ, _T("Starting"));

    //
    // Options parsing
    //
    LOG(Succ, _T("Parsing options"));
    ACE_FILTER_OPTIONS options = { 0 };
    DWORD importerAce = PLUGIN_MAX_IMPORTERS;
    DWORD importerObj = PLUGIN_MAX_IMPORTERS;
    DWORD importerSch = PLUGIN_MAX_IMPORTERS;

    if (argc > 1) {
        ParseOptions(&options, argc, argv);
    }
    else {
        options.misc.showHelp = TRUE;
    }

    if (options.misc.showHelp) {
        Usage(argv[0], NULL);
        ForeachLoadedPlugins(&options, PluginHelp);
        ExitProcess(EXIT_FAILURE);
    }


    //
    // Plugins verifications
    //
    LOG(Succ, "Verifying and choosing plugins");

    if (options.plugins.numberOfImporters == 0){
        FATAL(_T("No importer has been loaded"));
    }

    if (options.plugins.numberOfWriters == 0){
        FATAL(_T("No writer has been loaded"));
    }

    for (i = 0; i < options.plugins.numberOfImporters; i++) {
        if (!PLUGIN_IS_LOADED(&options.plugins.importers[i])) {
            FATAL(_T("Importer <%u> is registered, but not loaded"), i);
        }

        if (importerAce == PLUGIN_MAX_IMPORTERS && options.plugins.importers[i].functions.GetNextAce) {
            LOG(Info, SUB_LOG(_T("Using <%s> to import ACE")), PLUGIN_GET_NAME(&options.plugins.importers[i]));
            importerAce = i;
        }

        if (importerObj == PLUGIN_MAX_IMPORTERS && options.plugins.importers[i].functions.GetNextSchema) {
            LOG(Info, SUB_LOG(_T("Using <%s> to import objects")), PLUGIN_GET_NAME(&options.plugins.importers[i]));
            importerObj = i;
        }

        if (importerSch == PLUGIN_MAX_IMPORTERS && options.plugins.importers[i].functions.GetNextObject) {
            LOG(Info, SUB_LOG(_T("Using <%s> to import schema")), PLUGIN_GET_NAME(&options.plugins.importers[i]));
            importerSch = i;
        }
    }

	if (importerAce == PLUGIN_MAX_IMPORTERS){
		FATAL(_T("ACE importer is missing"));
	}
	if (importerObj == PLUGIN_MAX_IMPORTERS){
		FATAL(_T("Obj importer is missing"));
	}
	if (importerSch == PLUGIN_MAX_IMPORTERS){
		FATAL(_T("Sch importer is missing"));
	}

    // We allow no filter to be loaded, to permit ACE format conversion (direct link importer->writer)
    if (options.plugins.numberOfFilters > 0) {
        for (i = 0; i < options.plugins.numberOfFilters; i++) {
            if (!PLUGIN_IS_LOADED(&options.plugins.filters[i])) {
                FATAL(_T("Filter <%u> is registered, but not loaded"), i);
            }
        }
    }

    for (i = 0; i < options.plugins.numberOfWriters; i++) {
        if (!PLUGIN_IS_LOADED(&options.plugins.writers[i])) {
            FATAL(_T("Writer <%u> is registered, but not loaded"), i);
        }
    }


    //
    // Initializing plugins
    //
    LOG(Succ, _T("Initializing plugins"));
    ForeachLoadedPlugins(&options, PluginInitialize);


    //
    // Constructing caches
    //
    LOG(Succ, _T("Constructing caches"));

    CachesInitialize();

    if (PluginsRequires(&options, OPT_REQ_SID_RESOLUTION) || PluginsRequires(&options, OPT_REQ_DN_RESOLUTION)) {
        LOG(Info, SUB_LOG(_T("Plugins require SID or DN resolution, constructing object cache")));
        ConstructObjectCache(&options.plugins.importers[importerObj]);
        LOG(Info, SUB_LOG(_T("Object cache count : <by-sid:%u> <by-dn:%u>")), CacheObjectBySidCount(), CacheObjectByDnCount());
    }

	if (PluginsRequires(&options, OPT_REQ_GUID_RESOLUTION) || PluginsRequires(&options, OPT_REQ_CLASSID_RESOLUTION) || PluginsRequires(&options, OPT_REQ_DISPLAYNAME_RESOLUTION)) {
        LOG(Info, SUB_LOG(_T("Plugins require GUID or CLASSID or DisplayName resolution, constructing schema cache")));
        ConstructSchemaCache(&options.plugins.importers[importerSch]);
        LOG(Info, SUB_LOG(_T("Schema cache count : <by-guid:%u> <by-classid:%u> <by-displayname:%u>")), CacheSchemaByGuidCount(), CacheSchemaByClassidCount(), CacheSchemaByDisplayNameCount());
    }

    if (PluginsRequires(&options, OPT_REQ_ADMINSDHOLDER_SD)) {
        LOG(Info, SUB_LOG(_T("Plugins require AdminSdHolder security descriptor, constructing it")));
        ConstructAdminSdHolderSD(&options.plugins.importers[importerAce]);
    }


    //
    // Main Loop : process and filter ACEs
    //
    LOG(Succ, _T("Starting ACE filtering"));

    IMPORTED_ACE ace = { 0 };
    BOOL passedFilters = TRUE;
    BOOL filterRet = FALSE;

    // Stats variables
    DWORD aceCount = 0;
    DWORD keptAceCount = 0;
    ULONGLONG timeStart = 0;

    timeStart = GetTickCount64();

    options.plugins.importers[importerAce].functions.ResetReading(&gc_PluginApiTable, ImporterAce);
    while (options.plugins.importers[importerAce].functions.GetNextAce(&gc_PluginApiTable, &ace)) {
        passedFilters = TRUE;
        ace.computed.number = ++aceCount;

        for (i = 0; i < options.plugins.numberOfFilters; i++) {

            filterRet = options.plugins.filters[i].functions.FilterAce(&gc_PluginApiTable, &ace);
            passedFilters &= options.plugins.filters[i].inverted ? !filterRet : filterRet;

            if (!passedFilters) {
                LOG(All, _T("Ace <%u> was filtered by <%s>"), aceCount, PLUGIN_GET_NAME(&options.plugins.filters[i]));
                break;
            }
        }

        if (passedFilters) {
            keptAceCount++;
            LOG(All, _T("Ace <%u> passed all filters"), aceCount);
            for (i = 0; i < options.plugins.numberOfWriters; i++) {
                options.plugins.writers[i].functions.WriteAce(&gc_PluginApiTable, &ace);
            }
        }

        if (aceCount % options.misc.progression == 0) {
            LOG(Info, SUB_LOG(_T("Count : %u")), aceCount);
        }

        FreeCheckX(ace.imported.objectDn); // TODO : possible leak, since this is importer-dependant. Call importer's destroyer instead.
        LocalFreeCheckX(ace.imported.raw);
        ZeroMemory(&ace, sizeof(IMPORTED_ACE));
    }

    //
    // Stats
    //
    LOG(Succ, _T("Done. ACE Statistics :"));
    LOG(Succ, SUB_LOG(_T("<total    : %u>")), aceCount);
    LOG(Succ, SUB_LOG(_T("<filtered : %06.2f%%  %u>")), PERCENT((aceCount - keptAceCount), aceCount), (aceCount - keptAceCount));
    LOG(Succ, SUB_LOG(_T("<kept     : %06.2f%%  %u>")), PERCENT(keptAceCount, aceCount), keptAceCount);
    LOG(Succ, SUB_LOG(_T("<time     : %.3fs>")), TIME_DIFF_SEC(timeStart, GetTickCount64()));


    //
    // Finalizing and unloading plugins
    //
    LOG(Succ, _T("Finalizing and unloading plugins"));
    ForeachLoadedPlugins(&options, PluginFinalize);
    ForeachLoadedPlugins(&options, PluginUnload);

    CachesDestroy();
    DestroyStrPairList(gs_PluginOptions.head);

    //
    // End
    //
    LOG(Succ, _T("Done"));
    return EXIT_SUCCESS;
}
Пример #18
0
/**
 * @brief Entry point of the user-defined function for pg_bulkload.
 * @return Returns number of loaded tuples.  If the case of errors, -1 will be
 * returned.
 */
Datum
pg_bulkload(PG_FUNCTION_ARGS)
{
	Reader		   *rd = NULL;
	Writer		   *wt = NULL;
	Datum			options;
	MemoryContext	ctx;
	MemoryContext	ccxt;
	PGRUsage		ru0;
	PGRUsage		ru1;
	int64			count;
	int64			parse_errors;
	int64			skip;
	WriterResult	ret;
	char		   *start;
	char		   *end;
	float8			system;
	float8			user;
	float8			duration;
	TupleDesc		tupdesc;
	Datum			values[PG_BULKLOAD_COLS];
	bool			nulls[PG_BULKLOAD_COLS];
	HeapTuple		result;

	/* Build a tuple descriptor for our result type */
	if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
		elog(ERROR, "return type must be a row type");

	BULKLOAD_PROFILE_PUSH();

	pg_rusage_init(&ru0);

	/* must be the super user */
	if (!superuser())
		ereport(ERROR,
			(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
			 errmsg("must be superuser to use pg_bulkload")));

	options = PG_GETARG_DATUM(0);

	ccxt = CurrentMemoryContext;

	/*
	 * STEP 1: Initialization
	 */

	/* parse options and create reader and writer */
	ParseOptions(options, &rd, &wt, ru0.tv.tv_sec);

	/* initialize reader */
	ReaderInit(rd);

	/*
	 * We need to split PG_TRY block because gcc optimizes if-branches with
	 * longjmp codes too much. Local variables initialized in either branch
	 * cannot be handled another branch.
	 */
	PG_TRY();
	{
		/* truncate heap */
		if (wt->truncate)
			TruncateTable(wt->relid);

		/* initialize writer */
		WriterInit(wt);

		/* initialize checker */
		CheckerInit(&rd->checker, wt->rel, wt->tchecker);

		/* initialize parser */
		ParserInit(rd->parser, &rd->checker, rd->infile, wt->desc,
				   wt->multi_process, PG_GET_COLLATION());
	}
	PG_CATCH();
	{
		if (rd)
			ReaderClose(rd, true);
		if (wt)
			WriterClose(wt, true);
		PG_RE_THROW();
	}
	PG_END_TRY();

	/* No throwable codes here! */

	PG_TRY();
	{
		/* create logger */
		CreateLogger(rd->logfile, wt->verbose, rd->infile[0] == ':');

		start = timeval_to_cstring(ru0.tv);
		LoggerLog(INFO, "\npg_bulkload %s on %s\n\n",
				   PG_BULKLOAD_VERSION, start);

		ReaderDumpParams(rd);
		WriterDumpParams(wt);
		LoggerLog(INFO, "\n");

		BULKLOAD_PROFILE(&prof_init);

		/*
		 * STEP 2: Build heap
		 */

		/* Switch into its memory context */
		Assert(wt->context);
		ctx = MemoryContextSwitchTo(wt->context);

		/* Loop for each input file record. */
		while (wt->count < rd->limit)
		{
			HeapTuple	tuple;

			CHECK_FOR_INTERRUPTS();

			/* read tuple */
			BULKLOAD_PROFILE_PUSH();
			tuple = ReaderNext(rd);
			BULKLOAD_PROFILE_POP();
			BULKLOAD_PROFILE(&prof_reader);
			if (tuple == NULL)
				break;

			/* write tuple */
			BULKLOAD_PROFILE_PUSH();
			WriterInsert(wt, tuple);
			wt->count += 1;
			BULKLOAD_PROFILE_POP();
			BULKLOAD_PROFILE(&prof_writer);

			MemoryContextReset(wt->context);
			BULKLOAD_PROFILE(&prof_reset);
		}

		MemoryContextSwitchTo(ctx);

		/*
		 * STEP 3: Finalize heap and merge indexes
		 */

		count = wt->count;
		parse_errors = rd->parse_errors;

		/*
		 * close writer first and reader second because shmem_exit callback
		 * is managed by a simple stack.
		 */
		ret = WriterClose(wt, false);
		wt = NULL;
		skip = ReaderClose(rd, false);
		rd = NULL;
	}
	PG_CATCH();
	{
		ErrorData	   *errdata;
		MemoryContext	ecxt;

		ecxt = MemoryContextSwitchTo(ccxt);
		errdata = CopyErrorData();
		LoggerLog(INFO, "%s\n", errdata->message);
		FreeErrorData(errdata);

		/* close writer first, and reader second */
		if (wt)
			WriterClose(wt, true);
		if (rd)
			ReaderClose(rd, true);

		MemoryContextSwitchTo(ecxt);
		PG_RE_THROW();
	}
	PG_END_TRY();

	count -= ret.num_dup_new;

	LoggerLog(INFO, "\n"
			  "  " int64_FMT " Rows skipped.\n"
			  "  " int64_FMT " Rows successfully loaded.\n"
			  "  " int64_FMT " Rows not loaded due to parse errors.\n"
			  "  " int64_FMT " Rows not loaded due to duplicate errors.\n"
			  "  " int64_FMT " Rows replaced with new rows.\n\n",
			  skip, count, parse_errors, ret.num_dup_new, ret.num_dup_old);

	pg_rusage_init(&ru1);
	system = diffTime(ru1.ru.ru_stime, ru0.ru.ru_stime);
	user = diffTime(ru1.ru.ru_utime, ru0.ru.ru_utime);
	duration = diffTime(ru1.tv, ru0.tv);
	end = timeval_to_cstring(ru1.tv);

	memset(nulls, 0, sizeof(nulls));
	values[0] = Int64GetDatum(skip);
	values[1] = Int64GetDatum(count);
	values[2] = Int64GetDatum(parse_errors);
	values[3] = Int64GetDatum(ret.num_dup_new);
	values[4] = Int64GetDatum(ret.num_dup_old);
	values[5] = Float8GetDatumFast(system);
	values[6] = Float8GetDatumFast(user);
	values[7] = Float8GetDatumFast(duration);

	LoggerLog(INFO,
		"Run began on %s\n"
		"Run ended on %s\n\n"
		"CPU %.2fs/%.2fu sec elapsed %.2f sec\n",
		start, end, system, user, duration);

	LoggerClose();

	result = heap_form_tuple(tupdesc, values, nulls);

	BULKLOAD_PROFILE(&prof_fini);
	BULKLOAD_PROFILE_POP();
	BULKLOAD_PROFILE_PRINT();

	PG_RETURN_DATUM(HeapTupleGetDatum(result));
}
Пример #19
0
int main( int argc, char *argv[] )
{
  static LALStatus                status;

  StochasticOmegaGWParameters   parameters;
  REAL4FrequencySeries     omegaGW;

  UINT4 i;
  REAL4 omega, f;
  INT4 code;


  /* define valid parameters */

  parameters.alpha    = STOCHASTICOMEGAGWTESTC_ALPHA;
  parameters.fRef     = STOCHASTICOMEGAGWTESTC_FREF;
  parameters.omegaRef = STOCHASTICOMEGAGWTESTC_OMEGAREF;
  parameters.length   = STOCHASTICOMEGAGWTESTC_LENGTH;
  parameters.f0       = STOCHASTICOMEGAGWTESTC_F0;
  parameters.deltaF   = STOCHASTICOMEGAGWTESTC_DELTAF;

  omegaGW.data = NULL;

#ifndef LAL_NDEBUG
  REAL4FrequencySeries     dummyOutput;
  dummyOutput.data = NULL;
#endif


  ParseOptions( argc, argv );

  LALSCreateVector(&status, &(omegaGW.data), STOCHASTICOMEGAGWTESTC_LENGTH);
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICOMEGAGWTESTC_EFLS,
			    STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
  {
    return code;
  }

  /* TEST INVALID DATA HERE ------------------------------------------ */
#ifndef LAL_NDEBUG
  if ( ! lalNoDebug )
  {
    /* test behavior for null pointer to real frequency series for output */
    LALStochasticOmegaGW(&status, NULL, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: null pointer to output series results in error:       \n\"%s\"\n",
	   STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);


    /* test behavior for null pointer to parameter structure */
    LALStochasticOmegaGW(&status, &omegaGW, NULL);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: null pointer to parameter structure results in error:       \n\"%s\"\n",
	   STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);


    /* test behavior for null pointer to data member of real frequency
       series for output */
    LALStochasticOmegaGW(&status, &dummyOutput, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: null pointer to data member of output series results in error:       \n\"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);


    /* Create a vector for testing null data-data pointer */
    LALSCreateVector(&status, &(dummyOutput.data), STOCHASTICOMEGAGWTESTC_LENGTH);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICOMEGAGWTESTC_EFLS,
			      STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
    {
      return code;
    }
    REAL4                *tempPtr;
    tempPtr = dummyOutput.data->data;
    dummyOutput.data->data = NULL;

    /* test behavior for null pointer to data member of data member of
       real frequency series for output */
    LALStochasticOmegaGW(&status, &dummyOutput, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENULLPTR,
			      STOCHASTICCROSSCORRELATIONH_MSGENULLPTR,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: null pointer to data member of data member of output series results in error:       \n\"%s\"\n",
           STOCHASTICCROSSCORRELATIONH_MSGENULLPTR);

    /* clean up */

    dummyOutput.data->data = tempPtr;
    LALSDestroyVector(&status, &(dummyOutput.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICOMEGAGWTESTC_EFLS,
			      STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
    {
      return code;
    }

    /* test behavior for length parameter equal to zero */
    parameters.length = 0;
    LALStochasticOmegaGW(&status, &omegaGW, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EZEROLEN,
			      STOCHASTICCROSSCORRELATIONH_MSGEZEROLEN,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: zero length parameter results in error:       \n\"%s\"\n",
	   STOCHASTICCROSSCORRELATIONH_MSGEZEROLEN);
    /* assign valid length parameter */
    parameters.length = STOCHASTICOMEGAGWTESTC_LENGTH;

    /* test behavior for frequency spacing less than or equal to zero */
    parameters.deltaF = -1;
    LALStochasticOmegaGW(&status, &omegaGW, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
      return code;
    }
    printf("  PASS: negative frequency spacing results in error:       \n\"%s\"\n",
	   STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF);

    parameters.deltaF = 0;
    LALStochasticOmegaGW(&status, &omegaGW, &parameters);
    if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENONPOSDELTAF,
			      STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF,
			      STOCHASTICOMEGAGWTESTC_ECHK,
			      STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
    {
        return code;
    }
    printf("  PASS: zero frequency spacing results in error:       \n\"%s\"\n",
	   STOCHASTICCROSSCORRELATIONH_MSGENONPOSDELTAF);
    /* assign valid frequency spacing */
    parameters.deltaF = STOCHASTICOMEGAGWTESTC_DELTAF;
  }

#endif /* LAL_NDEBUG */

  /* test behavior for negative start frequency */
  parameters.f0 = -20.0;
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_ENEGFMIN,
			    STOCHASTICCROSSCORRELATIONH_MSGENEGFMIN,
			    STOCHASTICOMEGAGWTESTC_ECHK,
			    STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: negative start frequency results in error:\n       \"%s\"\n",
         STOCHASTICCROSSCORRELATIONH_MSGENEGFMIN);

  /* reassign valid start frequency */
  parameters.f0 = STOCHASTICOMEGAGWTESTC_F0;

  /* test behavior for length of data member of real frequency series
     for output not equal to length specified in input parameters */
  parameters.length += 1;
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EMMLEN,
			    STOCHASTICCROSSCORRELATIONH_MSGEMMLEN,
			    STOCHASTICOMEGAGWTESTC_ECHK,
			    STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: mismatch between length of output series and length parameter results in error:       \n\"%s\"\n",
	 STOCHASTICCROSSCORRELATIONH_MSGEMMLEN);
  /* reassign valid length to data member of dummy output */
  parameters.length -= 1;

  /* test behavior for fRef < deltaf */
  parameters.fRef = 0;
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status, STOCHASTICCROSSCORRELATIONH_EOORFREF,
                          STOCHASTICCROSSCORRELATIONH_MSGEOORFREF,
			  STOCHASTICOMEGAGWTESTC_ECHK,
			    STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: zero reference frequency results in error:       \n\"%s\"\n",
	 STOCHASTICCROSSCORRELATIONH_MSGEOORFREF);
  parameters.fRef = STOCHASTICOMEGAGWTESTC_FREF;

  /* test behavior for omegaRef <=0 */
  parameters.omegaRef = -1.0;
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status,  STOCHASTICCROSSCORRELATIONH_ENONPOSOMEGA,
                          STOCHASTICCROSSCORRELATIONH_MSGENONPOSOMEGA,
			  STOCHASTICOMEGAGWTESTC_ECHK,
			    STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: negative amplitude parameter results in error:       \n\"%s\"\n",
	 STOCHASTICCROSSCORRELATIONH_MSGENONPOSOMEGA);

  parameters.omegaRef = 0.0;
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status,  STOCHASTICCROSSCORRELATIONH_ENONPOSOMEGA,
			    STOCHASTICCROSSCORRELATIONH_MSGENONPOSOMEGA,
			    STOCHASTICOMEGAGWTESTC_ECHK,
			    STOCHASTICOMEGAGWTESTC_MSGECHK) ) )
  {
    return code;
  }
  printf("  PASS: zero amplitude parameter results in error:       \n\"%s\"\n",
	 STOCHASTICCROSSCORRELATIONH_MSGENONPOSOMEGA);
  parameters.omegaRef = STOCHASTICOMEGAGWTESTC_OMEGAREF;

  /* TEST VALID DATA HERE -------------------------------------------- */

  /* generate omegaGW */
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status,0, "",
			    STOCHASTICOMEGAGWTESTC_EFLS,
			    STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
  {
    return code;
  }

  /* test values */

  for (i=0; i<STOCHASTICOMEGAGWTESTC_LENGTH; ++i)
  {
    f = i * STOCHASTICOMEGAGWTESTC_DELTAF;
    omega = STOCHASTICOMEGAGWTESTC_OMEGAREF
      * pow(f/STOCHASTICOMEGAGWTESTC_FREF,STOCHASTICOMEGAGWTESTC_ALPHA);
    if (optVerbose)
    {
      printf("Omega(%f Hz)=%g, should be %g\n",
             f, omegaGW.data->data[i], omega);
    }
    if ( (omegaGW.data->data[i] - omega) &&
         abs((omegaGW.data->data[i] - omega)/omega) > STOCHASTICOMEGAGWTESTC_TOL )
    {
      printf("  FAIL: Valid data test #1 (alpha=%f)\n",STOCHASTICOMEGAGWTESTC_ALPHA);
      return STOCHASTICOMEGAGWTESTC_EFLS;
    }
  }
  printf("  PASS: Valid data test #1 (alpha=%f)\n",STOCHASTICOMEGAGWTESTC_ALPHA);

  /* change parameters */
  parameters.alpha = 0.0;

  /* generate omegaGW */
  LALStochasticOmegaGW(&status, &omegaGW, &parameters);
  if ( ( code = CheckStatus(&status,0, "",
			    STOCHASTICOMEGAGWTESTC_EFLS,
			    STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
  {
    return code;
  }

  /* test values */

  for (i=0; i<STOCHASTICOMEGAGWTESTC_LENGTH; ++i)
  {
    f = i * STOCHASTICOMEGAGWTESTC_DELTAF;
    if (optVerbose) {
      printf("Omega(%f Hz)=%g, should be %g\n",
             f, omegaGW.data->data[i], STOCHASTICOMEGAGWTESTC_OMEGAREF);
    }
    if ( abs(omegaGW.data->data[i] - STOCHASTICOMEGAGWTESTC_OMEGAREF)
         / STOCHASTICOMEGAGWTESTC_OMEGAREF > STOCHASTICOMEGAGWTESTC_TOL )
    {
      printf("  FAIL: Valid data test #2 (alpha=0)\n");
      return STOCHASTICOMEGAGWTESTC_EFLS;
    }
  }
  printf("  PASS: Valid data test #2 (alpha=0)\n");

  /* clean up valid data */
  LALSDestroyVector(&status, &(omegaGW.data));
  if ( ( code = CheckStatus(&status, 0 , "",
			    STOCHASTICOMEGAGWTESTC_EFLS,
			    STOCHASTICOMEGAGWTESTC_MSGEFLS) ) )
  {
    return code;
  }

  LALCheckMemoryLeaks();

  printf("PASS: all tests\n");

  if (optFile[0]) {
    parameters.alpha = optAlpha;
    parameters.length = optLength;
    parameters.deltaF = optDeltaF;
    parameters.f0 = optF0;
    parameters.omegaRef = optOmegaR;
    parameters.fRef = optFR;
    LALSCreateVector(&status, &(omegaGW.data), optLength);
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICOMEGAGWTESTC_EUSE,
			      STOCHASTICOMEGAGWTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALStochasticOmegaGW(&status, &omegaGW, &parameters);
    if ( ( code = CheckStatus(&status,0, "",
			      STOCHASTICOMEGAGWTESTC_EUSE,
			      STOCHASTICOMEGAGWTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALSPrintFrequencySeries( &omegaGW, optFile );

    printf("=== Stochastic Gravitational-wave Spectrum Written to File %s ===\n", optFile);


    LALSDestroyVector(&status, &(omegaGW.data));
    if ( ( code = CheckStatus(&status, 0 , "",
			      STOCHASTICOMEGAGWTESTC_EUSE,
			      STOCHASTICOMEGAGWTESTC_MSGEUSE) ) )
    {
      return code;
    }
    LALCheckMemoryLeaks();
  }

  return STOCHASTICOMEGAGWTESTC_ENOM;
}
int main(int argc, char **argv)
{
    bool useKernelStack = true;

    ParseOptions(argc, argv);
    if (argc - optind != 3) {
        Usage(argv[0]);
        exit(1);
    }

    char *qemu_trace_file = argv[optind++];
    char *elf_file = argv[optind++];
    char *dmtrace_file = argv[optind++];
    TraceReaderType *trace = new TraceReaderType;
    trace->Open(qemu_trace_file);
    trace->SetDemangle(demangle);
    trace->ReadKernelSymbols(elf_file);
    trace->SetRoot(root);
    TraceHeader *qheader = trace->GetHeader();
    uint64_t startTime = qheader->start_sec;
    startTime = (startTime << 32) | qheader->start_usec;
    int kernelPid = qheader->first_unused_pid;

    dmtrace = new DmTrace;
    dmtrace->open(dmtrace_file, startTime);

    bool inKernel = false;
    CallStackType *kernelStack = NULL;
    if (useKernelStack) {
        // Create a fake kernel thread stack where we will put all the kernel
        // code.
        kernelStack = new CallStackType(kernelPid, kNumStackFrames, trace);
        dmtrace->addThread(kernelPid, "(kernel)");
    }

    CallStackType *prevStack = NULL;
    BBEvent event;
    while (1) {
        BBEvent ignored;
        symbol_type *function;

        if (GetNextValidEvent(trace, &event, &ignored, &function))
            break;
        if (event.bb_num == 0)
            break;
#if 0
        fprintf(stderr, "event t %llu p %d %s\n",
                event.time, event.pid, function->name);
#endif

        CallStackType *pStack;
        if (useKernelStack) {
            uint32_t flags = function->region->flags;
            uint32_t region_mask = region_type::kIsKernelRegion
                    | region_type::kIsUserMappedRegion;
            if ((flags & region_mask) == region_type::kIsKernelRegion) {
                // Use the kernel stack
                pStack = kernelStack;
                inKernel = true;
            } else {
                // If we were just in the kernel then pop off all of the
                // stack frames for the kernel thread.
                if (inKernel == true) {
                    inKernel = false;
                    kernelStack->popAll(event.time);
                }
                
                // Get the stack for the current thread
                pStack = stacks[event.pid];
            }
        } else {
            // Get the stack for the current thread
            pStack = stacks[event.pid];
        }

        // If the stack does not exist, then allocate a new one.
        if (pStack == NULL) {
            pStack = new CallStackType(event.pid, kNumStackFrames, trace);
            stacks[event.pid] = pStack;
            char *name = trace->GetProcessName(event.pid);
            dmtrace->addThread(event.pid, name);
        }

        if (prevStack != pStack) {
            pStack->threadStart(event.time);
            if (prevStack)
                prevStack->threadStop(event.time);
        }
        prevStack = pStack;

        // If we have never seen this function before, then add it to the
        // list of known functions.
        if (function->id == 0) {
            function->id = nextFunctionId;
            nextFunctionId += 4;
            uint32_t flags = function->region->flags;
            const char *name = function->name;
            if (flags & region_type::kIsKernelRegion) {
                // To distinguish kernel function names from user library
                // names, add a marker to the name.
                int len = strlen(name) + strlen(" [kernel]") + 1;
                char *kernelName = new char[len];
                strcpy(kernelName, name);
                strcat(kernelName, " [kernel]");
                name = kernelName;
            }
            dmtrace->parseAndAddFunction(function->id, name);
        }

        // Update the stack
        pStack->updateStack(&event, function);
    }

    if (prevStack == NULL) {
        fprintf(stderr, "Error: no events in trace.\n");
        exit(1);
    }
    prevStack->threadStop(event.time);
    for (int ii = 0; ii < kMaxThreads; ++ii) {
        if (stacks[ii]) {
            stacks[ii]->threadStart(event.time);
            stacks[ii]->popAll(event.time);
        }
    }
    if (useKernelStack) {
        kernelStack->popAll(event.time);
    }

    // Read the pid events to find the names of the processes
    while (1) {
        PidEvent pid_event;
        if (trace->ReadPidEvent(&pid_event))
            break;
        if (pid_event.rec_type == kPidName) {
            dmtrace->updateName(pid_event.pid, pid_event.path);
        }
    }


    dmtrace->close();
    delete dmtrace;
    delete trace;
    return 0;
}
Пример #21
0
int main( int argc, char *argv[] )
{
  const UINT4 n  = 65536;
  const REAL4 dt = 1.0 / 16384.0;
  static LALStatus status;

  static REAL4TimeSeries         x;
  static COMPLEX8FrequencySeries X;

  static REAL4TimeSeries         y;
  static REAL4FrequencySeries    Y;

  static COMPLEX8TimeSeries      z;
  static COMPLEX8FrequencySeries Z;

  RealFFTPlan    *fwdRealPlan    = NULL;
  RealFFTPlan    *revRealPlan    = NULL;
  ComplexFFTPlan *fwdComplexPlan = NULL;
  ComplexFFTPlan *revComplexPlan = NULL;
  RandomParams   *randpar        = NULL;

  AverageSpectrumParams avgSpecParams;

  UINT4 srate[] = { 4096, 9000 };
  UINT4 npts[] = { 262144, 1048576 };
  REAL4 var[] = { 5, 16 };

  UINT4 j, sr, np, vr;


  /*CHAR fname[2048];*/

  ParseOptions( argc, argv );

  LALSCreateVector( &status, &x.data, n );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCCreateVector( &status, &X.data, n / 2 + 1 );
  TestStatus( &status, CODES( 0 ), 1 );

  LALCCreateVector( &status, &z.data, n );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCCreateVector( &status, &Z.data, n );
  TestStatus( &status, CODES( 0 ), 1 );

  LALCreateForwardRealFFTPlan( &status, &fwdRealPlan, n, 0 );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCreateReverseRealFFTPlan( &status, &revRealPlan, n, 0 );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCreateForwardComplexFFTPlan( &status, &fwdComplexPlan, n, 0 );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCreateReverseComplexFFTPlan( &status, &revComplexPlan, n, 0 );
  TestStatus( &status, CODES( 0 ), 1 );

  randpar = XLALCreateRandomParams( 100 );


  /*
   *
   * Try the real transform.
   *
   */


  x.f0 = 0;
  x.deltaT = dt;
  x.sampleUnits = lalMeterUnit;
  snprintf( x.name, sizeof( x.name ), "x" );
  XLALNormalDeviates( x.data, randpar );
  for ( j = 0; j < n; ++j ) /* add a 60 Hz line */
  {
    REAL4 t = j * dt;
    x.data->data[j] += 0.1 * cos( LAL_TWOPI * 60.0 * t );
  }
  LALSPrintTimeSeries( &x, "x.out" );

  snprintf( X.name, sizeof( X.name ), "X" );
  LALTimeFreqRealFFT( &status, &X, &x, fwdRealPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCPrintFrequencySeries( &X, "X.out" );

  LALFreqTimeRealFFT( &status, &x, &X, revRealPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALSPrintTimeSeries( &x, "xx.out" );


  /*
   *
   * Try the average power spectum.
   *
   */


  avgSpecParams.method = useMean;

  for ( np = 0; np < XLAL_NUM_ELEM(npts) ; ++np )
  {
    /* length of time series for 7 segments, overlapped by 1/2 segment */
    UINT4 tsLength = npts[np] * 7 - 6 * npts[np] / 2;
    LALCreateVector( &status, &y.data, tsLength );
    TestStatus( &status, CODES( 0 ), 1 );
    LALCreateVector( &status, &Y.data, npts[np] / 2 + 1  );
    TestStatus( &status, CODES( 0 ), 1 );
    avgSpecParams.overlap = npts[np] / 2;

    /* create the window */
    avgSpecParams.window = XLALCreateHannREAL4Window(npts[np]);
    avgSpecParams.plan = NULL;
    LALCreateForwardRealFFTPlan( &status, &avgSpecParams.plan, npts[np], 0 );
    TestStatus( &status, CODES( 0 ), 1 );

    for ( sr = 0; sr < XLAL_NUM_ELEM(srate) ; ++sr )
    {
      /* set the sample rate of the time series */
      y.deltaT = 1.0 / (REAL8) srate[sr];
      for ( vr = 0; vr < XLAL_NUM_ELEM(var) ; ++vr )
      {
        REAL4 eps = 1e-6; /* very conservative fp precision */
        REAL4 Sfk = 2.0 * var[vr] * var[vr] * y.deltaT;
        REAL4 sfk = 0;
        REAL4 lbn;
        REAL4 sig;
        REAL4 ssq;
        REAL4 tol;

        /* create the data */
        XLALNormalDeviates( y.data, randpar );
        ssq = 0;
        for ( j = 0; j < y.data->length; ++j )
        {
          y.data->data[j] *= var[vr];
          ssq += y.data->data[j] * y.data->data[j];
        }

        /* compute tolerance for comparison */
        lbn = log( y.data->length ) / log( 2 );
        sig = sqrt( 2.5 * lbn * eps * eps * ssq / y.data->length );
        tol = 5 * sig;

        /* compute the psd and find the average */
        LALREAL4AverageSpectrum( &status, &Y, &y, &avgSpecParams );
        TestStatus( &status, CODES( 0 ), 1 );
        LALSMoment( &status, &sfk, Y.data, 1 );
        TestStatus( &status, CODES( 0 ), 1 );

        /* check the result */
        if ( fabs(Sfk-sfk) > tol )
        {
          fprintf( stderr, "FAIL: PSD estimate appears incorrect\n");
          fprintf( stderr, "expected %e, got %e ", Sfk, sfk );
          fprintf( stderr, "(difference = %e, tolerance = %e)\n",
              fabs(Sfk-sfk), tol );
          exit(2);
        }

      }
    }

    /* destroy structures that need to be resized */
    LALDestroyRealFFTPlan( &status, &avgSpecParams.plan );
    TestStatus( &status, CODES( 0 ), 1 );
    XLALDestroyREAL4Window( avgSpecParams.window );
    LALDestroyVector( &status, &y.data );
    TestStatus( &status, CODES( 0 ), 1 );
    LALDestroyVector( &status, &Y.data );
    TestStatus( &status, CODES( 0 ), 1 );
  }


  /*
   *
   * Try the complex transform.
   *
   */


  z.f0 = 0;
  z.deltaT = dt;
  z.sampleUnits = lalVoltUnit;
  snprintf( z.name, sizeof( z.name ), "z" );
  { /* dirty hack */
    REAL4Vector tmp;
    tmp.length = 2 * z.data->length;
    tmp.data   = (REAL4 *)z.data->data;
    XLALNormalDeviates( &tmp, randpar );
  }
  for ( j = 0; j < n; ++j ) /* add a 50 Hz line and a 500 Hz ringdown */
  {
    REAL4 t = j * dt;
    z.data->data[j] += 0.2 * cos( LAL_TWOPI * 50.0 * t );
    z.data->data[j] += I * exp( -t ) * sin( LAL_TWOPI * 500.0 * t );
  }
  LALCPrintTimeSeries( &z, "z.out" );
  TestStatus( &status, CODES( 0 ), 1 );

  snprintf( Z.name, sizeof( Z.name ), "Z" );
  LALTimeFreqComplexFFT( &status, &Z, &z, fwdComplexPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCPrintFrequencySeries( &Z, "Z.out" );

  LALFreqTimeComplexFFT( &status, &z, &Z, revComplexPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCPrintTimeSeries( &z, "zz.out" );

  XLALDestroyRandomParams( randpar );

  LALDestroyRealFFTPlan( &status, &fwdRealPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALDestroyRealFFTPlan( &status, &revRealPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALDestroyComplexFFTPlan( &status, &fwdComplexPlan );
  TestStatus( &status, CODES( 0 ), 1 );
  LALDestroyComplexFFTPlan( &status, &revComplexPlan );
  TestStatus( &status, CODES( 0 ), 1 );

  LALCDestroyVector( &status, &Z.data );
  TestStatus( &status, CODES( 0 ), 1 );
  LALCDestroyVector( &status, &z.data );
  TestStatus( &status, CODES( 0 ), 1 );

  LALCDestroyVector( &status, &X.data );
  TestStatus( &status, CODES( 0 ), 1 );
  LALSDestroyVector( &status, &x.data );
  TestStatus( &status, CODES( 0 ), 1 );

  LALCheckMemoryLeaks();
  return 0;
}
Пример #22
0
/*
====================
idModelExport::ParseExportSection
====================
*/
int idModelExport::ParseExportSection( idParser &parser ) {
	idToken	command;
	idToken	token;
	idStr	defaultCommands;
	idLexer lex;
	idStr	temp;
	idStr	parms;
	int		count;
	// only export sections that match our export mask
	if( g_exportMask.GetString()[ 0 ] ) {
		if( parser.CheckTokenString( "{" ) ) {
			parser.SkipBracedSection( false );
			return 0;
		}
		parser.ReadToken( &token );
		if( token.Icmp( g_exportMask.GetString() ) ) {
			parser.SkipBracedSection();
			return 0;
		}
		parser.ExpectTokenString( "{" );
	} else if( !parser.CheckTokenString( "{" ) ) {
		// skip the export mask
		parser.ReadToken( &token );
		parser.ExpectTokenString( "{" );
	}
	count = 0;
	lex.SetFlags( LEXFL_NOSTRINGCONCAT | LEXFL_ALLOWPATHNAMES | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT );
	while( 1 ) {
		if( !parser.ReadToken( &command ) ) {
			parser.Error( "Unexpoected end-of-file" );
			break;
		}
		if( command == "}" ) {
			break;
		}
		if( command == "options" ) {
			parser.ParseRestOfLine( defaultCommands );
		} else if( command == "addoptions" ) {
			parser.ParseRestOfLine( temp );
			defaultCommands += " ";
			defaultCommands += temp;
		} else if( ( command == "mesh" ) || ( command == "anim" ) || ( command == "camera" ) ) {
			if( !parser.ReadToken( &token ) ) {
				parser.Error( "Expected filename" );
			}
			temp = token;
			parser.ParseRestOfLine( parms );
			if( defaultCommands.Length() ) {
				sprintf( temp, "%s %s", temp.c_str(), defaultCommands.c_str() );
			}
			if( parms.Length() ) {
				sprintf( temp, "%s %s", temp.c_str(), parms.c_str() );
			}
			lex.LoadMemory( temp, temp.Length(), parser.GetFileName() );
			Reset();
			if( ParseOptions( lex ) ) {
				const char *game = cvarSystem->GetCVarString( "fs_game" );
				if( strlen( game ) == 0 ) {
					game = BASE_GAMEDIR;
				}
				if( command == "mesh" ) {
					dest.SetFileExtension( MD5_MESH_EXT );
				} else if( command == "anim" ) {
					dest.SetFileExtension( MD5_ANIM_EXT );
				} else if( command == "camera" ) {
					dest.SetFileExtension( MD5_CAMERA_EXT );
				} else {
					dest.SetFileExtension( command );
				}
				idStr back = commandLine;
				sprintf( commandLine, "%s %s -dest %s -game %s%s", command.c_str(), src.c_str(), dest.c_str(), game, commandLine.c_str() );
				if( ConvertMayaToMD5() ) {
					count++;
				} else {
					parser.Warning( "Failed to export '%s' : %s", src.c_str(), Maya_Error.c_str() );
				}
			}
			lex.FreeSource();
		} else {
			parser.Error( "Unknown token: %s", command.c_str() );
			parser.SkipBracedSection( false );
			break;
		}
	}
	return count;
}
Пример #23
0
int main(int argc, char** argv)
{
  ArcoderSettings settings;

  if (ParseOptions(argc, (const char **)argv, settings) != 0)
  {
	  std::cout << "Failed to parse options." << std::endl;
	  PrintUsage(argv[0]);
    return 1;
  }

  std::ifstream in;
  in.open(settings.inputFileName.c_str(), std::ifstream::in | std::ifstream::binary);
  std::ofstream out;
  out.open(settings.outputFileName.c_str(), std::ofstream::out | std::ofstream::binary);

  if (!in.good())
  {
    std::cout << "Couldn't open " << settings.inputFileName.c_str() << " for reading" << std::endl;
    return 2;
  }

  if (!out.good())
  {
    std::cout << "Couldn't open " << settings.outputFileName.c_str() << " for writing" << std::endl;
    return 2;
  }

  Arcoder* coder = NULL;
  
  if (!settings.modelFileName.empty())
  {
    std::ifstream model;
    model.open(settings.modelFileName.c_str(), std::ifstream::in | std::ifstream::binary);
    if (!model.good())
    {
      std::cout << "Couldn't open " << settings.modelFileName.c_str() << " for reading" << std::endl;
      return 2;
    }

		coder = CreateArcoder(model);

    model.close();
  }
  else
  {
    coder = CreateArcoder();
  }

  assert(coder != NULL);

  int* modelChoosingTable = NULL;

  if (!settings.modelChoosingRulesFileName.empty())
  {
    std::ifstream modelChoosingRules;
    modelChoosingRules.open(settings.modelChoosingRulesFileName.c_str(), std::ifstream::in | std::ifstream::binary);
    if (!modelChoosingRules.good())
    {
      std::cout << "Couldn't open " << settings.modelChoosingRulesFileName.c_str() << " for reading" << std::endl;
      return 2;
    }

    int choosingRulesSize = 0;

    modelChoosingRules.read((char *)&choosingRulesSize, sizeof(choosingRulesSize));

    if (choosingRulesSize <= 0)
    {
      std::cout << "Invalid model choosing rules file" << std::endl;
      return 2;
    }

    modelChoosingTable = new int[2 * choosingRulesSize + 1];
    modelChoosingTable[0] = choosingRulesSize;

    modelChoosingRules.read((char *)(modelChoosingTable + 1), 2 * choosingRulesSize * sizeof(int));

    if (!(modelChoosingRules.good() || modelChoosingRules.eof()))
    {
      std::cout << "Failed to read file " << settings.modelChoosingRulesFileName.c_str() << std::endl;
      return 2;
    }

    modelChoosingRules.close();

    coder->SetModelChoosingCallback(choosingCallback, modelChoosingTable);
  }

  if (settings.compress)
  {
    coder->Compress(in, out);
  }
  else
  {
    coder->Decompress(in, out);
  }

  in.close();
  out.close();

  if (!settings.modelToSaveFileName.empty())
  {
    std::ofstream modelOut;
    modelOut.open(settings.modelToSaveFileName.c_str(), std::ofstream::out | std::ofstream::binary);
    coder->SaveModel(modelOut);
    modelOut.close();
  }

  if (modelChoosingTable)
  {
    delete [] modelChoosingTable;
  }

  return 0;
}
Пример #24
0
/***********************************************************************
 *
 *  Procedure:
 *	main - start of module
 *
 ***********************************************************************/
int main(int argc, char **argv)
{
  char *display_name = NULL;
  int itemp,i;
  char line[100];
  short opt_num;
  Window JunkRoot, JunkChild;
  int JunkX, JunkY;
  unsigned JunkMask;

#ifdef I18N_MB
  setlocale(LC_CTYPE, "");
#endif
  /* Save our program  name - for error messages */
  MyName = GetFileNameFromPath(argv[0]);

  if(argc  < 6)
    {
      fprintf(stderr,"%s Version %s should only be executed by fvwm!\n",MyName,
	      VERSION);
      exit(1);
    }

#ifdef HAVE_SIGACTION
  {
    struct sigaction  sigact;

    sigemptyset(&sigact.sa_mask);
    sigaddset(&sigact.sa_mask, SIGPIPE);
    sigaddset(&sigact.sa_mask, SIGTERM);
    sigaddset(&sigact.sa_mask, SIGQUIT);
    sigaddset(&sigact.sa_mask, SIGINT);
    sigaddset(&sigact.sa_mask, SIGHUP);
# ifdef SA_INTERRUPT
    sigact.sa_flags = SA_INTERRUPT;
# else
    sigact.sa_flags = 0;
# endif
    sigact.sa_handler = TerminateHandler;

    sigaction(SIGPIPE, &sigact, NULL);
    sigaction(SIGTERM, &sigact, NULL);
    sigaction(SIGQUIT, &sigact, NULL);
    sigaction(SIGINT,  &sigact, NULL);
    sigaction(SIGHUP,  &sigact, NULL);
  }
#else
  /* We don't have sigaction(), so fall back to less robust methods.  */
#ifdef USE_BSD_SIGNALS
  fvwmSetSignalMask( sigmask(SIGPIPE) |
                     sigmask(SIGTERM) |
                     sigmask(SIGQUIT) |
                     sigmask(SIGINT) |
                     sigmask(SIGHUP) );
#endif
  signal(SIGPIPE, TerminateHandler);
  signal(SIGTERM, TerminateHandler);
  signal(SIGQUIT, TerminateHandler);
  signal(SIGINT,  TerminateHandler);
  signal(SIGHUP,  TerminateHandler);
#ifdef HAVE_SIGINTERRUPT
  siginterrupt(SIGPIPE, 1);
  siginterrupt(SIGTERM, 1);
  siginterrupt(SIGQUIT, 1);
  siginterrupt(SIGINT, 1);
  siginterrupt(SIGHUP, 1);
#endif
#endif

  fd[0] = atoi(argv[1]);
  fd[1] = atoi(argv[2]);

  fd_width = GetFdWidth();

  opt_num = 6;
  if (argc >= 7 && (StrEquals(argv[opt_num], "-transient") ||
		    StrEquals(argv[opt_num], "transient")))
  {
    opt_num++;
    is_transient = True;
      do_ignore_next_button_release = True;
  }

  /* Check for an alias */
  if (argc >= opt_num + 1)
    {
      char *s;

      if (!StrEquals(argv[opt_num], "*"))
      {
	for (s = argv[opt_num]; *s; s++)
	{
	  if (!isdigit(*s) &&
	      (*s != '-' || s != argv[opt_num] || *(s+1) == 0))
	  {
	    free(MyName);
	    MyName=safestrdup(argv[opt_num]);
	    opt_num++;
	    break;
	  }
	}
      }
    }

  if (argc < opt_num + 1)
    {
      desk1 = Scr.CurrentDesk;
      desk2 = Scr.CurrentDesk;
    }
  else if (StrEquals(argv[opt_num], "*"))
    {
      desk1 = Scr.CurrentDesk;
      desk2 = Scr.CurrentDesk;
      fAlwaysCurrentDesk = 1;
    }
  else
    {
      desk1 = atoi(argv[opt_num]);
      if (argc == opt_num+1)
	desk2 = desk1;
      else
	desk2 = atoi(argv[opt_num+1]);
      if(desk2 < desk1)
	{
	  itemp = desk1;
	  desk1 = desk2;
	  desk2 = itemp;
	}
    }
  ndesks = desk2 - desk1 + 1;

  Desks = (DeskInfo *)safemalloc(ndesks*sizeof(DeskInfo));
  memset(Desks, 0, ndesks * sizeof(DeskInfo));
  for(i=0;i<ndesks;i++)
    {
      sprintf(line,"Desk %d",i+desk1);
      CopyString(&Desks[i].label,line);
      Desks[i].colorset = -1;
      Desks[i].highcolorset = -1;
      Desks[i].ballooncolorset = -1;
    }

  /* Initialize X connection */
  if (!(dpy = XOpenDisplay(display_name)))
    {
      fprintf(stderr,"%s: can't open display %s", MyName,
	      XDisplayName(display_name));
      exit (1);
    }
  x_fd = XConnectionNumber(dpy);
  InitPictureCMap(dpy);
  FScreenInit(dpy);
  AllocColorset(0);
  FShapeInit(dpy);

  Scr.screen = DefaultScreen(dpy);
  Scr.Root = RootWindow(dpy, Scr.screen);
  /* make a temp window for any pixmaps, deleted later */
  initialize_viz_pager();

#ifdef DEBUG
  fprintf(stderr,"[main]: Connection to X server established.\n");
#endif

  SetMessageMask(fd,
                 M_ADD_WINDOW|
                 M_CONFIGURE_WINDOW|
                 M_DESTROY_WINDOW|
                 M_FOCUS_CHANGE|
                 M_NEW_PAGE|
                 M_NEW_DESK|
                 M_RAISE_WINDOW|
                 M_LOWER_WINDOW|
                 M_ICONIFY|
		 M_ICON_LOCATION|
		 M_DEICONIFY|
		 M_RES_NAME|
		 M_RES_CLASS|
		 M_WINDOW_NAME|
		 M_ICON_NAME|
		 M_CONFIG_INFO|
		 M_END_CONFIG_INFO|
		 M_MINI_ICON|
		 M_END_WINDOWLIST|
		 M_RESTACK);
#ifdef DEBUG
  fprintf(stderr,"[main]: calling ParseOptions\n");
#endif
  ParseOptions();
  if (is_transient)
    {
      XQueryPointer(dpy, Scr.Root, &JunkRoot, &JunkChild,
		    &window_x, &window_y, &JunkX, &JunkY, &JunkMask);
      usposition = 1;
      xneg = 0;
      yneg = 0;
    }
#ifdef DEBUG
  fprintf(stderr,
	  "[main]: back from calling ParseOptions, calling init pager\n");
#endif

  if (PagerFore == NULL)
    PagerFore = safestrdup("black");

  if (PagerBack == NULL)
    PagerBack = safestrdup("white");

  if (HilightC == NULL)
    HilightC = safestrdup(PagerFore);

  if (WindowLabelFormat == NULL)
    WindowLabelFormat = safestrdup("%i");

  if (font_string == NULL)
    font_string = safestrdup("fixed");

  if ((HilightC == NULL) && (HilightPixmap == NULL))
    HilightDesks = 0;

  if (BalloonFont == NULL)
    BalloonFont = safestrdup("fixed");

  if (BalloonBorderColor == NULL)
    BalloonBorderColor = safestrdup("black");

  if (BalloonTypeString == NULL)
    BalloonTypeString = safestrdup("%i");

  if (BalloonFormatString == NULL)
    BalloonFormatString = safestrdup("%i");

  /* open a pager window */
  initialize_pager();
#ifdef DEBUG
  fprintf(stderr,"[main]: back from init pager, getting window list\n");
#endif

  /* Create a list of all windows */
  /* Request a list of all windows,
   * wait for ConfigureWindow packets */
  SendInfo(fd,"Send_WindowList",0);
#ifdef DEBUG
  fprintf(stderr,"[main]: back from getting window list, looping\n");
#endif

  if (is_transient)
  {
    Bool is_pointer_grabbed = False;
    Bool is_keyboard_grabbed = False;
    XSync(dpy,0);
    for (i = 0; i < 50 && !(is_pointer_grabbed && is_keyboard_grabbed); i++)
    {
      if (!is_pointer_grabbed &&
	  XGrabPointer(
	    dpy, Scr.Root, True,
	    ButtonPressMask|ButtonReleaseMask|ButtonMotionMask|
	    PointerMotionMask|EnterWindowMask|LeaveWindowMask, GrabModeAsync,
	    GrabModeAsync, None, None, CurrentTime) == GrabSuccess)
      {
	is_pointer_grabbed = True;
      }
      if (!is_keyboard_grabbed &&
	  XGrabKeyboard(
	    dpy, Scr.Root, True, GrabModeAsync, GrabModeAsync, CurrentTime) ==
	  GrabSuccess)
      {
	is_keyboard_grabbed = True;
      }
      /* If you go too fast, other windows may not get a change to release
       * any grab that they have. */
      usleep(20000);
    }
    if (!is_pointer_grabbed)
    {
      XBell(dpy, 0);
      fprintf(stderr,
	      "%s: could not grab pointer in transient mode. exiting.\n",
	      MyName);
      exit(1);
    }

    XSync(dpy,0);
  }

  /* tell fvwm we're running */
  SendFinishedStartupNotification(fd);

  Loop(fd);
#ifdef DEBUG
  if (debug_term_signal)
  {
    fprintf(stderr,"[main]: Terminated due to signal %d\n",
                   debug_term_signal);
  }
#endif
  return 0;
}
Пример #25
0
int main(int argc, char **argv) {
    // Parse the options
    ParseOptions(argc, argv);
    localParseOptions(argc, argv);
    if (argc - optind != 2) {
        Usage(argv[0]);
        exit(1);
    }

    char *trace_filename = argv[optind++];
    char *elf_file = argv[optind++];
    TraceReader<> *trace = new TraceReader<>;
    trace->Open(trace_filename);
    trace->SetDemangle(demangle);
    trace->ReadKernelSymbols(elf_file);
    trace->SetRoot(root);

    while (1) {
        symbol_type *sym;
        char buf[1024];
        BBEvent event;
        BBEvent ignored;

        if (GetNextValidEvent(trace, &event, &ignored, &sym))
            break;
#if 0
        fprintf(stderr, "t%llu bb %lld %d\n",
                event.time, event.bb_num, event.num_insns);
#endif

        uint32_t *insns = event.insns;
        uint32_t addr = event.bb_addr;
        uint32_t offset = addr - sym->addr - sym->region->base_addr;
        symbol_type *vm_sym = sym->vm_sym;
        const char *vm_name = NULL;
        if (vm_sym != NULL) {
            vm_name = vm_sym->name;
            offset = addr - vm_sym->addr - vm_sym->region->base_addr;
        }
#if 0
        if (strcmp(sym->name, "(unknown)") == 0 || offset > kOffsetThreshold) {
            ProcessState *process = trace->GetCurrentProcess();
            ProcessState *manager = process->addr_manager;
            for (int ii = 0; ii < manager->nregions; ++ii) {
                printf("  %2d: %08x - %08x base: %08x offset: %u nsyms: %4d flags: 0x%x %s\n",
                       ii,
                       manager->regions[ii]->vstart,
                       manager->regions[ii]->vend,
                       manager->regions[ii]->base_addr,
                       manager->regions[ii]->file_offset,
                       manager->regions[ii]->nsymbols,
                       manager->regions[ii]->flags,
                       manager->regions[ii]->path);
                int nsymbols = manager->regions[ii]->nsymbols;
                for (int jj = 0; jj < 10 && jj < nsymbols; ++jj) {
                    printf("    %08x %s\n",
                           manager->regions[ii]->symbols[jj].addr,
                           manager->regions[ii]->symbols[jj].name);
                }
            }
        }
#endif
#if 1
        for (int ii = 0; ii < event.num_insns; ++ii) {
            uint64_t sim_time = trace->ReadInsnTime(event.time);
            if (sim_time < startTime)
                continue;

            uint32_t insn = insns[ii];
            char *disasm;
            int bytes;
            if (vm_name != NULL) {
                sprintf(buf, "%s+%02x: %s", vm_name, offset, sym->name);
            } else {
                sprintf(buf, "%s+%02x", sym->name, offset);
            }

            if (insn_is_thumb(insn)) {
                bytes = 2;
                insn = insn_unwrap_thumb(insn);

                // thumb_pair is true if this is the first of a pair of
                // thumb instructions (BL or BLX).
                bool thumb_pair = ((insn & 0xf800) == 0xf000);

                // Get the next thumb instruction (if any) because we may need
                // it for the case where insn is BL or BLX.
                uint32_t insn2 = 0;
                if (thumb_pair && (ii + 1 < event.num_insns)) {
                    insn2 = insns[ii + 1];
                    insn2 = insn_unwrap_thumb(insn2);
                    bytes = 4;
                    ii += 1;
                }
                disasm = disasm_insn_thumb(addr, insn, insn2, NULL);
                if (thumb_pair) {
                    printf("%llu p%-4d %08x %04x %04x %-30s %s\n",
                           sim_time, event.pid, addr, insn, insn2, buf, disasm);
                } else {
                    printf("%llu p%-4d %08x     %04x %-30s %s\n",
                           sim_time, event.pid, addr, insn, buf, disasm);
                }
            } else {
                bytes = 4;
                disasm = Arm::disasm(addr, insn, NULL);
                printf("%llu p%-4d %08x %08x %-30s %s\n",
                       sim_time, event.pid, addr, insn, buf, disasm);
            }
            //printf("t%llu \t%08x\n", sim_time, addr);
            addr += bytes;
            offset += bytes;
        }
#endif
#if 0
        assert(offset < kOffsetThreshold);
#endif
    }

    delete trace;
    return 0;
}
Пример #26
0
/***********************************************************************
 *
 *  Procedure:
 *	main - start of module
 *
 ***********************************************************************/
void main(int argc, char **argv)
{
  char *temp, *s, *cptr;
  char *display_name = NULL;
  int itemp,i;
  char line[100];
  char mask_mesg[50];

  /* Save our program  name - for error messages */
  temp = argv[0];
  s=strrchr(argv[0], '/');
  if (s != NULL)
    temp = s + 1;
  
  MyName = safemalloc(strlen(temp)+2);
  strcpy(MyName, temp);
  
  if((argc != 7)&&(argc != 6))
    {
      fprintf(stderr,"%s Version %s should only be executed by fvwm!\n",MyName,
	      PACKAGE_VERSION);
      exit(1);
    }
  if(argc != 7)
    { 
      fprintf(stderr,"%s Version %s requires an argument: %s n m\n",
	      MyName,PACKAGE_VERSION,MyName);
      fprintf(stderr,"   where desktops n through m are displayed\n");
      exit(1);
    }
  
  /* Dead pipe == Fvwm died */
  signal (SIGPIPE, DeadPipe);  
  
  fd[0] = atoi(argv[1]);
  fd[1] = atoi(argv[2]);
  
  fd_width = GetFdWidth();
  
  cptr = argv[6];
  while((isspace(*cptr))&&(*cptr != 0))cptr++;
  desk1 = atoi(cptr);
  while(!(isspace(*cptr))&&(*cptr != 0))cptr++;
  while((isspace(*cptr))&&(*cptr != 0))cptr++;
  desk2 = atoi(cptr);
  if(desk2 < desk1)
    {
      itemp = desk1;
      desk1 = desk2;
      desk2 = itemp;
    }
  ndesks = desk2 - desk1 + 1;
  
  Desks = (DeskInfo *)malloc(ndesks*sizeof(DeskInfo));
  for(i=0;i<ndesks;i++)
    {
      sprintf(line,"Desk %d",i+desk1);
      CopyString(&Desks[i].label,line);
    }
  
  /* Initialize X connection */
  if (!(dpy = XOpenDisplay(display_name))) 
    {
      fprintf(stderr,"%s: can't open display %s", MyName,
	      XDisplayName(display_name));
      exit (1);
    }
  x_fd = XConnectionNumber(dpy);
  
  Scr.screen= DefaultScreen(dpy);
  Scr.Root = RootWindow(dpy, Scr.screen);
  if(Scr.Root == None) 
    {
      fprintf(stderr,"%s: Screen %d is not valid ", MyName, (int)Scr.screen);
      exit(1);
    }
  Scr.d_depth = DefaultDepth(dpy, Scr.screen);

  sprintf(mask_mesg,"SET_MASK %lu\n",(unsigned long)(M_ADD_WINDOW|
    M_CONFIGURE_WINDOW|
    M_DESTROY_WINDOW|
    M_FOCUS_CHANGE|
    M_NEW_PAGE|
    M_NEW_DESK|
    M_RAISE_WINDOW|
    M_LOWER_WINDOW|
    M_ICONIFY|
    M_ICON_LOCATION|
    M_DEICONIFY|
    M_ICON_NAME|
    M_END_WINDOWLIST));
  SendInfo(fd,mask_mesg,0);

  ParseOptions(argv[3]);
  
  /* open a pager window */
  initialize_pager();
  
  /* Create a list of all windows */
  /* Request a list of all windows,
   * wait for ConfigureWindow packets */
  SendInfo(fd,"Send_WindowList",0);
  
  Loop(fd);
}