Example #1
0
/* Main Program */
INT4 main ( INT4 argc, CHAR *argv[] ) {

  static LALStatus status;
  INT4 c;
  UINT4 i;
  REAL8 dt, totTime;
  REAL8 sampleRate = -1;
  REAL8 totalMass = -1, massRatio = -1;
  REAL8 lowFreq = -1, df, fLow;
  CHAR  *outFile = NULL, *outFileLong = NULL, tail[50];
  size_t optarg_len;
  REAL8 eta;
  REAL8 newtonianChirpTime, PN1ChirpTime, mergTime;
  UINT4 numPts;
  LIGOTimeGPS epoch;
  REAL8 offset;

  PhenomCoeffs coeffs;
  PhenomParams params;

  REAL4FrequencySeries     *Aeff   = NULL, *Phieff  = NULL;
  COMPLEX8Vector           *uFPlus = NULL, *uFCross = NULL;

  COMPLEX8 num;

  REAL4Vector      *hPlus = NULL, *hCross = NULL;
  REAL4TimeSeries  *hP = NULL, *hC = NULL;
  /*  REAL4TimeSeries  *hP = NULL, *hC = NULL;*/
  REAL4FFTPlan     *prevPlus = NULL, *prevCross = NULL;

  /*REAL4Vector      *Freq = NULL;*/

  UINT4 windowLength;
  INT4 hPLength;
  REAL8 linearWindow;

  /* getopt arguments */
  struct option long_options[] =
  {
    {"mass-ratio",              required_argument, 0,                'q'},
    {"low-freq (Hz)",           required_argument, 0,                'f'},
    {"total-mass (M_sun)",      required_argument, 0,                'm'},
    {"sample-rate",             required_argument, 0,                's'},
    {"output-file",             required_argument, 0,                'o'},
    {"help",                    no_argument,       0,                'h'},
    {"version",                 no_argument,       0,                'V'},
    {0, 0, 0, 0}
  };

  /* parse the arguments */
  while ( 1 )
  {
    /* getopt_long stores long option here */
    int option_index = 0;

    /* parse command line arguments */
    c = getopt_long_only( argc, argv, "q:t:d:hV",
        long_options, &option_index );

    /* detect the end of the options */
    if ( c == -1 )
      {
	break;
      }

    switch ( c )
    {
      case 0:
        fprintf( stderr, "Error parsing option '%s' with argument '%s'\n",
            long_options[option_index].name, optarg );
        exit( 1 );
        break;

      case 'h':
        /* help message */
        print_usage( argv[0] );
        exit( 0 );
        break;

      case 'V':
        /* print version information and exit */
        fprintf( stdout, "%s - Compute Ajith's Phenomenological Waveforms " \
		 "(arXiv:0710.2335) and output them to a plain text file\n" \
            "CVS Version: %s\nCVS Tag: %s\n", PROGRAM_NAME, CVS_ID_STRING, \
            CVS_NAME_STRING );
        exit( 0 );
        break;

      case 'q':
        /* set mass ratio */
        massRatio = atof( optarg );
        break;

      case 'f':
        /* set low freq */
        lowFreq = atof( optarg );
        break;

      case 'm':
        /* set total mass */
        totalMass = atof( optarg );
        break;

      case 's':
        /* set sample rate */
        sampleRate = atof( optarg );
        break;

      case 'o':
	/* set name of output file */
        optarg_len = strlen(optarg) + 1;
        outFile = (CHAR *)calloc(optarg_len, sizeof(CHAR));
        memcpy(outFile, optarg, optarg_len);
	break;

      case '?':
        print_usage( argv[0] );
        exit( 1 );
        break;

      default:
        fprintf( stderr, "ERROR: Unknown error while parsing options\n" );
        print_usage( argv[0] );
        exit( 1 );
    }
  }

  if ( optind < argc )
  {
    fprintf( stderr, "ERROR: Extraneous command line arguments:\n" );
    while ( optind < argc )
      {
	fprintf ( stderr, "%s\n", argv[optind++] );
      }
    exit( 1 );
  }


  /* * * * * * * * */
  /* Main Program  */
  /* * * * * * * * */

  eta = massRatio / pow(1. + massRatio, 2.);

  /* This freq low is the one used for the FFT */
  /* fLow = 2.E-3/(totalMass*LAL_MTSUN_SI); */
  fLow = lowFreq;       /* Changed by Ajith. 5 May 2008 */

  /* Phenomenological coefficients as in Ajith et. al */
  GetPhenomCoeffsLongJena( &coeffs );

  /* Compute phenomenologial parameters */
  ComputeParamsFromCoeffs( &params, &coeffs, eta, totalMass );


  /* Check validity of arguments */

  /* check we have freqs */
  if ( totalMass < 0 )
    {
      fprintf( stderr, "ERROR: --total-mass must be specified\n" );
      exit( 1 );
    }

  /* check we have mass ratio and delta t*/
  if ( massRatio < 0 )
    {
      fprintf( stderr, "ERROR: --mass-ratio must be specified\n" );
      exit( 1 );
    }
  if ( lowFreq < 0 )
    {
      fprintf( stderr, "ERROR: --low-freq must be specified\n" );
      exit( 1 );
    }
  if ( sampleRate < 0 )
    {
      fprintf( stderr, "ERROR: --sample-rate must be specified\n" );
      exit( 1 );
    }
  if ( lowFreq > params.fCut )
    {
      fprintf( stderr, "\nERROR in --low-freq\n"\
	       "The value chosen for the low frequency is larger "\
	       "than the frequency at the merger.\n"
	       "Frequency at the merger: %4.2f Hz\nPick either a lower value"\
	       " for --low-freq or a lower total mass\n\n", params.fCut);
      exit(1);
    }
  if ( lowFreq < fLow )
    {
      fprintf( stderr, "\nERROR in --low-freq\n"\
	       "The value chosen for the low frequency is lower "\
	       "than the lowest frequency computed\nby the implemented FFT.\n"
	       "Lowest frequency allowed: %4.2f Hz\nPick either a higher value"\
	       " for --low-freq or a higher total mass\n\n", fLow);
      exit(1);
    }
  if ( outFile == NULL )
    {
      fprintf( stderr, "ERROR: --output-file must be specified\n" );
      exit( 1 );
    }

  /* Complete file name with details of the input variables */
  sprintf(tail, "%s-Phenom_M%3.1f_R%2.1f.dat", outFile, totalMass, massRatio);
  optarg_len = strlen(tail) + strlen(outFile) + 1;
  outFileLong = (CHAR *)calloc(optarg_len, sizeof(CHAR));
  strcpy(outFileLong, tail);

  /* check sample rate is enough */
  if (sampleRate > 4.*params.fCut)   /* Changed by Ajith. 5 May 2008 */
    {
      dt = 1./sampleRate;
    }
  else
    {
      sampleRate = 4.*params.fCut;
      dt = 1./sampleRate;
    }

  /* Estimation of the time duration of the binary           */
  /* See Sathya (1994) for the Newtonian and PN1 chirp times */
  /* The merger time is overestimated                        */
  newtonianChirpTime =
    (5./(256.*eta))*pow(totalMass*LAL_MTSUN_SI,-5./3.)*pow(LAL_PI*fLow,-8./3.);
  PN1ChirpTime =
    5.*(743.+924.*eta)/(64512.*eta*totalMass*LAL_MTSUN_SI*pow(LAL_PI*fLow,2.));
  mergTime = 2000.*totalMass*LAL_MTSUN_SI;
  totTime = 1.2 * (newtonianChirpTime + PN1ChirpTime + mergTime);

  numPts = (UINT4) ceil(totTime/dt);
  df = 1/(numPts * dt);

  /* Compute Amplitude and Phase from the paper (Eq. 4.19) */
  Aeff = XLALHybridP1Amplitude(&params, fLow, df, eta, totalMass, numPts/2+1);
  Phieff = XLALHybridP1Phase(&params, fLow, df, eta, totalMass, numPts/2 +1);

  /* Construct u(f) = Aeff*e^(i*Phieff) */
  XLALComputeComplexVector(&uFPlus, &uFCross, Aeff, Phieff);

  /* Scale this to units of M */
  for (i = 0; i < numPts/2 + 1; i++) {
    num = uFPlus->data[i];
    num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
    num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
    uFPlus->data[i] = num;
    num = uFCross->data[i];
    num.re *= 1./(dt*totalMass*LAL_MTSUN_SI);
    num.im *= 1./(dt*totalMass*LAL_MTSUN_SI);
    uFCross->data[i] = num;
  }

  /* Inverse Fourier transform */
  LALCreateReverseREAL4FFTPlan( &status, &prevPlus, numPts, 0 );
  LALCreateReverseREAL4FFTPlan( &status, &prevCross, numPts, 0 );
  hPlus = XLALCreateREAL4Vector(numPts);
  hCross = XLALCreateREAL4Vector(numPts);

  LALReverseREAL4FFT( &status, hPlus, uFPlus, prevPlus );
  LALReverseREAL4FFT( &status, hCross, uFCross, prevCross );

  /* The LAL implementation of the FFT omits the factor 1/n */
  for (i = 0; i < numPts; i++) {
    hPlus->data[i] /= numPts;
    hCross->data[i] /= numPts;
  }

  /* Create TimeSeries to store more info about the waveforms */
  /* Note: it could be done easier using LALFreqTimeFFT instead of ReverseFFT */
  epoch.gpsSeconds = 0;
  epoch.gpsNanoSeconds = 0;

  hP =
    XLALCreateREAL4TimeSeries("", &epoch, 0, dt, &lalDimensionlessUnit, numPts);
  hP->data = hPlus;
  hC =
    XLALCreateREAL4TimeSeries("", &epoch, 0, dt, &lalDimensionlessUnit, numPts);
  hC->data = hCross;

  /* Cutting off the part of the waveform with f < fLow */
  /*  Freq = XLALComputeFreq( hP, hC);
      hP = XLALCutAtFreq( hP, Freq, lowFreq);
      hC = XLALCutAtFreq( hC, Freq, lowFreq); */

  /* multiply the last few samples of the time-series by a linearly
   * dropping window function in order to avid edges in the data
   * Added by Ajith 6 May 2008 */

  hPLength = hP->data->length;
  windowLength = (UINT4) (20.*totalMass * LAL_MTSUN_SI/dt);
  for (i=1; i<= windowLength; i++){
    linearWindow =  (i-1.)/windowLength;
    hP->data->data[hPLength-i] *= linearWindow;
    hC->data->data[hPLength-i] *= linearWindow;
  }

  /* Convert t column to units of (1/M) */
  /*  offset *= (1./(totalMass * LAL_MTSUN_SI));
      hP->deltaT *= (1./(totalMass * LAL_MTSUN_SI)); */

  /* Set t = 0 at the merger (defined as the max of the NR wave) */
  XLALFindNRCoalescenceTimeFromhoft( &offset, hP);
  XLALGPSAdd( &(hP->epoch), -offset);
  XLALGPSAdd( &(hC->epoch), -offset);

  /* Print waveforms to file */
  LALPrintHPlusCross( hP, hC, outFileLong );

  /* Free Memory */

  XLALDestroyREAL4FrequencySeries(Aeff);
  XLALDestroyREAL4FrequencySeries(Phieff);

  XLALDestroyREAL4FFTPlan(prevPlus);
  XLALDestroyREAL4FFTPlan(prevCross);

  XLALDestroyCOMPLEX8Vector(uFPlus);
  XLALDestroyCOMPLEX8Vector(uFCross);
  XLALDestroyREAL4TimeSeries(hP);
  XLALDestroyREAL4TimeSeries(hC);
  /*  XLALDestroyREAL4TimeSeries(hP); */
  /*  XLALDestroyREAL4TimeSeries(hC); */

  return(0);

}
Example #2
0
int main( int argc, char **argv )
{
   int32_t ret;
   char optstring[OPTSTRING_LEN];
   int  opt;
   int  opt_alloc = 0;
   int  opt_status = 0;
   uint32_t alloc_size = 0;
   int  opt_pid = -1;
   VCSM_STATUS_T status_mode = VCSM_STATUS_NONE;

   void *usr_ptr_1;
   unsigned int usr_hdl_1;
#if defined(DOUBLE_ALLOC) || defined(RESIZE_ALLOC)
   void *usr_ptr_2;
   unsigned int usr_hdl_2;
#endif

   // Initialize VCOS
   vcos_init();

   vcos_log_set_level(&smem_log_category, VCOS_LOG_INFO);
   smem_log_category.flags.want_prefix = 0;
   vcos_log_register( "smem", &smem_log_category );

   // Create the option string that we will be using to parse the arguments
   create_optstring( optstring );

   // Parse the command line arguments
   while (( opt = getopt_long_only( argc, argv, optstring, long_opts,
                                    NULL )) != -1 )
   {
      switch ( opt )
      {
         case 0:
         {
            // getopt_long returns 0 for entries where flag is non-NULL
            break;
         }
         case OPT_ALLOC:
         {
            char *end;
            alloc_size = (uint32_t)strtoul( optarg, &end, 10 );
            if (end == optarg)
            {
               vcos_log_info( "Invalid arguments '%s'", optarg );
               goto err_out;
            }

            opt_alloc = 1;
            break;
         }
         case OPT_PID:
         {
            char *end;
            opt_pid = (int)strtol( optarg, &end, 10 );
            if (end == optarg)
            {
               vcos_log_info( "Invalid arguments '%s'", optarg );
               goto err_out;
            }

            break;
         }
         case OPT_STATUS:
         {
            char status_str[32];

            /* coverity[secure_coding] String length specified, so can't overflow */
            if ( sscanf( optarg, "%31s", status_str ) != 1 )
            {
               vcos_log_info( "Invalid arguments '%s'", optarg );
               goto err_out;
            }

            if ( vcos_strcasecmp( status_str, "all" ) == 0 )
            {
               status_mode = VCSM_STATUS_VC_MAP_ALL;
            }
            else if ( vcos_strcasecmp( status_str, "vc" ) == 0 )
            {
               status_mode = VCSM_STATUS_VC_WALK_ALLOC;
            }
            else if ( vcos_strcasecmp( status_str, "map" ) == 0 )
            {
               status_mode = VCSM_STATUS_HOST_WALK_MAP;
            }
            else if ( vcos_strcasecmp( status_str, "host" ) == 0 )
            {
               status_mode = VCSM_STATUS_HOST_WALK_PID_ALLOC;
            }
            else
            {
               goto err_out;
            }

            opt_status = 1;
            break;
         }
         default:
         {
            vcos_log_info( "Unrecognized option '%d'", opt );
            goto err_usage;
         }
         case '?':
         case OPT_HELP:
         {
            goto err_usage;
         }
      } // end switch
   } // end while

   argc -= optind;
   argv += optind;

   if (( optind == 1 ) || ( argc > 0 ))
   {
      if ( argc > 0 )
      {
         vcos_log_info( "Unrecognized argument -- '%s'", *argv );
      }

      goto err_usage;
   }

   // Start the shared memory support.
   if ( vcsm_init() == -1 )
   {
      vcos_log_info( "Cannot initialize smem device" );
      goto err_out;
   }

   if ( opt_alloc == 1 )
   {
      vcos_log_info( "Allocating 2 times %u-bytes in shared memory", alloc_size );

      usr_hdl_1 = vcsm_malloc( alloc_size,
                               "smem-test-alloc" );

      vcos_log_info( "Allocation 1 result: user %x, vc-hdl %x",
                     usr_hdl_1, vcsm_vc_hdl_from_hdl( usr_hdl_1 ) );

#if defined(DOUBLE_ALLOC) || defined(RESIZE_ALLOC)
      usr_hdl_2 = vcsm_malloc( alloc_size,
                               NULL );
      vcos_log_info( "Allocation 2 result: user %x",
                     usr_hdl_2 );

      usr_ptr_2 = vcsm_lock( usr_hdl_2 );
      vcos_log_info( "Allocation 2 : lock %p",
                     usr_ptr_2 );
      vcos_log_info( "Allocation 2 : unlock %d",
                     vcsm_unlock_hdl( usr_hdl_2 ) );
#endif

      // Do a simple write/read test.
      if ( usr_hdl_1 != 0 )
      {
         usr_ptr_1 = vcsm_lock( usr_hdl_1 );
         vcos_log_info( "Allocation 1 : lock %p",
                        usr_ptr_1 );
         if ( usr_ptr_1 )
         {
            memset ( usr_ptr_1,
                     0,
                     alloc_size );
            memcpy ( usr_ptr_1,
                     blah_blah,
                     32 );
            vcos_log_info( "Allocation 1 contains: \"%s\"",
                           (char *)usr_ptr_1 );

            vcos_log_info( "Allocation 1: vc-hdl %x",
                           vcsm_vc_hdl_from_ptr ( usr_ptr_1 ) );
            vcos_log_info( "Allocation 1: usr-hdl %x",
                           vcsm_usr_handle ( usr_ptr_1 ) );
            vcos_log_info( "Allocation 1 : unlock %d",
                           vcsm_unlock_ptr( usr_ptr_1 ) );
         }

         usr_ptr_1 = vcsm_lock( usr_hdl_1 );
         vcos_log_info( "Allocation 1 (relock) : lock %p",
                        usr_ptr_1 );
         if ( usr_ptr_1 )
         {
            vcos_log_info( "Allocation 1 (relock) : unlock %d",
                           vcsm_unlock_hdl( usr_hdl_1 ) );
         }
      }

#if defined(RESIZE_ALLOC)
      ret = vcsm_resize( usr_hdl_1, 2 * alloc_size );
      vcos_log_info( "Allocation 1 : resize %d", ret );
      if ( ret == 0 )
      {
         usr_ptr_1 = vcsm_lock( usr_hdl_1 );
         vcos_log_info( "Allocation 1 (resize) : lock %p",
                        usr_ptr_1 );
         if ( usr_ptr_1 )
         {
            memset ( usr_ptr_1,
                     0,
                     2 * alloc_size );
            memcpy ( usr_ptr_1,
                     blah_blah,
                     32 );
            vcos_log_info( "Allocation 1 (resized) contains: \"%s\"",
                           (char *)usr_ptr_1 );
            vcos_log_info( "Allocation 1 (resized) : unlock %d",
                           vcsm_unlock_ptr( usr_ptr_1 ) );
         }
      }

      // This checks that the memory can be remapped properly
      // because the Block 1 expanded beyond Block 2 boundary.
      //
      usr_ptr_2 = vcsm_lock( usr_hdl_2 );
      vcos_log_info( "Allocation 2 : lock %p",
                     usr_ptr_2 );
      vcos_log_info( "Allocation 2 : unlock %d",
                     vcsm_unlock_hdl( usr_hdl_2 ) );

      // This checks that we can free a memory block even if it
      // is locked, which could be the case if the application 
      // dies.
      //
      usr_ptr_2 = vcsm_lock( usr_hdl_2 );
      vcos_log_info( "Allocation 2 : lock %p",
                     usr_ptr_2 );
      vcsm_free ( usr_hdl_2 );
#endif

#if defined(DOUBLE_ALLOC)
#endif
   }

   if ( opt_status == 1 )
   {
      get_status( status_mode, opt_pid );
   }
   
   // If we allocated something, wait for the signal to exit to give chance for the
   // user to poke around the allocation test.
   //
   if ( opt_alloc == 1 )
   {
      start_monitor();
      
      vcos_event_wait( &quit_event );
      vcos_event_delete( &quit_event );
   }

   // Terminate the shared memory support.
   vcsm_exit ();
   goto err_out;

err_usage:
   show_usage();

err_out:
   exit( 1 );
}
Example #3
0
static int
captured_main (void *data)
{
  struct captured_main_args *context = data;
  int argc = context->argc;
  char **argv = context->argv;
  int count;
  static int quiet = 0;
  static int batch = 0;
  static int set_args = 0;
  static int already_initialized = 0;

  /* Pointers to various arguments from command line.  */
  char *symarg = NULL;
  char *execarg = NULL;
  char *corearg = NULL;
  char *cdarg = NULL;
  char *ttyarg = NULL;

  /* These are static so that we can take their address in an initializer.  */
  static int print_help;
  static int print_version;

  /* Pointers to all arguments of --command option.  */
  struct cmdarg {
    enum {
      CMDARG_FILE,
      CMDARG_COMMAND
    } type;
    char *string;
  } *cmdarg;
  /* Allocated size of cmdarg.  */
  int cmdsize;
  /* Number of elements of cmdarg used.  */
  int ncmd;

  /* Indices of all arguments of --directory option.  */
  char **dirarg;
  /* Allocated size.  */
  int dirsize;
  /* Number of elements used.  */
  int ndir;

  struct stat homebuf, cwdbuf;
  char *homedir;

  int i;

  long time_at_startup = get_run_time ();

#if defined (HAVE_SETLOCALE) && defined (HAVE_LC_MESSAGES)
  setlocale (LC_MESSAGES, "");
#endif
#if defined (HAVE_SETLOCALE)
  setlocale (LC_CTYPE, "");
#endif
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

#ifdef HAVE_SBRK
  lim_at_start = (char *) sbrk (0);
#endif

#if defined (ALIGN_STACK_ON_STARTUP)
  i = (int) &count & 0x3;
  if (i != 0)
    alloca (4 - i);
#endif

  /* (TiEmu 20050514 Kevin Kofler) Skip all these in case of a restart. */
  cmdsize = 1;
  cmdarg = (struct cmdarg *) xmalloc (cmdsize * sizeof (*cmdarg));
  ncmd = 0;
  dirsize = 1;
  dirarg = (char **) xmalloc (dirsize * sizeof (*dirarg));
  ndir = 0;

  quit_flag = 0;
  line = (char *) xmalloc (linesize);
  line[0] = '\0';		/* Terminate saved (now empty) cmd line */
  if (already_initialized)
    {
      /* (TiEmu 20050512 Kevin Kofler) Reinitialize Insight in case of a restart. */
      gdbtk_started = 0;
      gdbtk_disable_fputs = 1;
    }
  else
  {
  instream = stdin;

  getcwd (gdb_dirbuf, sizeof (gdb_dirbuf));
  current_directory = gdb_dirbuf;

  gdb_stdout = stdio_fileopen (stdout);
  gdb_stderr = stdio_fileopen (stderr);
  gdb_stdlog = gdb_stderr;	/* for moment */
  gdb_stdtarg = gdb_stderr;	/* for moment */
  gdb_stdin = stdio_fileopen (stdin);
  gdb_stdtargerr = gdb_stderr;	/* for moment */
  gdb_stdtargin = gdb_stdin;	/* for moment */

  /* Set the sysroot path.  */
#ifdef TARGET_SYSTEM_ROOT_RELOCATABLE
  gdb_sysroot = make_relative_prefix (argv[0], BINDIR, TARGET_SYSTEM_ROOT);
  if (gdb_sysroot)
    {
      struct stat s;
      int res = 0;

      if (stat (gdb_sysroot, &s) == 0)
	if (S_ISDIR (s.st_mode))
	  res = 1;

      if (res == 0)
	{
	  xfree (gdb_sysroot);
	  gdb_sysroot = TARGET_SYSTEM_ROOT;
	}
    }
  else
    gdb_sysroot = TARGET_SYSTEM_ROOT;
#else
#if defined (TARGET_SYSTEM_ROOT)
  gdb_sysroot = TARGET_SYSTEM_ROOT;
#else
  gdb_sysroot = "";
#endif
#endif

  /* There will always be an interpreter.  Either the one passed into
     this captured main, or one specified by the user at start up, or
     the console.  Initialize the interpreter to the one requested by 
     the application.  */
  interpreter_p = xstrdup (context->interpreter_p);

  /* Parse arguments and options.  */
  {
    int c;
    /* When var field is 0, use flag field to record the equivalent
       short option (or arbitrary numbers starting at 10 for those
       with no equivalent).  */
    enum {
      OPT_SE = 10,
      OPT_CD,
      OPT_ANNOTATE,
      OPT_STATISTICS,
      OPT_TUI,
      OPT_NOWINDOWS,
      OPT_WINDOWS
    };
    static struct option long_options[] =
    {
#if defined(TUI)
      {"tui", no_argument, 0, OPT_TUI},
#endif
      {"xdb", no_argument, &xdb_commands, 1},
      {"dbx", no_argument, &dbx_commands, 1},
      {"readnow", no_argument, &readnow_symbol_files, 1},
      {"r", no_argument, &readnow_symbol_files, 1},
      {"quiet", no_argument, &quiet, 1},
      {"q", no_argument, &quiet, 1},
      {"silent", no_argument, &quiet, 1},
      {"nx", no_argument, &inhibit_gdbinit, 1},
      {"n", no_argument, &inhibit_gdbinit, 1},
      {"batch-silent", no_argument, 0, 'B'},
      {"batch", no_argument, &batch, 1},
      {"epoch", no_argument, &epoch_interface, 1},

    /* This is a synonym for "--annotate=1".  --annotate is now preferred,
       but keep this here for a long time because people will be running
       emacses which use --fullname.  */
      {"fullname", no_argument, 0, 'f'},
      {"f", no_argument, 0, 'f'},

      {"annotate", required_argument, 0, OPT_ANNOTATE},
      {"help", no_argument, &print_help, 1},
      {"se", required_argument, 0, OPT_SE},
      {"symbols", required_argument, 0, 's'},
      {"s", required_argument, 0, 's'},
      {"exec", required_argument, 0, 'e'},
      {"e", required_argument, 0, 'e'},
      {"core", required_argument, 0, 'c'},
      {"c", required_argument, 0, 'c'},
      {"pid", required_argument, 0, 'p'},
      {"p", required_argument, 0, 'p'},
      {"command", required_argument, 0, 'x'},
      {"eval-command", required_argument, 0, 'X'},
      {"version", no_argument, &print_version, 1},
      {"x", required_argument, 0, 'x'},
      {"ex", required_argument, 0, 'X'},
#ifdef GDBTK
      {"tclcommand", required_argument, 0, 'z'},
      {"enable-external-editor", no_argument, 0, 'y'},
      {"editor-command", required_argument, 0, 'w'},
#endif
      {"ui", required_argument, 0, 'i'},
      {"interpreter", required_argument, 0, 'i'},
      {"i", required_argument, 0, 'i'},
      {"directory", required_argument, 0, 'd'},
      {"d", required_argument, 0, 'd'},
      {"cd", required_argument, 0, OPT_CD},
      {"tty", required_argument, 0, 't'},
      {"baud", required_argument, 0, 'b'},
      {"b", required_argument, 0, 'b'},
      {"nw", no_argument, NULL, OPT_NOWINDOWS},
      {"nowindows", no_argument, NULL, OPT_NOWINDOWS},
      {"w", no_argument, NULL, OPT_WINDOWS},
      {"windows", no_argument, NULL, OPT_WINDOWS},
      {"statistics", no_argument, 0, OPT_STATISTICS},
      {"write", no_argument, &write_files, 1},
      {"args", no_argument, &set_args, 1},
     {"l", required_argument, 0, 'l'},
      {"return-child-result", no_argument, &return_child_result, 1},
      {0, no_argument, 0, 0}
    };

    while (1)
      {
	int option_index;

	c = getopt_long_only (argc, argv, "",
			      long_options, &option_index);
	if (c == EOF || set_args)
	  break;

	/* Long option that takes an argument.  */
	if (c == 0 && long_options[option_index].flag == 0)
	  c = long_options[option_index].val;

	switch (c)
	  {
	  case 0:
	    /* Long option that just sets a flag.  */
	    break;
	  case OPT_SE:
	    symarg = optarg;
	    execarg = optarg;
	    break;
	  case OPT_CD:
	    cdarg = optarg;
	    break;
	  case OPT_ANNOTATE:
	    /* FIXME: what if the syntax is wrong (e.g. not digits)?  */
	    annotation_level = atoi (optarg);
	    break;
	  case OPT_STATISTICS:
	    /* Enable the display of both time and space usage.  */
	    display_time = 1;
	    display_space = 1;
	    break;
	  case OPT_TUI:
	    /* --tui is equivalent to -i=tui.  */
	    xfree (interpreter_p);
	    interpreter_p = xstrdup (INTERP_TUI);
	    break;
	  case OPT_WINDOWS:
	    /* FIXME: cagney/2003-03-01: Not sure if this option is
               actually useful, and if it is, what it should do.  */
#ifdef GDBTK
	    /* --windows is equivalent to -i=insight.  */
	    xfree (interpreter_p);
	    interpreter_p = xstrdup (INTERP_INSIGHT);
#endif
	    use_windows = 1;
	    break;
	  case OPT_NOWINDOWS:
	    /* -nw is equivalent to -i=console.  */
	    xfree (interpreter_p);
	    interpreter_p = xstrdup (INTERP_CONSOLE);
	    use_windows = 0;
	    break;
	  case 'f':
	    annotation_level = 1;
/* We have probably been invoked from emacs.  Disable window interface.  */
	    use_windows = 0;
	    break;
	  case 's':
	    symarg = optarg;
	    break;
	  case 'e':
	    execarg = optarg;
	    break;
	  case 'c':
	    corearg = optarg;
	    break;
	  case 'p':
	    /* "corearg" is shared by "--core" and "--pid" */
	    corearg = optarg;
	    break;
	  case 'x':
	    cmdarg[ncmd].type = CMDARG_FILE;
	    cmdarg[ncmd++].string = optarg;
	    if (ncmd >= cmdsize)
	      {
		cmdsize *= 2;
		cmdarg = xrealloc ((char *) cmdarg,
				   cmdsize * sizeof (*cmdarg));
	      }
	    break;
	  case 'X':
	    cmdarg[ncmd].type = CMDARG_COMMAND;
	    cmdarg[ncmd++].string = optarg;
	    if (ncmd >= cmdsize)
	      {
		cmdsize *= 2;
		cmdarg = xrealloc ((char *) cmdarg,
				   cmdsize * sizeof (*cmdarg));
	      }
	    break;
	  case 'B':
	    batch = batch_silent = 1;
	    gdb_stdout = ui_file_new();
	    break;
#ifdef GDBTK
	  case 'z':
	    {
extern int gdbtk_test (char *);
	      if (!gdbtk_test (optarg))
		{
		  fprintf_unfiltered (gdb_stderr, _("%s: unable to load tclcommand file \"%s\""),
				      argv[0], optarg);
		  exit (1);
		}
	      break;
	    }
	  case 'y':
	    /* Backwards compatibility only.  */
	    break;
	  case 'w':
	    {
	      external_editor_command = xstrdup (optarg);
	      break;
	    }
#endif /* GDBTK */
	  case 'i':
	    xfree (interpreter_p);
	    interpreter_p = xstrdup (optarg);
	    break;
	  case 'd':
	    dirarg[ndir++] = optarg;
	    if (ndir >= dirsize)
	      {
		dirsize *= 2;
		dirarg = (char **) xrealloc ((char *) dirarg,
					     dirsize * sizeof (*dirarg));
	      }
	    break;
	  case 't':
	    ttyarg = optarg;
	    break;
	  case 'q':
	    quiet = 1;
	    break;
	  case 'b':
	    {
	      int i;
	      char *p;

	      i = strtol (optarg, &p, 0);
	      if (i == 0 && p == optarg)

		/* Don't use *_filtered or warning() (which relies on
		   current_target) until after initialize_all_files(). */

		fprintf_unfiltered
		  (gdb_stderr,
		   _("warning: could not set baud rate to `%s'.\n"), optarg);
	      else
		baud_rate = i;
	    }
            break;
	  case 'l':
	    {
	      int i;
	      char *p;

	      i = strtol (optarg, &p, 0);
	      if (i == 0 && p == optarg)

		/* Don't use *_filtered or warning() (which relies on
		   current_target) until after initialize_all_files(). */

		fprintf_unfiltered
		  (gdb_stderr,
		 _("warning: could not set timeout limit to `%s'.\n"), optarg);
	      else
		remote_timeout = i;
	    }
	    break;

	  case '?':
	    fprintf_unfiltered (gdb_stderr,
			_("Use `%s --help' for a complete list of options.\n"),
				argv[0]);
	    exit (1);
	  }
      }

    /* If --help or --version, disable window interface.  */
    if (print_help || print_version)
      {
	use_windows = 0;
      }

    if (set_args)
      {
	/* The remaining options are the command-line options for the
	   inferior.  The first one is the sym/exec file, and the rest
	   are arguments.  */
	if (optind >= argc)
	  {
	    fprintf_unfiltered (gdb_stderr,
				_("%s: `--args' specified but no program specified\n"),
				argv[0]);
	    exit (1);
	  }
	symarg = argv[optind];
	execarg = argv[optind];
	++optind;
	set_inferior_args_vector (argc - optind, &argv[optind]);
      }
    else
      {
	/* OK, that's all the options.  The other arguments are filenames.  */
	count = 0;
	for (; optind < argc; optind++)
	  switch (++count)
	    {
	    case 1:
	      symarg = argv[optind];
	      execarg = argv[optind];
	      break;
	    case 2:
	      /* The documentation says this can be a "ProcID" as well. 
	         We will try it as both a corefile and a pid.  */
	      corearg = argv[optind];
	      break;
	    case 3:
	      fprintf_unfiltered (gdb_stderr,
				  _("Excess command line arguments ignored. (%s%s)\n"),
				  argv[optind], (optind == argc - 1) ? "" : " ...");
	      break;
	    }
      }
    if (batch)
      quiet = 1;
  }

  /* Initialize all files.  Give the interpreter a chance to take
     control of the console via the deprecated_init_ui_hook ().  */
  gdb_init (argv[0]);
    already_initialized = 1;
  }

  /* Do these (and anything which might call wrap_here or *_filtered)
     after initialize_all_files() but before the interpreter has been
     installed.  Otherwize the help/version messages will be eaten by
     the interpreter's output handler.  */

  if (print_version)
    {
      print_gdb_version (gdb_stdout);
      wrap_here ("");
      printf_filtered ("\n");
      exit (0);
    }

  if (print_help)
    {
      print_gdb_help (gdb_stdout);
      fputs_unfiltered ("\n", gdb_stdout);
      exit (0);
    }

  /* FIXME: cagney/2003-02-03: The big hack (part 1 of 2) that lets
     GDB retain the old MI1 interpreter startup behavior.  Output the
     copyright message before the interpreter is installed.  That way
     it isn't encapsulated in MI output.  */
  if (!quiet && strcmp (interpreter_p, INTERP_MI1) == 0)
    {
      /* Print all the junk at the top, with trailing "..." if we are about
         to read a symbol file (possibly slowly).  */
      print_gdb_version (gdb_stdout);
      if (symarg)
	printf_filtered ("..");
      wrap_here ("");
      printf_filtered ("\n");
      gdb_flush (gdb_stdout);	/* Force to screen during slow operations */
    }


  /* Install the default UI.  All the interpreters should have had a
     look at things by now.  Initialize the default interpreter. */

  {
    /* Find it.  */
    struct interp *interp = interp_lookup (interpreter_p);
    if (interp == NULL)
      error (_("Interpreter `%s' unrecognized"), interpreter_p);
    /* Install it.  */
    if (!interp_set (interp))
      {
        fprintf_unfiltered (gdb_stderr,
			    "Interpreter `%s' failed to initialize.\n",
                            interpreter_p);
        exit (1);
      }
  }

  /* FIXME: cagney/2003-02-03: The big hack (part 2 of 2) that lets
     GDB retain the old MI1 interpreter startup behavior.  Output the
     copyright message after the interpreter is installed when it is
     any sane interpreter.  */
  if (!quiet && !current_interp_named_p (INTERP_MI1))
    {
      /* Print all the junk at the top, with trailing "..." if we are about
         to read a symbol file (possibly slowly).  */
      print_gdb_version (gdb_stdout);
      if (symarg)
	printf_filtered ("..");
      wrap_here ("");
      printf_filtered ("\n");
      gdb_flush (gdb_stdout);	/* Force to screen during slow operations */
    }

  /* Set off error and warning messages with a blank line.  */
  error_pre_print = "\n";
  quit_pre_print = error_pre_print;
  warning_pre_print = _("\nwarning: ");

  /* Read and execute $HOME/.gdbinit file, if it exists.  This is done
     *before* all the command line arguments are processed; it sets
     global parameters, which are independent of what file you are
     debugging or what directory you are in.  */
  homedir = getenv ("HOME");
  if (homedir)
    {
      char *homeinit = xstrprintf ("%s/%s", homedir, gdbinit);

      if (!inhibit_gdbinit)
	{
	  catch_command_errors (source_script, homeinit, 0, RETURN_MASK_ALL);
	}

      /* Do stats; no need to do them elsewhere since we'll only
         need them if homedir is set.  Make sure that they are
         zero in case one of them fails (this guarantees that they
         won't match if either exists).  */

      memset (&homebuf, 0, sizeof (struct stat));
      memset (&cwdbuf, 0, sizeof (struct stat));

      stat (homeinit, &homebuf);
      stat (gdbinit, &cwdbuf);	/* We'll only need this if
				   homedir was set.  */
      xfree (homeinit);
    }

  /* Now perform all the actions indicated by the arguments.  */
  if (cdarg != NULL)
    {
      catch_command_errors (cd_command, cdarg, 0, RETURN_MASK_ALL);
    }

  for (i = 0; i < ndir; i++)
    catch_command_errors (directory_switch, dirarg[i], 0, RETURN_MASK_ALL);
  xfree (dirarg);

  if (execarg != NULL
      && symarg != NULL
      && strcmp (execarg, symarg) == 0)
    {
      /* The exec file and the symbol-file are the same.  If we can't
         open it, better only print one error message.
         catch_command_errors returns non-zero on success! */
      if (catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL))
	catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL);
    }
  else
    {
      if (execarg != NULL)
	catch_command_errors (exec_file_attach, execarg, !batch, RETURN_MASK_ALL);
      if (symarg != NULL)
	catch_command_errors (symbol_file_add_main, symarg, 0, RETURN_MASK_ALL);
    }

  if (corearg != NULL)
    {
      /* corearg may be either a corefile or a pid.
	 If its first character is a digit, try attach first
	 and then corefile.  Otherwise try corefile first. */

      if (isdigit (corearg[0]))
	{
	  if (catch_command_errors (attach_command, corearg, 
				    !batch, RETURN_MASK_ALL) == 0)
	    catch_command_errors (core_file_command, corearg, 
				  !batch, RETURN_MASK_ALL);
	}
      else /* Can't be a pid, better be a corefile. */
	catch_command_errors (core_file_command, corearg, 
			      !batch, RETURN_MASK_ALL);
    }

  if (ttyarg != NULL)
    catch_command_errors (tty_command, ttyarg, !batch, RETURN_MASK_ALL);

  /* Error messages should no longer be distinguished with extra output. */
  error_pre_print = NULL;
  quit_pre_print = NULL;
  warning_pre_print = _("warning: ");

  /* Read the .gdbinit file in the current directory, *if* it isn't
     the same as the $HOME/.gdbinit file (it should exist, also).  */

  if (!homedir
      || memcmp ((char *) &homebuf, (char *) &cwdbuf, sizeof (struct stat)))
    if (!inhibit_gdbinit)
      {
	catch_command_errors (source_script, gdbinit, 0, RETURN_MASK_ALL);
      }

  for (i = 0; i < ncmd; i++)
    {
#if 0
      /* NOTE: cagney/1999-11-03: SET_TOP_LEVEL() was a macro that
         expanded into a call to setjmp().  */
      if (!SET_TOP_LEVEL ()) /* NB: This is #if 0'd out */
	{
	  /* NOTE: I am commenting this out, because it is not clear
	     where this feature is used. It is very old and
	     undocumented. ezannoni: 1999-05-04 */
#if 0
	  if (cmdarg[i][0] == '-' && cmdarg[i][1] == '\0')
	    read_command_file (stdin);
	  else
#endif
	    source_script (cmdarg[i], !batch);
	  do_cleanups (ALL_CLEANUPS);
	}
#endif
      if (cmdarg[i].type == CMDARG_FILE)
        catch_command_errors (source_script, cmdarg[i].string,
			      !batch, RETURN_MASK_ALL);
      else  /* cmdarg[i].type == CMDARG_COMMAND */
        catch_command_errors (execute_command, cmdarg[i].string,
			      !batch, RETURN_MASK_ALL);
    }
  xfree (cmdarg);

  /* Read in the old history after all the command files have been read. */
  init_history ();

  if (batch)
    {
      /* We have hit the end of the batch file.  */
      quit_force (NULL, 0);
    }

  /* Do any host- or target-specific hacks.  This is used for i960 targets
     to force the user to set a nindy target and spec its parameters.  */

#ifdef BEFORE_MAIN_LOOP_HOOK
  BEFORE_MAIN_LOOP_HOOK;
#endif

  /* Show time and/or space usage.  */

  if (display_time)
    {
      long init_time = get_run_time () - time_at_startup;

      printf_unfiltered (_("Startup time: %ld.%06ld\n"),
			 init_time / 1000000, init_time % 1000000);
    }

  if (display_space)
    {
#ifdef HAVE_SBRK
      extern char **environ;
      char *lim = (char *) sbrk (0);

      printf_unfiltered (_("Startup size: data size %ld\n"),
			 (long) (lim - (char *) &environ));
#endif
    }

#if 0
  /* FIXME: cagney/1999-11-06: The original main loop was like: */
  while (1)
    {
      if (!SET_TOP_LEVEL ())
	{
	  do_cleanups (ALL_CLEANUPS);	/* Do complete cleanup */
	  /* GUIs generally have their own command loop, mainloop, or
	     whatever.  This is a good place to gain control because
	     many error conditions will end up here via longjmp().  */
	  if (deprecated_command_loop_hook)
	    deprecated_command_loop_hook ();
	  else
	    deprecated_command_loop ();
	  quit_command ((char *) 0, instream == stdin);
	}
    }
  /* NOTE: If the command_loop() returned normally, the loop would
     attempt to exit by calling the function quit_command().  That
     function would either call exit() or throw an error returning
     control to SET_TOP_LEVEL. */
  /* NOTE: The function do_cleanups() was called once each time round
     the loop.  The usefulness of the call isn't clear.  If an error
     was thrown, everything would have already been cleaned up.  If
     command_loop() returned normally and quit_command() was called,
     either exit() or error() (again cleaning up) would be called. */
#endif
  /* NOTE: cagney/1999-11-07: There is probably no reason for not
     moving this loop and the code found in captured_command_loop()
     into the command_loop() proper.  The main thing holding back that
     change - SET_TOP_LEVEL() - has been eliminated. */
  while (1)
    {
      catch_errors (captured_command_loop, 0, "", RETURN_MASK_ALL);
    }
  /* No exit -- exit is through quit_command.  */
}
Example #4
0
int main(int argc, char** argv)
{
    int     ret = 0;
    int     option = 0;
    int     ignoreIn = 0;
    int     ignoreOut = 0;
    int     long_index = 0;
    int     i;

    if (argc == 1) {
        printf("Main Help.\n");
        wolfCLU_help();
    }
    /* Set ignore variables for -in and -out files */
    ret = wolfCLU_checkForArg("-in", 3, argc, argv);
    if (ret > 0) {
        ignoreIn = ret + 1;
    }
    ret = wolfCLU_checkForArg("-out", 4, argc, argv);
    if (ret > 0) {
        ignoreOut = ret + 1;
    }


    /* flexibility: allow users to input any CAPS or lower case,
     * we will do all processing on lower case only. */
    for (i = 0; i < argc; i++) {
        if (i != ignoreIn && i != ignoreOut) {
            convert_to_lower(argv[i], (int) XSTRLEN(argv[i]));
        }
    }

    while ((option = getopt_long_only(argc, argv,"",
                   long_options, &long_index )) != -1) {

        switch (option) {
            /* Encrypt */
            case ENCRYPT:  ret = wolfCLU_setup(argc, argv, 'e');
                            break;
            /* Decrypt */
            case DECRYPT:  ret = wolfCLU_setup(argc, argv, 'd');;
                            break;
            /* Benchmark */
            case BENCHMARK:ret = wolfCLU_benchSetup(argc, argv);
                            break;
            /* Hash */
            case HASH:     ret = wolfCLU_hashSetup(argc, argv);
                            break;
            /* x509 Certificate processing */
            case X509:     ret = wolfCLU_certSetup(argc, argv);
                            break;
            /* x509 Certificate request */
            case REQUEST:  ret = wolfCLU_requestSetup(argc, argv);
                            break;
            case GEN_KEY:  ret = wolfCLU_genKeySetup(argc, argv);
                            break;
/* Ignore the following arguments for now. Will be handled by their respective
 * setups IE Crypto setup, Benchmark setup, or Hash Setup */

            /* File passed in by user */
            case INFILE:    break;
            /* Output file */
            case OUTFILE:   break;
            /* Password */
            case PASSWORD:  break;
            /* Key if used must be in hex */
            case KEY:       break;
            /* IV if used must be in hex */
            case IV:        break;
            /* Opt to benchmark all available algorithms */
            case ALL:       break;
            /* size for hash to output */
            case SIZE:      break;
            /* Time to benchmark for 1-10 seconds optional default: 3s */
            case TIME:      break;
            /* Verify results, used with -iv and -key */
            case VERIFY:    break;
            /* Certificate Stuff*/
            case INFORM:    break;
            case OUTFORM:   break;
            case OUTPUT:    break;
            case NOOUT:     break;
            case TEXT_OUT:  break;
            case SILENT:    break;
            case HELP1:
                    if (argc == 2) {
                        printf("Main help menu:\n");
                        wolfCLU_help();
                        return 0;
                    }
                    break;
            case HELP2:
                    if (argc == 2) {
                        printf("Main help menu:\n");
                        wolfCLU_help();
                        return 0;
                    }
                    break;
            /* which version of clu am I using */
            case VERBOSE:
                            wolfCLU_verboseHelp();
                            return 0;
/*End of ignored arguments */

            case 'v':       wolfCLU_version();
                            return 0;

             default:
                            printf("Main help default.\n");
                            wolfCLU_help();
                            return 0;
        }
    }

    if (ret != 0)
        printf("Error returned: %d.\n", ret);

    return ret;
}
Example #5
0
/******************************************************************************
Description.: this function is called first, in order to initialise
              this plugin and pass a parameter string
Input Value.: parameters
Return Value: 0 if everything is ok, non-zero otherwise
******************************************************************************/
int output_init(output_parameter *param)
{
    int i;

    delay = 0;

    param->argv[0] = OUTPUT_PLUGIN_NAME;

    /* show all parameters for DBG purposes */
    for(i = 0; i < param->argc; i++) {
        DBG("argv[%d]=%s\n", i, param->argv[i]);
    }

    reset_getopt();
    while(1) {
        int option_index = 0, c = 0;
        static struct option long_options[] = {
            {"h", no_argument, 0, 0
            },
            {"help", no_argument, 0, 0},
            {"f", required_argument, 0, 0},
            {"folder", required_argument, 0, 0},
            {"d", required_argument, 0, 0},
            {"delay", required_argument, 0, 0},
            {"c", required_argument, 0, 0},
            {"command", required_argument, 0, 0},
            {"I", required_argument, 0, 0},
            {"IP", required_argument, 0, 0},
            {"p", required_argument, 0, 0},
            {"port", required_argument, 0, 0},
            {"i", required_argument, 0, 0},
            {"input", required_argument, 0, 0},
            {0, 0, 0, 0}
        };

        c = getopt_long_only(param->argc, param->argv, "", long_options, &option_index);

        /* no more options to parse */
        if(c == -1) break;

        /* unrecognized option */
        if(c == '?') {
            help();
            return 1;
        }

        switch(option_index) {
            /* h, help */
        case 0:
        case 1:
            DBG("case 0,1\n");
            help();
            return 1;
            break;

            /* f, folder */
        case 2:
        case 3:
            DBG("case 2,3\n");
            folder = malloc(strlen(optarg) + 1);
            strcpy(folder, optarg);
            if(folder[strlen(folder)-1] == '/')
                folder[strlen(folder)-1] = '\0';
            break;

            /* d, delay */
        case 4:
        case 5:
            DBG("case 4,5\n");
            delay = atoi(optarg);
            break;

            /* c, command */
        case 6:
        case 7:
            DBG("case 6,7\n");
            command = strdup(optarg);
            break;

            /* I, ip addr */
        case 8:
        case 9:
            DBG("case 8,9\n");
            ip = strdup(optarg);
            break;

            /* p, port */
        case 10:
        case 11:
            DBG("case 8,9\n");
            port = atoi(optarg);
            break;
            /* i, input */
        case 12:
        case 13:
            DBG("case 10,11\n");
            input_number = atoi(optarg);
            break;
        }
    }

    pglobal = param->global;
    if(ip == NULL){
    	OPRINT("ERROR: no ip address, eg: \"-I 172.0.0.1\"\n");
    	return 1;
    }
    if(!(input_number < pglobal->incnt)) {
        OPRINT("ERROR: the %d input_plugin number is too much only %d plugins loaded\n", input_number, pglobal->incnt);
        return 1;
    }
    OPRINT("input plugin.....: %d: %s\n", input_number, pglobal->in[input_number].plugin);
    OPRINT("output folder.....: %s\n", folder);
    OPRINT("delay after save..: %d\n", delay);
    OPRINT("command...........: %s\n", (command == NULL) ? "disabled" : command);
    OPRINT("UDP IP..........: %s\n", ip);
    if(port > 0) {
        OPRINT("UDP port..........: %d\n", port);
    } else {
        OPRINT("UDP port..........: %s\n", "disabled");
    }
    return 0;
}
Example #6
0
int
main(int argc, char *argv[])
{
	struct ifreq ifr;
	struct ipsectunnelconf *shc=(struct ipsectunnelconf *)&ifr.ifr_data;
	int s;
	int c, previous = -1;
	char *program_name;
	int debug = 0;
	int argcount = argc;
	char me[] = "ipsec tncfg";
     
	memset(&ifr, 0, sizeof(ifr));
	program_name = argv[0];

	while((c = getopt_long_only(argc, argv, ""/*"adchvV:P:l:+:"*/, longopts, 0)) != EOF) {
		switch(c) {
		case 'g':
			debug = 1;
			argcount--;
			break;
		case 'a':
			if(shc->cf_cmd) {
				fprintf(stderr, "%s: exactly one of '--attach', '--detach' or '--clear' options must be specified.\n",	program_name);
				exit(1);
			}
			shc->cf_cmd = IPSEC_SET_DEV;
			break;
		case 'd':
			if(shc->cf_cmd) {
				fprintf(stderr, "%s: exactly one of '--attach', '--detach' or '--clear' options must be specified.\n",	program_name);
				exit(1);
			}
			shc->cf_cmd = IPSEC_DEL_DEV;
			break;
		case 'c':
			if(shc->cf_cmd) {
				fprintf(stderr, "%s: exactly one of '--attach', '--detach' or '--clear' options must be specified.\n",	program_name);
				exit(1);
			}
			shc->cf_cmd = IPSEC_CLR_DEV;
			break;
		case 'h':
			usage(program_name);
			break;
		case 'v':
			if(optarg) {
				fprintf(stderr, "%s: warning; '-v' and '--version' options don't expect arguments, arg '%s' found, perhaps unintended.\n",
					program_name, optarg);
			}
			fprintf(stdout, "%s %s\n", me, ipsec_version_code());
			fprintf(stdout, "See `ipsec --copyright' for copyright information.\n");
			exit(1);
			break;
		case 'V':
			strcpy(ifr.ifr_name, optarg);
			break;
		case 'P':
			strcpy(shc->cf_name, optarg);
			break;
		case 'l':
			program_name = malloc(strlen(argv[0])
					      + 10 /* update this when changing the sprintf() */
					      + strlen(optarg));
			sprintf(program_name, "%s --label %s",
				argv[0],
				optarg);
			argcount -= 2;
			break;
		case '+': /* optionsfrom */
			optionsfrom(optarg, &argc, &argv, optind, stderr);
			/* no return on error */
			break;
		default:
			usage(program_name);
			break;
		}
		previous = c;
	}

	if(argcount == 1) {
		system("cat /proc/net/ipsec_tncfg");
		exit(0);
	}

	switch(shc->cf_cmd) {
	case IPSEC_SET_DEV:
		if(!shc->cf_name) {
			fprintf(stderr, "%s: physical I/F parameter missing.\n",
				program_name);
			exit(1);
		}
	case IPSEC_DEL_DEV:
		if(!ifr.ifr_name) {
			fprintf(stderr, "%s: virtual I/F parameter missing.\n",
				program_name);
			exit(1);
		}
		break;
	case IPSEC_CLR_DEV:
		strcpy(ifr.ifr_name, "ipsec0");
		break;
	default:
		fprintf(stderr, "%s: exactly one of '--attach', '--detach' or '--clear' options must be specified.\n"
			"Try %s --help' for usage information.\n",
			program_name, program_name);
		exit(1);
	}

	s=socket(AF_INET, SOCK_DGRAM,0);
	if(s==-1)
	{
		fprintf(stderr, "%s: Socket creation failed -- ", program_name);
		switch(errno)
		{
		case EACCES:
			if(getuid()==0)
				fprintf(stderr, "Root denied permission!?!\n");
			else
				fprintf(stderr, "Run as root user.\n");
			break;
		case EPROTONOSUPPORT:
			fprintf(stderr, "Internet Protocol not enabled");
			break;
		case EMFILE:
		case ENFILE:
		case ENOBUFS:
			fprintf(stderr, "Insufficient system resources.\n");
			break;
		case ENODEV:
			fprintf(stderr, "No such device.  Is the virtual device valid?  Is the ipsec module linked into the kernel or loaded as a module?\n");
			break;
		default:
			fprintf(stderr, "Unknown socket error %d.\n", errno);
		}
		exit(1);
	}
	if(ioctl(s, shc->cf_cmd, &ifr)==-1)
	{
		if(shc->cf_cmd == IPSEC_SET_DEV) {
			fprintf(stderr, "%s: Socket ioctl failed on attach -- ", program_name);
			switch(errno)
			{
			case EINVAL:
				fprintf(stderr, "Invalid argument, check kernel log messages for specifics.\n");
				break;
			case ENODEV:
				fprintf(stderr, "No such device.  Is the virtual device valid?  Is the ipsec module linked into the kernel or loaded as a module?\n");
				break;
			case ENXIO:
				fprintf(stderr, "No such device.  Is the physical device valid?\n");
				break;
			case EBUSY:
				fprintf(stderr, "Device busy.  Virtual device %s is already attached to a physical device -- Use detach first.\n",
				       ifr.ifr_name);
				break;
			default:
				fprintf(stderr, "Unknown socket error %d.\n", errno);
			}
			exit(1);
		}
		if(shc->cf_cmd == IPSEC_DEL_DEV) {
			fprintf(stderr, "%s: Socket ioctl failed on detach -- ", program_name);
			switch(errno)
			{
			case EINVAL:
				fprintf(stderr, "Invalid argument, check kernel log messages for specifics.\n");
				break;
			case ENODEV:
				fprintf(stderr, "No such device.  Is the virtual device valid?  The ipsec module may not be linked into the kernel or loaded as a module.\n");
				break;
			case ENXIO:
				fprintf(stderr, "Device requested is not linked to any physical device.\n");
				break;
			default:
				fprintf(stderr, "Unknown socket error %d.\n", errno);
			}
			exit(1);
		}
		if(shc->cf_cmd == IPSEC_CLR_DEV) {
			fprintf(stderr, "%s: Socket ioctl failed on clear -- ", program_name);
			switch(errno)
			{
			case EINVAL:
				fprintf(stderr, "Invalid argument, check kernel log messages for specifics.\n");
				break;
			case ENODEV:
				fprintf(stderr, "Failed.  Is the ipsec module linked into the kernel or loaded as a module?.\n");
				break;
			default:
				fprintf(stderr, "Unknown socket error %d.\n", errno);
			}
			exit(1);
		}
	}
	exit(0);
}
Example #7
0
/*
 * Function             - st_process_alsa_test_options
 * Functionality        - This function parses the command line options and values passed for the options
 * Input Params         -  argc,argv
 * Return Value         -  None
 * Note                 -  None
 */
static void st_process_alsa_test_options(int argc, char **argv)
{
	for (;;) {
		int option_index = 0;

		/*
		 * Options for getopt - New test case options added need to be
		 * populated here
		 */
		static struct option long_options[] = {
			{"access", required_argument, NULL, OPTION_ACCESS},
			{"channel", required_argument, NULL, OPTION_CHANNEL},
			{"device", required_argument, NULL, OPTION_DEVICE},
			{"format", required_argument, NULL, OPTION_FORMAT},
			{"file", required_argument, NULL, OPTION_FILE},
			{"periodsize", required_argument, NULL,
			 OPTION_PERIODSIZE},
			{"totalsize", required_argument, NULL,
			 OPTION_TOTALSIZE},
			{"rate", required_argument, NULL, OPTION_RATE},
			{"playback", required_argument, NULL, OPTION_PLAYBACK},
			{"record", required_argument, NULL, OPTION_RECORD},
			{"loopback", no_argument, NULL, OPTION_LOOPBACK},
			{"nonblock", no_argument, NULL, OPTION_NONBLOCK},
			{"performance", optional_argument, NULL,
			 OPTION_PERFORMANCE},
			{"id", required_argument, NULL, OPTION_TESTCASE_ID},
			{"version", no_argument, NULL, OPTION_VERSION},
			{"help", no_argument, NULL, OPTION_HELP},
			{NULL, 0, NULL, 0}
		};
		int c = getopt_long_only(argc, argv, "vh", long_options,
					 &option_index);
		if (c == -1) {
			break;
		}
		if (c == '?') {
			quit = TRUE;
			break;
		}
		switch (c) {
		case OPTION_ACCESS:
			if (optarg != NULL) {
				testoptions_capture.access_type = atoi(optarg);
				testoptions_playback.access_type = atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.access_type =
				    atoi(argv[optind]);
				testoptions_playback.access_type = atoi(optarg);
			}
			break;
		case OPTION_CHANNEL:
			if (optarg != NULL) {
				testoptions_capture.channel = atoi(optarg);
				testoptions_playback.channel = atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.channel =
				    atoi(argv[optind]);
				testoptions_playback.channel =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_DEVICE:
			if (optarg != NULL) {
				testoptions_capture.card_name = optarg;
				testoptions_playback.card_name = optarg;
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.card_name = argv[optind];
				testoptions_playback.card_name = argv[optind];
			}
			break;
		case OPTION_FORMAT:
			if (optarg != NULL) {
				testoptions_capture.format = atoi(optarg);
				testoptions_playback.format = atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.format = atoi(argv[optind]);
				testoptions_playback.format =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_FILE:
			if (optarg != NULL) {
				testoptions_capture.file_name = optarg;
				testoptions_playback.file_name = optarg;
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.file_name = argv[optind];
				testoptions_playback.file_name = argv[optind];
			}
			break;
		case OPTION_NONBLOCK:
			if (NULL != optarg) {
				testoptions_capture.io_opmode = NON_BLOCKING;
				testoptions_playback.io_opmode = NON_BLOCKING;
			} else if (optind < argc && argv[optind]) {
				testoptions_capture.io_opmode = NON_BLOCKING;
				testoptions_playback.io_opmode = NON_BLOCKING;
			}
			break;
		case OPTION_PERIODSIZE:
			if (optarg != NULL) {
				testoptions_capture.period_size = atoi(optarg);
				testoptions_playback.period_size = atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.period_size =
				    atoi(argv[optind]);
				testoptions_playback.period_size =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_TOTALSIZE:
			if (optarg != NULL) {
				testoptions_capture.total_size = atoi(optarg);
				testoptions_playback.total_size = atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.total_size =
				    atoi(argv[optind]);
				testoptions_playback.total_size =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_RATE:
			if (optarg != NULL) {
				testoptions_capture.sampling_rate =
				    atoi(optarg);
				testoptions_playback.sampling_rate =
				    atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.sampling_rate =
				    atoi(argv[optind]);
				testoptions_playback.sampling_rate =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_HELP:
			st_alsa_test_suite_help();
			quit = TRUE;
		case OPTION_VERSION:
			quit = TRUE;
			st_display_alsa_testsuite_version();
			break;
		case OPTION_PLAYBACK:
			error = FALSE;
			play_or_record = OPTION_PLAYBACK;
			if (optarg != NULL) {
				testoptions_playback.play_from_file =
				    atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_playback.play_from_file =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_RECORD:
			error = FALSE;
			play_or_record = OPTION_RECORD;
			if (optarg != NULL) {
				testoptions_capture.capture_to_file =
				    atoi(optarg);
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testoptions_capture.capture_to_file =
				    atoi(argv[optind]);
			}
			break;
		case OPTION_PERFORMANCE:
			testoptions_playback.throughput_flag = TRUE;
			testoptions_playback.cpuload_flag = TRUE;
			testoptions_capture.throughput_flag = TRUE;
			testoptions_capture.cpuload_flag = TRUE;
			if (optarg != NULL) {
				if (strcmp(optarg, THROUGHPUT) == 0) {
					testoptions_playback.throughput_flag =
					    TRUE;
					testoptions_playback.cpuload_flag =
					    FALSE;
					testoptions_capture.throughput_flag =
					    TRUE;
					testoptions_capture.cpuload_flag =
					    FALSE;
				} else if (strcmp(optarg, CPULOAD) == 0) {
					testoptions_playback.throughput_flag =
					    FALSE;
					testoptions_playback.cpuload_flag =
					    TRUE;
					testoptions_capture.throughput_flag =
					    FALSE;
					testoptions_capture.cpuload_flag = TRUE;
				}
			} else if (optind < argc && ('-' != argv[optind][0])) {
				if (strcmp(argv[optind], THROUGHPUT) == 0) {
					testoptions_playback.throughput_flag =
					    TRUE;
					testoptions_playback.cpuload_flag =
					    FALSE;
					testoptions_capture.throughput_flag =
					    TRUE;
					testoptions_capture.cpuload_flag =
					    FALSE;
				} else if (strcmp(argv[optind], CPULOAD) == 0) {
					testoptions_playback.throughput_flag =
					    FALSE;
					testoptions_playback.cpuload_flag =
					    TRUE;
					testoptions_capture.throughput_flag =
					    FALSE;
					testoptions_capture.cpuload_flag = TRUE;
				}
			}
			break;
		case OPTION_TESTCASE_ID:
			if (optarg != NULL) {
				testcaseid = optarg;
			} else if (optind < argc && ('-' != argv[optind][0])) {
				testcaseid = argv[optind];
			}
			break;
		}
	}
}
ExitStatus readArgs(int argc, char * const * argv, KextstatArgs * toolArgs)
{
    ExitStatus   result        = EX_USAGE;
    CFStringRef  scratchString = NULL;  // must release
    int          optChar       = 0;
    
    bzero(toolArgs, sizeof(*toolArgs));

   /*****
    * Allocate collection objects needed for command line argument processing.
    */
    if (!createCFMutableArray(&toolArgs->bundleIDs, &kCFTypeArrayCallBacks)) {
        goto finish;
    }

   /*****
    * Process command-line arguments.
    */
    result = EX_USAGE;

    while ((optChar = getopt_long_only(argc, argv, kOptChars,
        sOptInfo, NULL)) != -1) {

        SAFE_RELEASE_NULL(scratchString);

        switch (optChar) {

            case kOptHelp:
                usage(kUsageLevelFull);
                result = kKextstatExitHelp;
                goto finish;
                break;

            case kOptNoKernelComponents:
                toolArgs->flagNoKernelComponents = true;
                break;

            case kOptListOnly:
                toolArgs->flagListOnly = true;
                break;

            case kOptBundleIdentifier:
                scratchString = CFStringCreateWithCString(kCFAllocatorDefault,
                    optarg, kCFStringEncodingUTF8);
                if (!scratchString) {
                    OSKextLogMemError();
                    result = EX_OSERR;
                    goto finish;
                }
                CFArrayAppendValue(toolArgs->bundleIDs, scratchString);
                break;
            
            case kOptArchitecture:
                toolArgs->flagShowArchitecture = true;
                break;
                
            }
    }

    argc -= optind;
    argv += optind;

    if (argc) {
        OSKextLog(/* kext */ NULL,
            kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
            "Extra arguments starting at %s....", argv[0]);
        usage(kUsageLevelBrief);
        goto finish;
    }

    result = EX_OK;

finish:
    SAFE_RELEASE_NULL(scratchString);

    if (result == EX_USAGE) {
        usage(kUsageLevelBrief);
    }
    return result;
}
Example #9
0
int
main (int argc, string *argv)
{
    int getopt_return_val;
    int option_index = 0;

    name_program = xbasename(argv[0]);
    if (!strcmp(name_program, "ofm2opl") ||
        !strcmp(name_program, "OFM2OPL.EXE")) {
        program = PROG_OFM2OPL;
        name_help = OFM2OPLHELP;
	name_program = "ofm2opl";
        name_msg = "This is ofm2opl, Version 2.0";
        no_files = 2;
        files[0] = &name_ofm;
        files[1] = &name_opl;
        suffixes[0] = "ofm";
        suffixes[1] = "opl";
        full_suffixes[0] = ".ofm";
        full_suffixes[1] = ".opl";
    } else if (!strcmp(name_program, "opl2ofm") ||
               !strcmp(name_program, "OPL2OFM.EXE")) {
        program = PROG_OPL2OFM;
        name_help = OPL2OFMHELP;
	name_program = "opl2ofm";
        name_msg = "This is opl2ofm, Version 2.0";
        no_files = 2;
        files[0] = &name_opl;
        files[1] = &name_ofm;
        suffixes[0] = "opl";
        suffixes[1] = "ofm";
        full_suffixes[0] = ".opl";
        full_suffixes[1] = ".ofm";
    } else if (!strcmp(name_program, "ovp2ovf") ||
               !strcmp(name_program, "OVP2OVF.EXE")) {
        program = PROG_OVP2OVF;
        name_help = OVP2OVFHELP;
	name_program = "ovp2ovf";
        name_msg = "This is ovp2ovf, Version 2.0";
        no_files = 3;
        files[0] = &name_ovp;
        files[1] = &name_ovf;
        files[2] = &name_ofm;
        suffixes[0] = "ovp";
        suffixes[1] = "ovf";
        suffixes[2] = "ofm";
        full_suffixes[0] = ".ovp";
        full_suffixes[1] = ".ovf";
        full_suffixes[2] = ".ofm";
    } else if (!strcmp(name_program, "ovf2ovp") ||
               !strcmp(name_program, "OVF2OVP.EXE")) {
        program = PROG_OVF2OVP;
        name_help = OVF2OVPHELP;
	name_program = "ovf2ovp";
        name_msg = "This is ovf2ovp, Version 2.0";
        no_files = 3;
        files[0] = &name_ovf;
        files[1] = &name_ofm;
        files[2] = &name_ovp;
        suffixes[0] = "ovf";
        suffixes[1] = "ofm";
        suffixes[2] = "ovp";
        full_suffixes[0] = ".ovf";
        full_suffixes[1] = ".ofm";
        full_suffixes[2] = ".ovp";
    } else {
        fprintf(stderr , "Unrecognized program: %s\n", name_program);
        fprintf(stderr ,
        "This binary supports ofm2opl, opl2ofm, ovf2ovp, and ovp2ovf\n");
        exit(1);
    }
    kpse_set_program_name(name_program, NULL);
    kpse_init_prog(uppercasify(name_program), 0, nil, nil);

    do {
        getopt_return_val =
        getopt_long_only(argc, argv, "", long_options, &option_index) ;
        if (getopt_return_val == -1) { ; }
        else if ( getopt_return_val == 63 ) {
            usage (name_program);
        } else if (!strcmp(long_options[option_index].name, "help")) {
            usagehelp (name_help, NULL);
        } else if (!strcmp(long_options[option_index ].name, "version")) {
            printversionandexit(name_msg, nil,
                "J. Plaice, Y. Haralambous, D.E. Knuth",
                nil);
        } else if (!strcmp(long_options[option_index ].name, "char-format")) {
            if (!strcmp(optarg, "ascii")) char_format = CHAR_CODE_ASCII;
            else if (!strcmp(optarg, "num")) char_format = CHAR_CODE_NUM;
            else warning_s("Bad character code format (%s)", optarg);
        } else if (!strcmp(long_options[option_index ].name, "num-format")) {
            if (!strcmp(optarg, "hex")) num_format = NUM_CODE_HEX;
            else if (!strcmp(optarg, "octal")) num_format = NUM_CODE_OCTAL;
            else warning_s("Bad number code format (%s)", optarg);
        } else if (!strcmp(long_options[option_index ].name, "text-format")) {
            if (!strcmp(optarg, "upper")) text_format = TEXT_CODE_UPPER;
            else if (!strcmp(optarg, "mixed")) text_format = TEXT_CODE_MIXED;
            else warning_s("Bad text code format (%s)", optarg);
        }
    } while (getopt_return_val != -1);
    if (((argc-optind) > no_files) || ((argc-optind) < 1)) {
        fprintf(stderr , "%s: %s\n", name_program,
                no_files == 2 ? "Need one or two file arguments."
                              : "Need one to three file arguments.");
        usage (name_program);
    }
    *(files[0]) = extend_filename(cmdline(optind) , suffixes[0]);
    if (optind+2 <= argc) {
        *(files[1]) = extend_filename(cmdline(optind+1) , suffixes[1]);
        if (no_files == 3) {
            if (optind+3 <= argc) {
                *(files[2]) = extend_filename(cmdline(optind+2) , suffixes[2]);
            } else if (program == PROG_OVP2OVF) {
                *(files[2]) = extend_filename(cmdline(optind+1), suffixes[2]);
            }
        }
    } else if (program != PROG_OFM2OPL) {
        *(files[1]) = basenamechangesuffix(*(files[0]),
                      full_suffixes[0], full_suffixes[1]);
        if ((no_files == 3) && (program == PROG_OVP2OVF)) {
            *(files[2]) = basenamechangesuffix(*(files[0]),
                      full_suffixes[0], full_suffixes[2]);
        }
    }

    switch(program) {
        case PROG_OFM2OPL: {
            file_ofm = kpse_open_file(name_ofm, kpse_ofm_format);
            read_in_whole(&ofm, &length_ofm, file_ofm, name_ofm);
            (void)fclose(file_ofm);
            if (name_opl==NULL) file_opl = stdout;
            else rewrite(file_opl, name_opl);
            file_output = file_opl;
            parse_ofm(FALSE);
            break;
        }
        case PROG_OVF2OVP: {
            file_ovf = kpse_open_file(name_ovf, kpse_ovf_format);
            read_in_whole(&ovf, &length_ovf, file_ovf, name_ovf);
            (void)fclose(file_ovf);
            file_ofm = kpse_open_file(name_ofm, kpse_ofm_format);
            read_in_whole(&ofm, &length_ofm, file_ofm, name_ofm);
            (void)fclose(file_ofm);
            if (name_ovp==NULL) file_ovp = stdout;
            else rewrite(file_ovp, name_ovp);
            file_output = file_ovp;
            parse_ofm(TRUE);
            break;
        }
        case PROG_OPL2OFM: {
            file_opl = kpse_open_file(name_opl, kpse_opl_format);
            rewritebin(file_ofm, name_ofm);
            init_tables();
            yyin = file_opl;
            (void)yyparse();
            output_ofm_file();
            (void)fclose(file_ofm);
            break;
        }
        case PROG_OVP2OVF: {
            file_ovp = kpse_open_file(name_ovp, kpse_ovp_format);
            rewritebin(file_ovf, name_ovf);
            rewritebin(file_ofm, name_ofm);
            init_tables();
            yyin = file_ovp;
            (void)yyparse();
            output_ofm_file();
            /*(void)fclose(file_ofm);*/
            output_ovf_file();
            (void)fclose(file_ovf);
            break;
        }
        default: {exit(1);}
    }
    exit(0);
}
Example #10
0
void parseParameters(int argc, char *argv[]){
   // Help message:
   std::string help = "Usage: xooky_nabox [-version] [-help] <file>\n\n";

   // Get the flag values and store.
   int showVersion = 0;
   int showHelp = 0;
   const struct option long_options[] = {
			{"version", no_argument, &showVersion, 1},
			{"help", no_argument, &showHelp, 1},
			{ NULL, no_argument, NULL, 0 }
   };
   int option_index;
   int c;
   while((c = getopt_long_only(argc, argv, "i:o:r:b:", long_options, &option_index)) != -1){
      switch (c){
         case '0':
            // One of the flags was entered, nothing to do.
         break;
         default:
         break;
      }
   }

   // If no params
   if(argc<=1){
      std::cout << help;
      exit(1);
   }

   #ifdef DEBUG
   std::cout << "showVersion: " << showVersion << std::endl;
   std::cout << "showHelp: " << showHelp << std::endl;
   std::cout << "file: " << argv[argc-1] << std::endl << std::endl;
   #endif

   if(showHelp == 1){
      std::cout << help;
      exit(0);
   }

   if(showVersion == 1){
      std::cout << "XookyNabox version is " << XOOKY_VERSION << std::endl;
      std::cout << "LibPd version is " << LIB_PD_VERSION << std::endl;
      exit(0);
   }

   //Last argument must be a filename. Validate and store.
   char* arg_patch = argv[argc-1];
   std::ifstream patch_file(arg_patch);
   if(!patch_file.good()){
      std::cout << "The file " << arg_patch <<" is not valid.\n";
      std::cout << help;
      exit(1);		
   }
   char patch_path[1024];
   realpath(arg_patch, patch_path);
   std::string patch_path_str = std::string(patch_path);
   unsigned int pos = patch_path_str.find_last_of('/');
   directory = patch_path_str.substr(0,pos+1);
   filename = patch_path_str.substr(pos+1);
}
Example #11
0
ParseArgsStatus CApplication::ParseArguments(int argc, char *argv[])
{
    enum OptionType
    {
        OPT_HELP = 1,
        OPT_DEBUG,
        OPT_DATADIR,
        OPT_LOGLEVEL,
        OPT_LANGUAGE,
        OPT_LANGDIR,
        OPT_VBO
    };

    option options[] =
    {
        { "help", no_argument, nullptr, OPT_HELP },
        { "debug", no_argument, nullptr, OPT_DEBUG },
        { "datadir", required_argument, nullptr, OPT_DATADIR },
        { "loglevel", required_argument, nullptr, OPT_LOGLEVEL },
        { "language", required_argument, nullptr, OPT_LANGUAGE },
        { "langdir", required_argument, nullptr, OPT_LANGDIR },
        { "vbo", required_argument, nullptr, OPT_VBO }
    };

    opterr = 0;

    int c = 0;
    int index = -1;
    while ((c = getopt_long_only(argc, argv, "", options, &index)) != -1)
    {
        if (c == '?')
        {
            if (optopt == 0)
                GetLogger()->Error("Invalid argument: %s\n", argv[optind-1]);
            else
                GetLogger()->Error("Expected argument for option: %s\n", argv[optind-1]);

            m_exitCode = 1;
            return PARSE_ARGS_FAIL;
        }

        index = -1;

        switch (c)
        {
            case OPT_HELP:
            {
                GetLogger()->Message("\n");
                GetLogger()->Message("Colobot %s (%s)\n", COLOBOT_CODENAME, COLOBOT_VERSION);
                GetLogger()->Message("\n");
                GetLogger()->Message("List of available options:\n");
                GetLogger()->Message("  -help            this help\n");
                GetLogger()->Message("  -debug           enable debug mode (more info printed in logs)\n");
                GetLogger()->Message("  -datadir path    set custom data directory path\n");
                GetLogger()->Message("  -loglevel level  set log level to level (one of: trace, debug, info, warn, error, none)\n");
                GetLogger()->Message("  -language lang   set language (one of: en, de, fr, pl)\n");
                GetLogger()->Message("  -langdir path    set custom language directory path\n");
                GetLogger()->Message("  -vbo mode        set OpenGL VBO mode (one of: auto, enable, disable)\n");
                return PARSE_ARGS_HELP;
            }
            case OPT_DEBUG:
            {
                SetDebugMode(true);
                break;
            }
            case OPT_DATADIR:
            {
                m_dataPath = optarg;
                GetLogger()->Info("Using custom data dir: '%s'\n", m_dataPath.c_str());
                break;
            }
            case OPT_LOGLEVEL:
            {
                LogLevel logLevel;
                if (! CLogger::ParseLogLevel(optarg, logLevel))
                {
                    GetLogger()->Error("Invalid log level: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                GetLogger()->Message("[*****] Log level changed to %s\n", optarg);
                GetLogger()->SetLogLevel(logLevel);
                break;
            }
            case OPT_LANGUAGE:
            {
                Language language;
                if (! ParseLanguage(optarg, language))
                {
                    GetLogger()->Error("Invalid language: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                GetLogger()->Info("Using language %s\n", optarg);
                m_language = language;
                break;
            }
            case OPT_LANGDIR:
            {
                m_langPath = optarg;
                GetLogger()->Info("Using custom language dir: '%s'\n", m_langPath.c_str());
                break;
            }
            case OPT_VBO:
            {
                std::string vbo;
                vbo = optarg;
                if (vbo == "auto")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_AUTO;
                else if (vbo == "enable")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_ENABLE;
                else if (vbo == "disable")
                    m_deviceConfig.vboMode = Gfx::VBO_MODE_DISABLE;
                else
                {
                    GetLogger()->Error("Invalid vbo mode: \"%s\"\n", optarg);
                    return PARSE_ARGS_FAIL;
                }

                break;
            }
            default:
                assert(false); // should never get here
        }
    }

    return PARSE_ARGS_OK;
}
Example #12
0
int
main (int argc, char **argv)
{

  int frequency, oversample, stereo;
  struct song *song;
  int index;
  int c;
  int opt, error_flag;


  /* supposed to make wildcard expansion */
  _wildcard(&argc,&argv);

  signal (2, nextsong);
  signal (3, goodbye);

  printf("Tracker1 V0.91 for the SBOS2 package\n");

  /* Read environment variables */
  frequency = read_env ("FREQUENCY", 0);
  oversample = read_env ("OVERSAMPLE", 1);
  transpose = read_env ("TRANSPOSE", 0);

  if (getenv ("MONO"))
    pref.stereo = 0;
  else if (getenv ("STEREO"))
    pref.stereo = 1;
  else
    pref.stereo = DEFAULT_CHANNELS - 1;
  pref.type = BOTH;
  pref.repeats = 1;
  pref.speed = 50;
  pref.tolerate = 2;
  pref.verbose = 0;
  set_mix (DEFAULT_MIX);        /* 0 = full stereo, 100 = mono */

  error_flag = 0;
  while ((opt = getopt_long_only (argc, argv, "", long_options, NULL)) != EOF)
    {
      switch (opt)
        {
        case 'H':               /* help */
          error_flag++;
          break;
        case 'Q':               /* quiet */
          quiet++;
          break;
        case 'P':               /* abort on faults (be picky) */
          pref.tolerate = 0;
          break;
        case 'N':               /* new tracker type */
          pref.type = NEW;
          break;
        case 'O':               /* old tracker type */
          pref.type = OLD;
          break;
        case 'B':               /* both tracker types */
          pref.type = BOTH;
          break;
        case 'M':               /* mono */
          pref.stereo = 0;
          break;
        case 'S':               /* stereo */
          pref.stereo = 1;
          break;
        case 'V':
          pref.verbose = 1;
          break;
        case 'f':               /* frequency */
          frequency = atoi (optarg);
          break;
        case 'o':               /* oversampling */
          oversample = atoi (optarg);
          break;
        case 't':               /* transpose half-steps*/
          transpose = atoi (optarg);
          break;
        case 'r':               /* number of repeats */
          pref.repeats = atoi (optarg);
          break;
        case 's':               /* speed */
          pref.speed = atoi (optarg);
          break;
        case 'm':               /* % of channel mix.  100=mono */
          set_mix (atoi (optarg));
          break;
        default:                /* ??? */
          error_flag++;
          break;
        }
    }
  if (error_flag || !argv[optind])
    {
      fprintf (stderr, "Usage: %s " USAGE, argv[0]);
      exit(1);
    }

  frequency = open_audio (frequency);
  init_player (oversample, frequency);

  while (argv[optind])
    {
      switch (pref.type)
        {
        case BOTH:
          song = do_read_song (argv[optind], NEW);
          if (!song)
            song = do_read_song (argv[optind], OLD);
          break;
        case OLD:
          song = do_read_song (argv[optind], pref.type);
          break;
        case NEW:
          /* this is explicitly flagged as a new module,
           * so we don't need to look for a signature.
           */
          song = do_read_song (argv[optind], NEW_NO_CHECK);
          break;
        }
      optind++;
      if (song == NULL)
        continue;

      dump_song (song);
      play_song (song, &pref);
      release_song (song);

      /* flush out anything remaining in DMA buffers */
      flush_DMA_buffers();

    }

  close_audio ();
  return 0;
}
ExitStatus readArgs(
    int            * argc,
    char * const  ** argv,
    KcgenArgs  * toolArgs)
{
    ExitStatus   result         = EX_USAGE;
    ExitStatus   scratchResult  = EX_USAGE;
    CFStringRef  scratchString  = NULL;  // must release
    CFNumberRef  scratchNumber  = NULL;  // must release
    CFURLRef     scratchURL     = NULL;  // must release
    size_t       len            = 0;
    int32_t      i              = 0;
    int          optchar        = 0;
    int          longindex      = -1;

    bzero(toolArgs, sizeof(*toolArgs));
    
   /*****
    * Allocate collection objects.
    */
    if (!createCFMutableSet(&toolArgs->kextIDs, &kCFTypeSetCallBacks)             ||
        !createCFMutableSet(&toolArgs->optionalKextIDs, &kCFTypeSetCallBacks)     ||
        !createCFMutableArray(&toolArgs->argURLs, &kCFTypeArrayCallBacks)         ||
        !createCFMutableArray(&toolArgs->repositoryURLs, &kCFTypeArrayCallBacks)  ||
        !createCFMutableArray(&toolArgs->namedKextURLs, &kCFTypeArrayCallBacks)   ||
        !createCFMutableArray(&toolArgs->targetArchs, NULL)) {

        OSKextLogMemError();
        result = EX_OSERR;
        exit(result);
    }

    /*****
    * Process command line arguments.
    */
    while ((optchar = getopt_long_only(*argc, *argv,
        kOptChars, sOptInfo, &longindex)) != -1) {

        SAFE_RELEASE_NULL(scratchString);
        SAFE_RELEASE_NULL(scratchNumber);
        SAFE_RELEASE_NULL(scratchURL);

        /* When processing short (single-char) options, there is no way to
         * express optional arguments.  Instead, we suppress missing option
         * argument errors by adding a leading ':' to the option string.
         * When getopt detects a missing argument, it will return a ':' so that
         * we can screen for options that are not required to have an argument.
         */
        if (optchar == ':') {
            switch (optopt) {
                case kOptPrelinkedKernel:
                    optchar = optopt;
                    break;
                default:
                    OSKextLog(/* kext */ NULL,
                        kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
                        "Error - option requires an argument -- -%c.", 
                        optopt);
                    break;
            }
        }

        switch (optchar) {
  
            case kOptArch:
                if (!addArchForName(toolArgs, optarg)) {
                    OSKextLog(/* kext */ NULL,
                        kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
                        "Error - unknown architecture %s.", optarg);
                    goto finish;
                }
                break;
  
            case kOptBundleIdentifier:
                scratchString = CFStringCreateWithCString(kCFAllocatorDefault,
                   optarg, kCFStringEncodingUTF8);
                if (!scratchString) {
                    OSKextLogMemError();
                    result = EX_OSERR;
                    goto finish;
                }
                CFSetAddValue(toolArgs->kextIDs, scratchString);
                break;
  
            case kOptPrelinkedKernel:
                scratchResult = readPrelinkedKernelArgs(toolArgs, *argc, *argv,
                    /* isLongopt */ longindex != -1);
                if (scratchResult != EX_OK) {
                    result = scratchResult;
                    goto finish;
                }
                break;
  
            case kOptHelp:
                usage(kUsageLevelFull);
                result = kKcgenExitHelp;
                goto finish;
    
            case kOptKernel:
                if (toolArgs->kernelPath) {
                    OSKextLog(/* kext */ NULL,
                        kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                        "Warning - kernel file already specified; using last.");
                } else {
                    toolArgs->kernelPath = malloc(PATH_MAX);
                    if (!toolArgs->kernelPath) {
                        OSKextLogMemError();
                        result = EX_OSERR;
                        goto finish;
                    }
                }

                len = strlcpy(toolArgs->kernelPath, optarg, PATH_MAX);
                if (len >= PATH_MAX) {
                    OSKextLog(/* kext */ NULL,
                        kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
                        "Error - kernel filename length exceeds PATH_MAX");
                    goto finish;
                }
                break;
    
            case kOptTests:
                toolArgs->printTestResults = true;
                break;
  
            case kOptQuiet:
                beQuiet();
                break;

            case kOptVerbose:
                scratchResult = setLogFilterForOpt(*argc, *argv,
                    /* forceOnFlags */ kOSKextLogKextOrGlobalMask);
                if (scratchResult != EX_OK) {
                    result = scratchResult;
                    goto finish;
                }
                break;

            case kOptNoAuthentication:
                OSKextLog(/* kext */ NULL,
                    kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                    "Note: -%s is implicitly set for %s.", kOptNameNoAuthentication, progname);
                break;

            case 0:
                switch (longopt) {
                    case kLongOptOptionalBundleIdentifier:
                        scratchString = CFStringCreateWithCString(kCFAllocatorDefault,
                           optarg, kCFStringEncodingUTF8);
                        if (!scratchString) {
                            OSKextLogMemError();
                            result = EX_OSERR;
                            goto finish;
                        }
                        CFSetAddValue(toolArgs->optionalKextIDs, scratchString);
                        break;
          
                    case kLongOptCompressed:
                        toolArgs->compress = true;
                        break;

                    case kLongOptUncompressed:
                        toolArgs->uncompress = true;
                        break;

                    case kLongOptSymbols:
                        if (toolArgs->symbolDirURL) {
                            OSKextLog(/* kext */ NULL,
                                kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                                "Warning - symbol directory already specified; using last.");
                            SAFE_RELEASE_NULL(toolArgs->symbolDirURL);
                        }

                        scratchURL = CFURLCreateFromFileSystemRepresentation(
                            kCFAllocatorDefault,
                            (const UInt8 *)optarg, strlen(optarg), true);
                        if (!scratchURL) {
                            OSKextLogStringError(/* kext */ NULL);
                            result = EX_OSERR;
                            goto finish;
                        }

                        toolArgs->symbolDirURL = CFRetain(scratchURL);
                        toolArgs->generatePrelinkedSymbols = true;
                        break;

                    case kLongOptVolumeRoot:
                        if (toolArgs->volumeRootURL) {
                            OSKextLog(/* kext */ NULL,
                                kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                                "Warning: volume root already specified; using last.");
                            SAFE_RELEASE_NULL(toolArgs->volumeRootURL);
                        }

                        scratchURL = CFURLCreateFromFileSystemRepresentation(
                            kCFAllocatorDefault,
                            (const UInt8 *)optarg, strlen(optarg), true);
                        if (!scratchURL) {
                            OSKextLogStringError(/* kext */ NULL);
                            result = EX_OSERR;
                            goto finish;
                        }

                        toolArgs->volumeRootURL = CFRetain(scratchURL);
                        break;

                    case kLongOptAllPersonalities:
                        OSKextLog(/* kext */ NULL,
                            kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                            "Note: -%s is implicitly set for %s.", kOptNameAllPersonalities, progname);
                        break;

                    case kLongOptNoLinkFailures:
                        OSKextLog(/* kext */ NULL,
                            kOSKextLogWarningLevel | kOSKextLogGeneralFlag,
                            "Note: -%s is implicitly set for %s.", kOptNameNoLinkFailures, progname);
                        break;

                    case kLongOptStripSymbols:
                        toolArgs->stripSymbols = true;
                        break;

                    case kLongOptMaxSliceSize:
                        toolArgs->maxSliceSize = atol(optarg);
                        break;

                    default:
                       /* Because we use ':', getopt_long doesn't print an error message.
                        */
                        OSKextLog(/* kext */ NULL,
                            kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
                            "Error - unrecognized option %s", (*argv)[optind-1]);
                        goto finish;
                        break;
                }
                break;

            default:
               /* Because we use ':', getopt_long doesn't print an error message.
                */
                OSKextLog(/* kext */ NULL,
                    kOSKextLogErrorLevel | kOSKextLogGeneralFlag,
                    "Error - unrecognized option %s", (*argv)[optind-1]);
                goto finish;
                break;

        }
        
       /* Reset longindex, because getopt_long_only() is stupid and doesn't.
        */
        longindex = -1;
    }

   /* Update the argc & argv seen by main().
    */
    *argc -= optind;
    *argv += optind;

   /*
    * Record the kext & directory names from the command line.
    */
    for (i = 0; i < *argc; i++) {
        SAFE_RELEASE_NULL(scratchURL);
        SAFE_RELEASE_NULL(scratchString);

        scratchURL = CFURLCreateFromFileSystemRepresentation(
            kCFAllocatorDefault,
            (const UInt8 *)(*argv)[i], strlen((*argv)[i]), true);
        if (!scratchURL) {
            OSKextLogMemError();
            result = EX_OSERR;
            goto finish;
        }
        CFArrayAppendValue(toolArgs->argURLs, scratchURL);

        scratchString = CFURLCopyPathExtension(scratchURL);
        if (scratchString && CFEqual(scratchString, CFSTR("kext"))) {
            CFArrayAppendValue(toolArgs->namedKextURLs, scratchURL);
        } else {
            CFArrayAppendValue(toolArgs->repositoryURLs, scratchURL);
        }
    }

    result = EX_OK;

finish:
    SAFE_RELEASE(scratchString);
    SAFE_RELEASE(scratchNumber);
    SAFE_RELEASE(scratchURL);

    if (result == EX_USAGE) {
        usage(kUsageLevelBrief);
    }
    return result;
}
Example #14
0
int main(int argc, char **argv) {
  int c, i;
  struct emitter_config emitter_config;
  struct option *getopt_options = NULL;

  struct kv *extra_fields = NULL;
  size_t extra_fields_len = 0;

  /* defaults */
  memset(&emitter_config, 0, sizeof(struct emitter_config));
  emitter_config.port = 5001;
  emitter_config.window_size = 4096;
  
  /* convert the 'option_doc' array into a 'struct option' array 
   * for use with getopt_long_only */
  for (i = 0; options[i].name != NULL; i++) {
    getopt_options = realloc(getopt_options, (i+1) * sizeof(struct option));
    getopt_options[i].name = options[i].name;
    getopt_options[i].has_arg = options[i].has_arg;
    getopt_options[i].flag = NULL;
    getopt_options[i].val = options[i].val;
  }

  /* Add one last item for the list terminator NULL */
  getopt_options = realloc(getopt_options, (i+1) * sizeof(struct option));
  getopt_options[i].name = NULL;

  char *tmp;
  while (i = -1, c = getopt_long_only(argc, argv, "+hv", getopt_options, &i), c != -1) {
    /* TODO(sissel): handle args */
    switch (c) {
      case opt_ssl_ca_path:
        emitter_config.ssl_ca_path = strdup(optarg);
        break;
      case opt_version:
        printf("version unknown. Could be awesome.\n");
        break;
      case opt_help:
        usage(argv[0]);
        return 0;
      case opt_host:
        emitter_config.host = strdup(optarg);
        break;
      case opt_port:
        emitter_config.port = (unsigned short)atoi(optarg);
        break;
      case opt_window_size:
        emitter_config.window_size = (size_t)atoi(optarg);
        printf("size: %d\n", (int)emitter_config.window_size);
        break;
      case opt_field:
        tmp = strchr(optarg, '=');
        if (tmp == NULL) {
          printf("Invalid --field setting, expected 'foo=bar' form, " \
                 "didn't see '=' in '%s'", optarg);
          usage(argv[0]);
          exit(1);
        }
        extra_fields_len += 1;
        extra_fields = realloc(extra_fields, extra_fields_len * sizeof(struct kv));
        *tmp = '\0'; // turn '=' into null terminator
        tmp++; /* skip to first char of value */
        extra_fields[extra_fields_len - 1].key = strdup(optarg);
        extra_fields[extra_fields_len - 1].key_len = strlen(optarg);
        extra_fields[extra_fields_len - 1].value = strdup(tmp);
        extra_fields[extra_fields_len - 1].value_len = strlen(tmp);
        break;
      default:
        insist(i == -1, "Flag (--%s%s%s) known, but someone forgot to " \
               "implement handling of it! This is certainly a bug.",
               options[i].name, 
               options[i].has_arg ? " " : "",
               options[i].has_arg ? optarg : "");

        usage(argv[0]);
        return 1;
    }
  }
  free(getopt_options);

  if (emitter_config.host == NULL) {
    printf("Missing --host flag\n");
    usage(argv[0]);
    return 1;
  }

  if (emitter_config.port == 0) {
    printf("Missing --port flag\n");
    usage(argv[0]);
    return 1;
  }

  argc -= optind;
  argv += optind;

  /* I'll handle write failures; no signals please */
  signal(SIGPIPE, SIG_IGN);

  insist(argc > 0, "No arguments given. What log files do you want shipped?");

  /* Set resource (memory, open file, etc) limits based on the
   * number of files being watched. */
  set_resource_limits(argc);

  pthread_t *harvesters = calloc(argc, sizeof(pthread_t));
  /* no I/O threads needed since we use inproc:// only */
  void *zmq = zmq_init(0 /* IO threads */); 

  /* Start harvesters for each path given */
  for (i = 0; i < argc; i++) {
    struct harvest_config *harvester = calloc(1, sizeof(struct harvest_config));
    harvester->zmq = zmq;
    harvester->zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
    harvester->path = argv[i];
    harvester->fields = extra_fields;
    harvester->fields_len = extra_fields_len;
    pthread_create(&harvesters[i], NULL, harvest, harvester);
  }

  pthread_t emitter_thread;
  emitter_config.zmq = zmq;
  emitter_config.zmq_endpoint = ZMQ_EMITTER_ENDPOINT;
  pthread_create(&emitter_thread, NULL, emitter, &emitter_config);

  for (i = 0; i < argc; i++) {
    pthread_join(harvesters[i], NULL);
  }

  flog(stdout, "All harvesters completed. Exiting.");
  free(harvesters);

  /* TODO(sissel): Tell emitter to flush and exit */
  return 1;
} /* main */
Example #15
0
int ctx_vcfcov(int argc, char **argv)
{
  struct MemArgs memargs = MEM_ARGS_INIT;
  const char *out_path = NULL, *out_type = NULL;

  uint32_t max_allele_len = 0, max_gt_vars = 0;
  char *ref_path = NULL;
  bool low_mem = false;

  // Arg parsing
  char cmd[100];
  char shortopts[300];
  cmd_long_opts_to_short(longopts, shortopts, sizeof(shortopts));
  int c;
  size_t i;

  // silence error messages from getopt_long
  // opterr = 0;

  while((c = getopt_long_only(argc, argv, shortopts, longopts, NULL)) != -1) {
    cmd_get_longopt_str(longopts, c, cmd, sizeof(cmd));
    switch(c) {
      case 0: /* flag set */ break;
      case 'h': cmd_print_usage(NULL); break;
      case 'o': cmd_check(!out_path, cmd); out_path = optarg; break;
      case 'O': cmd_check(!out_type, cmd); out_type = optarg; break;
      case 'f': cmd_check(!futil_get_force(), cmd); futil_set_force(true); break;
      case 'm': cmd_mem_args_set_memory(&memargs, optarg); break;
      case 'n': cmd_mem_args_set_nkmers(&memargs, optarg); break;
      case 'r': cmd_check(!ref_path, cmd); ref_path = optarg; break;
      case 'L': cmd_check(!max_allele_len,cmd); max_allele_len = cmd_uint32(cmd,optarg); break;
      case 'N': cmd_check(!max_gt_vars,cmd); max_gt_vars = cmd_uint32(cmd,optarg); break;
      case 'M': cmd_check(!low_mem, cmd); low_mem = true; break;
      case ':': /* BADARG */
      case '?': /* BADCH getopt_long has already printed error */
        // cmd_print_usage(NULL);
        die("`"CMD" "SUBCMD" -h` for help. Bad option: %s", argv[optind-1]);
      default: abort();
    }
  }

  // Defaults for unset values
  if(out_path == NULL) out_path = "-";
  if(ref_path == NULL) cmd_print_usage("Require a reference (-r,--ref <ref.fa>)");
  if(optind+2 > argc) cmd_print_usage("Require VCF and graph files");

  if(!max_allele_len) max_allele_len = DEFAULT_MAX_ALLELE_LEN;
  if(!max_gt_vars) max_gt_vars = DEFAULT_MAX_GT_VARS;

  status("[vcfcov] max allele length: %u; max number of variants: %u",
         max_allele_len, max_gt_vars);

  // open ref
  // index fasta with: samtools faidx ref.fa
  faidx_t *fai = fai_load(ref_path);
  if(fai == NULL) die("Cannot load ref index: %s / %s.fai", ref_path, ref_path);

  // Open input VCF file
  const char *vcf_path = argv[optind++];
  htsFile *vcffh = hts_open(vcf_path, "r");
  if(vcffh == NULL) die("Cannot open VCF file: %s", vcf_path);
  bcf_hdr_t *vcfhdr = bcf_hdr_read(vcffh);
  if(vcfhdr == NULL) die("Cannot read VCF header: %s", vcf_path);

  // Test we can close and reopen files
  if(low_mem) {
    if((vcffh = hts_open(vcf_path, "r")) == NULL)
      die("Cannot re-open VCF file: %s", vcf_path);
    if((vcfhdr = bcf_hdr_read(vcffh)) == NULL)
      die("Cannot re-read VCF header: %s", vcf_path);
  }

  //
  // Open graph files
  //
  const size_t num_gfiles = argc - optind;
  char **graph_paths = argv + optind;
  ctx_assert(num_gfiles > 0);

  GraphFileReader *gfiles = ctx_calloc(num_gfiles, sizeof(GraphFileReader));
  size_t ncols, ctx_max_kmers = 0, ctx_sum_kmers = 0;

  ncols = graph_files_open(graph_paths, gfiles, num_gfiles,
                           &ctx_max_kmers, &ctx_sum_kmers);

  // Check graph + paths are compatible
  graphs_gpaths_compatible(gfiles, num_gfiles, NULL, 0, -1);

  //
  // Decide on memory
  //
  size_t bits_per_kmer, kmers_in_hash, graph_mem;

  bits_per_kmer = sizeof(BinaryKmer)*8 + sizeof(Covg)*8 * ncols;
  kmers_in_hash = cmd_get_kmers_in_hash(memargs.mem_to_use,
                                        memargs.mem_to_use_set,
                                        memargs.num_kmers,
                                        memargs.num_kmers_set,
                                        bits_per_kmer,
                                        low_mem ? -1 : (int64_t)ctx_max_kmers,
                                        ctx_sum_kmers,
                                        true, &graph_mem);

  cmd_check_mem_limit(memargs.mem_to_use, graph_mem);

  //
  // Open output file
  //
  // v=>vcf, z=>compressed vcf, b=>bcf, bu=>uncompressed bcf
  int mode = vcf_misc_get_outtype(out_type, out_path);
  futil_create_output(out_path);
  htsFile *outfh = hts_open(out_path, modes_htslib[mode]);
  status("[vcfcov] Output format: %s", hsmodes_htslib[mode]);


  // Allocate memory
  dBGraph db_graph;
  db_graph_alloc(&db_graph, gfiles[0].hdr.kmer_size, ncols, 1, kmers_in_hash,
                 DBG_ALLOC_COVGS);

  //
  // Set up tag names
  //

  // *R => ref, *A => alt
  sprintf(kcov_ref_tag, "K%zuR", db_graph.kmer_size); // mean coverage
  sprintf(kcov_alt_tag, "K%zuA", db_graph.kmer_size);

  // #SAMPLE=<ID=...,K29KCOV=...,K29NK=...,K29RLK>
  // - K29_kcov is empirical kmer coverage
  // - K29_nkmers is the number of kmers in the sample
  // - mean_read_length is the mean read length in bases
  char sample_kcov_tag[20], sample_nk_tag[20], sample_rlk_tag[20];
  sprintf(sample_kcov_tag, "K%zu_kcov", db_graph.kmer_size); // mean coverage
  sprintf(sample_nk_tag, "K%zu_nkmers", db_graph.kmer_size);
  sprintf(sample_rlk_tag, "mean_read_length");

  //
  // Load kmers if we are using --low-mem
  //

  VcfCovStats st;
  memset(&st, 0, sizeof(st));
  VcfCovPrefs prefs = {.kcov_ref_tag = kcov_ref_tag,
                       .kcov_alt_tag = kcov_alt_tag,
                       .max_allele_len = max_allele_len,
                       .max_gt_vars = max_gt_vars,
                       .load_kmers_only = false};

  if(low_mem)
  {
    status("[vcfcov] Loading kmers from VCF+ref");

    prefs.load_kmers_only = true;
    vcfcov_file(vcffh, vcfhdr, NULL, NULL, vcf_path, fai,
                NULL, &prefs, &st, &db_graph);

    // Close files
    hts_close(vcffh);
    bcf_hdr_destroy(vcfhdr);

    // Re-open files
    if((vcffh = hts_open(vcf_path, "r")) == NULL)
      die("Cannot re-open VCF file: %s", vcf_path);
    if((vcfhdr = bcf_hdr_read(vcffh)) == NULL)
      die("Cannot re-read VCF header: %s", vcf_path);

    prefs.load_kmers_only = false;
  }

  //
  // Load graphs
  //
  GraphLoadingStats gstats;
  memset(&gstats, 0, sizeof(gstats));

  GraphLoadingPrefs gprefs = graph_loading_prefs(&db_graph);
  gprefs.must_exist_in_graph = low_mem;

  for(i = 0; i < num_gfiles; i++) {
    graph_load(&gfiles[i], gprefs, &gstats);
    graph_file_close(&gfiles[i]);
  }
  ctx_free(gfiles);

  hash_table_print_stats(&db_graph.ht);

  //
  // Set up VCF header / graph matchup
  //
  size_t *samplehdrids = ctx_malloc(db_graph.num_of_cols * sizeof(size_t));

  // Add samples to vcf header
  bcf_hdr_t *outhdr = bcf_hdr_dup(vcfhdr);
  bcf_hrec_t *hrec;
  int sid;
  char hdrstr[200];

  for(i = 0; i < db_graph.num_of_cols; i++) {
    char *sname = db_graph.ginfo[i].sample_name.b;
    if((sid = bcf_hdr_id2int(outhdr, BCF_DT_SAMPLE, sname)) < 0) {
      bcf_hdr_add_sample(outhdr, sname);
      sid = bcf_hdr_id2int(outhdr, BCF_DT_SAMPLE, sname);
    }
    samplehdrids[i] = sid;

    // Add SAMPLE field
    hrec = bcf_hdr_get_hrec(outhdr, BCF_HL_STR, "ID", sname, "SAMPLE");

    if(hrec == NULL) {
      sprintf(hdrstr, "##SAMPLE=<ID=%s,%s=%"PRIu64",%s=%"PRIu64",%s=%zu>", sname,
              sample_kcov_tag,
              gstats.nkmers[i] ? gstats.sumcov[i] / gstats.nkmers[i] : 0,
              sample_nk_tag, gstats.nkmers[i],
              sample_rlk_tag, (size_t)db_graph.ginfo[i].mean_read_length);
      bcf_hdr_append(outhdr, hdrstr);
    }
    else {
      // mean kcovg
      sprintf(hdrstr, "%"PRIu64, gstats.sumcov[i] / gstats.nkmers[i]);
      vcf_misc_add_update_hrec(hrec, sample_kcov_tag, hdrstr);
      // num kmers
      sprintf(hdrstr, "%"PRIu64, gstats.nkmers[i]);
      vcf_misc_add_update_hrec(hrec, sample_nk_tag, hdrstr);
      // mean read length in kmers
      sprintf(hdrstr, "%zu", (size_t)db_graph.ginfo[i].mean_read_length);
      vcf_misc_add_update_hrec(hrec, sample_rlk_tag, hdrstr);
    }

    status("[vcfcov] Colour %zu: %s [VCF column %zu]", i, sname, samplehdrids[i]);
  }

  // Add genotype format fields
  // One field per alternative allele

  sprintf(hdrstr, "##FORMAT=<ID=%s,Number=A,Type=Integer,"
          "Description=\"Coverage on ref (k=%zu): sum(kmer_covs) / exp_num_kmers\">\n",
          kcov_ref_tag, db_graph.kmer_size);
  bcf_hdr_append(outhdr, hdrstr);
  sprintf(hdrstr, "##FORMAT=<ID=%s,Number=A,Type=Integer,"
          "Description=\"Coverage on alt (k=%zu): sum(kmer_covs) / exp_num_kmers\">\n",
          kcov_alt_tag, db_graph.kmer_size);
  bcf_hdr_append(outhdr, hdrstr);

  bcf_hdr_set_version(outhdr, "VCFv4.2");

  // Add command string to header
  vcf_misc_hdr_add_cmd(outhdr, cmd_get_cmdline(), cmd_get_cwd());

  if(bcf_hdr_write(outfh, outhdr) != 0)
    die("Cannot write header to: %s", futil_outpath_str(out_path));

  status("[vcfcov] Reading %s and adding coverage", vcf_path);

  // Reset stats and get coverage
  memset(&st, 0, sizeof(st));

  vcfcov_file(vcffh, vcfhdr, outfh, outhdr, vcf_path, fai,
              samplehdrids, &prefs, &st, &db_graph);

  // Print statistics
  char ns0[50], ns1[50];
  status("[vcfcov] Read %s VCF lines", ulong_to_str(st.nvcf_lines, ns0));
  status("[vcfcov] Read %s ALTs", ulong_to_str(st.nalts_read, ns0));
  status("[vcfcov] Used %s kmers", ulong_to_str(st.ngt_kmers, ns0));
  status("[vcfcov] ALTs used: %s / %s (%.2f%%)",
         ulong_to_str(st.nalts_loaded, ns0), ulong_to_str(st.nalts_read, ns1),
         st.nalts_read ? (100.0*st.nalts_loaded) / st.nalts_read : 0.0);
  status("[vcfcov] ALTs too long (>%ubp): %s / %s (%.2f%%)", max_allele_len,
         ulong_to_str(st.nalts_too_long, ns0), ulong_to_str(st.nalts_read, ns1),
         st.nalts_read ? (100.0*st.nalts_too_long) / st.nalts_read : 0.0);
  status("[vcfcov] ALTs too dense (>%u within %zubp): %s / %s (%.2f%%)",
         max_gt_vars, db_graph.kmer_size,
         ulong_to_str(st.nalts_no_covg, ns0), ulong_to_str(st.nalts_read, ns1),
         st.nalts_read ? (100.0*st.nalts_no_covg) / st.nalts_read : 0.0);
  status("[vcfcov] ALTs printed with coverage: %s / %s (%.2f%%)",
         ulong_to_str(st.nalts_with_covg, ns0), ulong_to_str(st.nalts_read, ns1),
         st.nalts_read ? (100.0*st.nalts_with_covg) / st.nalts_read : 0.0);

  status("[vcfcov] Saved to: %s\n", out_path);

  ctx_free(samplehdrids);
  graph_loading_stats_destroy(&gstats);

  bcf_hdr_destroy(vcfhdr);
  bcf_hdr_destroy(outhdr);
  hts_close(vcffh);
  hts_close(outfh);
  fai_destroy(fai);
  db_graph_dealloc(&db_graph);

  return EXIT_SUCCESS;
}
Example #16
0
int main(int argc, char* argv[])
{
  StringSet targets, configurations, schemes;
  String sdkRoot, projectPath, xcconfigPath, workspacePath;
  String logVerbosity("warning");
  int projectSet = 0;
  int workspaceSet = 0;
  int interactiveFlag = 0;
  int relativeSdkFlag = 0;
  int allTargets = 0;
  int allSchemes = 0;
  int mode = GenerateMode;


  static struct option long_options[] = {
    {"version", no_argument, 0, 0},
    {"usage", no_argument, 0, 0},
    {"help", no_argument, 0, 0},
    {"interactive", no_argument, &interactiveFlag, 1},
    {"loglevel", required_argument, 0, 0},
    {"sdk", required_argument, 0, 0},
    {"list", no_argument, &mode, ListMode},
    {"project", required_argument, &projectSet, 1},
    {"target", required_argument, 0, 0},
    {"alltargets", no_argument, &allTargets, 1},
    {"configuration", required_argument, 0, 0},
    {"xcconfig", required_argument, 0, 0},
    {"workspace", required_argument, &workspaceSet, 1},
    {"scheme", required_argument, 0, 0},
    {"allschemes", required_argument, &allSchemes, 1},
    {"relativepath", no_argument, &relativeSdkFlag, 1},
    {0, 0, 0, 0}
  };

  int numOptions = sizeof(long_options) / sizeof(struct option) - 1;
  while (1) {
    int option_index = 0;
    int c = getopt_long_only(argc, argv, "", long_options, &option_index);

    if (c == -1)
      break;
    else if (c || option_index < 0 || option_index >= numOptions)
      printUsage(argv[0], false, EXIT_FAILURE);

    // Process options
    switch (option_index) {
    case 0:
      printVersion(argv[0]);
      break;
    case 1:
      printUsage(argv[0], false, EXIT_SUCCESS);
      break;
    case 2:
      printUsage(argv[0], true, EXIT_SUCCESS);
      break;
    case 4:
      logVerbosity = strToLower(optarg);
      break;
    case 5:
      sdkRoot = optarg;
      break;
    case 7:
      projectPath = optarg;
      break;
    case 8:
      targets.insert(optarg);
      break;
    case 10:
      configurations.insert(optarg);
      break;
    case 11:
      xcconfigPath = optarg;
      break;
    case 12:
      workspacePath = optarg;
      break;
    case 13:
      schemes.insert(optarg);
      break;
    default:
      // Do nothing
      break;
    }
  }

  // Set AI Telemetry_Init 
  TELEMETRY_INIT(L"AIF-23c336e0-1e7e-43ba-a5ce-eb9dc8a06d34");

  if (checkTelemetryOptIn())
  {
      TELEMETRY_ENABLE();
  }
  else
  {
      TELEMETRY_DISABLE();
  }

  TELEMETRY_SET_INTERNAL(isMSFTInternalMachine());
  String machineID = getMachineID();
  if (!machineID.empty())
  {
      TELEMETRY_SET_MACHINEID(machineID.c_str());
  }

  TELEMETRY_EVENT_DATA(L"VSImporterStart", "WinStore10");

  // Process non-option ARGV-elements
  VariableCollectionManager& settingsManager = VariableCollectionManager::get();
  while (optind < argc) {
    String arg = argv[optind];
    if (arg == "/?") {
        // Due to issue 6715724, flush before exiting
		TELEMETRY_EVENT_DATA(L"VSImporterIncomplete", "printUsage");
		TELEMETRY_FLUSH();
        printUsage(argv[0], true, EXIT_SUCCESS);
    } else if (arg.find_first_of('=') != String::npos) {
      settingsManager.processGlobalAssignment(arg);
    } else {
		sbValidateWithTelemetry(0, "Unsupported argument: " + arg);
    }
    optind++;
  }

  // Set output format
  settingsManager.setGlobalVar("VSIMPORTER_OUTPUT_FORMAT", "WinStore10");

  // Set logging level
  SBLogLevel logLevel;
  if (logVerbosity == "debug")
    logLevel = SB_DEBUG;
  else if (logVerbosity == "info")
    logLevel = SB_INFO;
  else if (logVerbosity == "warning")
    logLevel = SB_WARN;
  else if (logVerbosity == "error")
    logLevel = SB_ERROR;
  else if (!logVerbosity.empty()) {
	  sbValidateWithTelemetry(0, "Unrecognized logging verbosity: " + logVerbosity);
  }
  SBLog::setVerbosity(logLevel);

  // Look for a project file in current directory, if one hasn't been explicitly specified 
  if (!projectSet && !workspaceSet) {
    StringList projects;
    findFiles(".", "*.xcodeproj", DT_DIR, false, projects);
    StringList workspaces;
    findFiles(".", "*.xcworkspace", DT_DIR, false, workspaces);

    if (!workspaces.empty()) {
      sbValidateWithTelemetry(workspaces.size() == 1, "Multiple workspaces found. Select the workspace to use with the -workspace option.");
      workspacePath = workspaces.front();
      workspaceSet = 1;
	}
	else if (!projects.empty()) {
		sbValidateWithTelemetry(projects.size() == 1, "Multiple projects found. Select the project to use with the -project option.");
		projectPath = projects.front();
		projectSet = 1;
	} else {
		sbValidateWithTelemetry(0, "The current directory does not contain a project or workspace.");
    }
  }

  // Set the architecture
  String arch = "msvc";
  settingsManager.setGlobalVar("ARCHS", arch);
  settingsManager.setGlobalVar("CURRENT_ARCH", arch);

  // Make sure workspace arguments are valid
  if (workspaceSet) {
	  sbValidateWithTelemetry(!projectSet, "Cannot specify both a project and a workspace.");
	sbValidateWithTelemetry(targets.empty(), "Cannot specify target(s) when specifying a workspace.");
  }

  // Disallow specifying schemes and targets together
  sbValidateWithTelemetry((schemes.empty() && !allSchemes) || (targets.empty() && !allTargets), "Cannot specify schemes and targets together.");

  // Process allTargets and allSchemes flags
  if (allSchemes)
    schemes.clear();
  if (allTargets)
    targets.clear();

  // Initialize global settings
  String binaryDir = sb_dirname(getBinaryLocation());
  sbValidateWithTelemetry(!binaryDir.empty(), "Failed to resolve binary directory.");
  settingsManager.setGlobalVar("VSIMPORTER_BINARY_DIR", binaryDir);
  settingsManager.setGlobalVar("VSIMPORTER_INTERACTIVE", interactiveFlag ? "YES" : "NO");
  settingsManager.setGlobalVar("VSIMPORTER_RELATIVE_SDK_PATH", relativeSdkFlag ? "YES" : "NO");
  if (!sdkRoot.empty()) {
    sdkRoot = joinPaths(getcwd(), sdkRoot);
  } else {
    sdkRoot = joinPaths(binaryDir, "..");
  }
  settingsManager.setGlobalVar("WINOBJC_SDK_ROOT", sdkRoot);

  // Add useful environment variables to global settings
  String username;
  sbValidateWithTelemetry(sb_getenv("USERNAME", username), "Failed to get current username.");
  settingsManager.setGlobalVar("USER", username);

  // Read xcconfig file specified from the command line
  if (!xcconfigPath.empty())
    settingsManager.processGlobalConfigFile(xcconfigPath);

  // Read xcconfig file specified by the XCODE_XCCONFIG_FILE environment variable
  String xcconfigFile;
  if (sb_getenv("XCODE_XCCONFIG_FILE", xcconfigFile))
    settingsManager.processGlobalConfigFile(xcconfigFile);

  // Validate WinObjC SDK directory
  checkWinObjCSDK();

  // Create a workspace
  SBWorkspace *mainWorkspace;
  if (workspaceSet) {
    mainWorkspace = SBWorkspace::createFromWorkspace(workspacePath);
  } else if (projectSet) {
    mainWorkspace = SBWorkspace::createFromProject(projectPath);
  } else {
	  sbAssertWithTelemetry(0); // non-reachable
  }

  if (mode == ListMode) {
    mainWorkspace->printSummary();
  } else if (mode == GenerateMode) {
    if (allTargets) {
      mainWorkspace->queueAllTargets(configurations);
    } else if (projectSet) {
      mainWorkspace->queueTargets(targets, configurations);
    } else if (workspaceSet) {
      mainWorkspace->queueSchemes(schemes, configurations);
    } else {
		sbAssertWithTelemetry(0); // non-reachable
    }
    mainWorkspace->generateFiles();
  } else {
	  sbAssertWithTelemetry(0); // non-reachable
  }

  TELEMETRY_EVENT_DATA(L"VSImporterComplete", "WinStore10");
  TELEMETRY_FLUSH();

  return EXIT_SUCCESS;
}
Example #17
0
File: bti.c Project: pferor/bti
int main(int argc, char *argv[], char *envp[])
{
	static const struct option options[] = {
		{ "debug", 0, NULL, 'd' },
		{ "verbose", 0, NULL, 'V' },
		{ "account", 1, NULL, 'a' },
		{ "password", 1, NULL, 'p' },
		{ "host", 1, NULL, 'H' },
		{ "proxy", 1, NULL, 'P' },
		{ "action", 1, NULL, 'A' },
		{ "user", 1, NULL, 'u' },
		{ "group", 1, NULL, 'G' },
		{ "logfile", 1, NULL, 'L' },
		{ "shrink-urls", 0, NULL, 's' },
		{ "help", 0, NULL, 'h' },
		{ "bash", 0, NULL, 'b' },
		{ "background", 0, NULL, 'B' },
		{ "dry-run", 0, NULL, 'n' },
		{ "page", 1, NULL, 'g' },
		{ "column", 1, NULL, 'o' },
		{ "version", 0, NULL, 'v' },
		{ "config", 1, NULL, 'c' },
		{ "replyto", 1, NULL, 'r' },
		{ "retweet", 1, NULL, 'w' },
		{ }
	};
    struct stat s;
	struct session *session;
	pid_t child;
	char *tweet;
	static char password[80];
	int retval = 0;
	int option;
	char *http_proxy;
	char *home;
	const char *config_file;
	time_t t;
	int page_nr;

	debug = 0;

	session = session_alloc();
	if (!session) {
		fprintf(stderr, "no more memory...\n");
		return -1;
	}

	/* get the current time so that we can log it later */
	time(&t);
	session->time = strdup(ctime(&t));
	session->time[strlen(session->time)-1] = 0x00;

	/*
	 * Get the home directory so we can try to find a config file.
	 * If we have no home dir set up, look in /etc/bti
	 */
	home = getenv("HOME");
	if (home) {
		/* We have a home dir, so this might be a user */
		session->homedir = strdup(home);

        /* if '.config/' exists, use XDG standard, else don't */
        if (-1 == stat("~/.config"), &s) {
            config_file = config_xdg_default;
        } else {
    		config_file = config_user_default;
        }
	} else {
		session->homedir = strdup("");
		config_file = config_default;
	}

	/* set up a default config file location (traditionally "~/.bti" or "~/.config/bti") */
	session->configfile = zalloc(strlen(session->homedir) + strlen(config_file) + 7);
	sprintf(session->configfile, "%s/%s", session->homedir, config_file);

	/* Set environment variables first, before reading command line options
	 * or config file values. */
	http_proxy = getenv("http_proxy");
	if (http_proxy) {
		if (session->proxy)
			free(session->proxy);
		session->proxy = strdup(http_proxy);
		dbg("http_proxy = %s\n", session->proxy);
	}

	bti_parse_configfile(session);

	while (1) {
		option = getopt_long_only(argc, argv,
					  "dp:P:H:a:A:u:c:hg:o:G:sr:nVvw:",
					  options, NULL);
		if (option == -1)
			break;
		switch (option) {
		case 'd':
			debug = 1;
			break;
		case 'V':
			session->verbose = 1;
			break;
		case 'a':
			if (session->account)
				free(session->account);
			session->account = strdup(optarg);
			dbg("account = %s\n", session->account);
			break;
		case 'g':
			page_nr = atoi(optarg);
			dbg("page = %d\n", page_nr);
			session->page = page_nr;
			break;
		case 'o':
			session->column_output = atoi(optarg);
			dbg("column_output = %d\n", session->column_output);
			break;
		case 'r':
			session->replyto = strdup(optarg);
			dbg("in_reply_to_status_id = %s\n", session->replyto);
			break;
		case 'w':
			session->retweet = strdup(optarg);
			dbg("Retweet ID = %s\n", session->retweet);
			break;
		case 'p':
			if (session->password)
				free(session->password);
			session->password = strdup(optarg);
			dbg("password = %s\n", session->password);
			break;
		case 'P':
			if (session->proxy)
				free(session->proxy);
			session->proxy = strdup(optarg);
			dbg("proxy = %s\n", session->proxy);
			break;
		case 'A':
			if (strcasecmp(optarg, "update") == 0)
				session->action = ACTION_UPDATE;
			else if (strcasecmp(optarg, "friends") == 0)
				session->action = ACTION_FRIENDS;
			else if (strcasecmp(optarg, "user") == 0)
				session->action = ACTION_USER;
			else if (strcasecmp(optarg, "replies") == 0)
				session->action = ACTION_REPLIES;
			else if (strcasecmp(optarg, "public") == 0)
				session->action = ACTION_PUBLIC;
			else if (strcasecmp(optarg, "group") == 0)
				session->action = ACTION_GROUP;
			else if (strcasecmp(optarg, "retweet") == 0)
				session->action = ACTION_RETWEET;
			else
				session->action = ACTION_UNKNOWN;
			dbg("action = %d\n", session->action);
			break;
		case 'u':
			if (session->user)
				free(session->user);
			session->user = strdup(optarg);
			dbg("user = %s\n", session->user);
			break;

		case 'G':
			if (session->group)
				free(session->group);
			session->group = strdup(optarg);
			dbg("group = %s\n", session->group);
			break;
		case 'L':
			if (session->logfile)
				free(session->logfile);
			session->logfile = strdup(optarg);
			dbg("logfile = %s\n", session->logfile);
			break;
		case 's':
			session->shrink_urls = 1;
			break;
		case 'H':
			if (session->hosturl)
				free(session->hosturl);
			if (session->hostname)
				free(session->hostname);
			if (strcasecmp(optarg, "twitter") == 0) {
				session->host = HOST_TWITTER;
				session->hosturl = strdup(twitter_host);
				session->hostname = strdup(twitter_name);
			} else if (strcasecmp(optarg, "identica") == 0) {
				session->host = HOST_IDENTICA;
				session->hosturl = strdup(identica_host);
				session->hostname = strdup(identica_name);
			} else {
				session->host = HOST_CUSTOM;
				session->hosturl = strdup(optarg);
				session->hostname = strdup(optarg);
			}
			dbg("host = %d\n", session->host);
			break;
		case 'b':
			session->bash = 1;
			/* fall-through intended */
		case 'B':
			session->background = 1;
			break;
		case 'c':
			if (session->configfile)
				free(session->configfile);
			session->configfile = strdup(optarg);
			dbg("configfile = %s\n", session->configfile);

			/*
			 * read the config file now.  Yes, this could override
			 * previously set options from the command line, but
			 * the user asked for it...
			 */
			bti_parse_configfile(session);
			break;
		case 'h':
			display_help();
			goto exit;
		case 'n':
			session->dry_run = 1;
			break;
		case 'v':
			display_version();
			goto exit;
		default:
			display_help();
			goto exit;
		}
	}

	session_readline_init(session);
	/*
	 * Show the version to make it easier to determine what
	 * is going on here
	 */
	if (debug)
		display_version();

	if (session->host == HOST_TWITTER) {
		if (!session->consumer_key || !session->consumer_secret) {
			if (session->action == ACTION_USER ||
					session->action == ACTION_PUBLIC) {
				/*
				 * Some actions may still work without
				 * authentication
				 */
				session->guest = 1;
			} else {
				fprintf(stderr,
						"Twitter no longer supports HTTP basic authentication.\n"
						"Both consumer key, and consumer secret are required"
						" for bti in order to behave as an OAuth consumer.\n");
				goto exit;
			}
		}
		if (session->action == ACTION_GROUP) {
			fprintf(stderr, "Groups only work in Identi.ca.\n");
			goto exit;
		}
	} else {
		if (!session->consumer_key || !session->consumer_secret)
			session->no_oauth = 1;
	}

	if (session->no_oauth) {
		if (!session->account) {
			fprintf(stdout, "Enter account for %s: ",
				session->hostname);
			session->account = session->readline(NULL);
		}
		if (!session->password) {
			read_password(password, sizeof(password),
				      session->hostname);
			session->password = strdup(password);
		}
	} else if (!session->guest) {
		if (!session->access_token_key ||
		    !session->access_token_secret) {
			request_access_token(session);
			goto exit;
		}
	}

	if (session->action == ACTION_UNKNOWN) {
		fprintf(stderr, "Unknown action, valid actions are:\n"
			"'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
		goto exit;
	}

	if (session->action == ACTION_GROUP && !session->group) {
		fprintf(stdout, "Enter group name: ");
		session->group = session->readline(NULL);
	}

	if (session->action == ACTION_RETWEET) {
		if (!session->retweet) {
			char *rtid;

			fprintf(stdout, "Status ID to retweet: ");
			rtid = get_string_from_stdin();
			session->retweet = zalloc(strlen(rtid) + 10);
			sprintf(session->retweet, "%s", rtid);
			free(rtid);
		}

		if (!session->retweet || strlen(session->retweet) == 0) {
			dbg("no retweet?\n");
			return -1;
		}

		dbg("retweet ID = %s\n", session->retweet);
	}

	if (session->action == ACTION_UPDATE) {
		if (session->background || !session->interactive)
			tweet = get_string_from_stdin();
		else
			tweet = session->readline("tweet: ");
		if (!tweet || strlen(tweet) == 0) {
			dbg("no tweet?\n");
			return -1;
		}

		if (session->shrink_urls)
			tweet = shrink_urls(tweet);

		session->tweet = zalloc(strlen(tweet) + 10);
		if (session->bash)
			sprintf(session->tweet, "%c %s",
				getuid() ? '$' : '#', tweet);
		else
			sprintf(session->tweet, "%s", tweet);

		free(tweet);
		dbg("tweet = %s\n", session->tweet);
	}

	if (session->page == 0)
		session->page = 1;
	dbg("config file = %s\n", session->configfile);
	dbg("host = %d\n", session->host);
	dbg("action = %d\n", session->action);

	/* fork ourself so that the main shell can get on
	 * with it's life as we try to connect and handle everything
	 */
	if (session->background) {
		child = fork();
		if (child) {
			dbg("child is %d\n", child);
			exit(0);
		}
	}

	retval = send_request(session);
	if (retval && !session->background)
		fprintf(stderr, "operation failed\n");

	log_session(session, retval);
exit:
	session_readline_cleanup(session);
	session_free(session);
	return retval;;
}
Example #18
0
int cmd_search(context_t *context) {
  Window *list = NULL;
  xdo_search_t search;
  unsigned int nwindows;
  unsigned int i;
  int c;
  int op_sync = False;

  int search_title = 0;
  int search_name = 0;
  int search_class = 0;
  int search_classname = 0;
  typedef enum { 
    opt_unused, opt_title, opt_onlyvisible, opt_name, opt_class, opt_maxdepth,
    opt_pid, opt_help, opt_any, opt_all, opt_screen, opt_classname, opt_desktop,
    opt_limit, opt_sync
  } optlist_t;
  struct option longopts[] = {
    { "all", no_argument, NULL, opt_all },
    { "any", no_argument, NULL, opt_any },
    { "class", no_argument, NULL, opt_class },
    { "classname", no_argument, NULL, opt_classname },
    { "help", no_argument, NULL, opt_help },
    { "maxdepth", required_argument, NULL, opt_maxdepth },
    { "name", no_argument, NULL, opt_name },
    { "onlyvisible", 0, NULL, opt_onlyvisible },
    { "pid", required_argument, NULL, opt_pid },
    { "screen", required_argument, NULL, opt_screen },
    { "title", no_argument, NULL, opt_title },
    { "desktop", required_argument, NULL, opt_desktop },
    { "limit", required_argument, NULL, opt_limit },
    { "sync", no_argument, NULL, opt_sync },
    { 0, 0, 0, 0 },
  };
  static const char *usage = 
      "Usage: xdotool %s "
      "[options] regexp_pattern\n"
      "--class         check regexp_pattern against the window class\n"
      "--classname     check regexp_pattern against the window classname\n"
      "--maxdepth N    set search depth to N. Default is infinite.\n"
      "                -1 also means infinite.\n"
      "--onlyvisible   matches only windows currently visible\n"
      "--pid PID       only show windows belonging to specific process\n"
      "                Not supported by all X11 applications\n"
      "--screen N      only search a specific screen. Default is all screens\n"
      "--desktop N     only search a specific desktop number\n"
      "--limit N       break search after N results\n"
      "--name          check regexp_pattern against the window name\n"
      "--title         DEPRECATED. Same as --name.\n"
      "--all           Require all conditions match a window. Default is --any\n"
      "--any           Windows matching any condition will be reported\n"
      "--sync          Wait until a search result is found.\n"
      "-h, --help      show this help output\n"
      "\n"
      "If none of --name, --classname, or --class are specified, the \n"
      "defaults are: --name --classname --class\n";

  memset(&search, 0, sizeof(xdo_search_t));
  search.max_depth = -1;
  search.require = SEARCH_ANY;

  char *cmd = *context->argv;
  int option_index;

  while ((c = getopt_long_only(context->argc, context->argv, "+h",
                               longopts, &option_index)) != -1) {
    switch (c) {
      case 0:
        break;
      case 'h':
      case opt_help:
        printf(usage, cmd);
        consume_args(context, context->argc);
        return EXIT_SUCCESS;
      case opt_maxdepth:
        search.max_depth = strtol(optarg, NULL, 0);
        break;
      case opt_pid:
        search.pid = atoi(optarg);
        search.searchmask |= SEARCH_PID;
        break;
      case opt_any:
        search.require = SEARCH_ANY;
        break;
      case opt_all:
        search.require = SEARCH_ALL;
        break;
      case opt_screen:
        search.screen = strtoul(optarg, NULL, 0);
        search.searchmask |= SEARCH_SCREEN;
        break;
      case opt_onlyvisible:
        search.only_visible = True;
        search.searchmask |= SEARCH_ONLYVISIBLE;
        break;
      case opt_class:
        search_class = True;
        break;
      case opt_classname:
        search_classname = True;
        break;
      case opt_title:
        fprintf(stderr, "This flag is deprecated. Assuming you mean --name (the"
                " window name).\n");
        /* fall through */
      case opt_name:
        search_name = True;
        break;
      case opt_desktop:
        search.desktop = strtol(optarg, NULL, 0);
        search.searchmask |= SEARCH_DESKTOP;
        break;
      case opt_limit:
        search.limit = atoi(optarg);
        break;
      case opt_sync:
        op_sync = True;
        break;
      default:
        fprintf(stderr, "Invalid usage\n");
        fprintf(stderr, usage, cmd);
        return EXIT_FAILURE;
    }
  }

  consume_args(context, optind);

  /* We require a pattern or a pid to search for */
  if (context->argc < 1 && search.pid == 0) {
    fprintf(stderr, usage, cmd);
    return EXIT_FAILURE;
  }

  if (context->argc > 0) {
    if (!search_title && !search_name && !search_class && !search_classname) {
      fprintf(stderr, "Defaulting to search window name, class, and classname\n");
      search.searchmask |= (SEARCH_NAME | SEARCH_CLASS | SEARCH_CLASSNAME);
      search_name = 1;
      search_class = 1;
      search_classname = 1;
    }

    if (search_title) {
      search.searchmask |= SEARCH_NAME;
      search.winname = context->argv[0];
    }
    if (search_name) {
      search.searchmask |= SEARCH_NAME;
      search.winname = context->argv[0];
    }
    if (search_class) {
      search.searchmask |= SEARCH_CLASS;
      search.winclass = context->argv[0];
    }
    if (search_classname) {
      search.searchmask |= SEARCH_CLASSNAME;
      search.winclassname = context->argv[0];
    }
    consume_args(context, 1);
  }

  do {
    if (list != NULL) {
      free(list);
    }

    xdo_search_windows(context->xdo, &search, &list, &nwindows);

    if (context->argc == 0) {
      /* only print if we're the last command */
      for (i = 0; i < nwindows; i++) {
        window_print(list[i]);
      }
    }

    if (op_sync && nwindows == 0) {
      xdotool_debug(context, "No search results, still waiting...");

      /* TODO(sissel): Make this tunable */
      usleep(500000);
    }
  } while (op_sync && nwindows == 0);

  /* Free old list as it's malloc'd by xdo_search_windows */
  if (context->windows != NULL) {
    free(context->windows);
  }
  context->windows = list;
  context->nwindows = nwindows;

  /* error if number of windows found is zero (behave like grep) */
  return (nwindows ? EXIT_SUCCESS : EXIT_FAILURE);
}
Example #19
0
int main(int argc, char *argv[]) {
	static struct option long_options[] = {
		{"listen", required_argument, 0, 'l'},
		{"port", required_argument, 0, 'p'},
		{"help", no_argument, 0, 'h'},
		{"verbose", no_argument, 0, 'v'},
		{"ping-parent", no_argument, 0, 'x'},
		{"gcc-command", required_argument, 0, 'g'},
		{"vx32sdk", required_argument, 0, 's'},
		{"tmpdir", required_argument, 0, 't'},
		{"engine", required_argument, 0, 'e'},
		{"no-vx32", no_argument, 0, 'n'},
		{0, 0, 0, 0}
	};
	
	struct server *server = (struct server*)st_calloc(1, sizeof(struct server));
	server->info_handler = &info_handler;
	server->quit_handler = &quit_handler;
	server->process_multi= &process_multi;
	INIT_LIST_HEAD(&server->root);
	
	server->host = "127.0.0.1";
	server->port = 22122;
	
	struct config *config = (struct config*)st_calloc(1, sizeof(struct config));
	server->userdata = config;
	config->tmpdir = "/tmp";
	config->vx32sdk_path = "./untrusted/";
	config->vx32sdk_gcc_command = strdup(flatten_argv(NELEM(default_vx32sdk_gcc_command), default_vx32sdk_gcc_command, " "));
	config->syscall_limit = 4; /* 4 syscalls per request allowed */
	
	int option_index;
	int arg;
	char *engine_name = NULL;
	while((arg = getopt_long_only(argc, argv, "hxvnl:p:g:s:t:e:", long_options, &option_index)) != EOF) {
		switch(arg) {
		case 'h':
			print_help(server, config);
			exit(-1);
			break;
		case 'v':
			server->trace = 1;
			break;
		case 'x':
			server->ping_parent = 1;
			break;
		case 'l':
			server->host = optarg;
			break;
		case 'p':
			server->port = atoi(optarg);
			if(server->port < 0 || server->port > 65536)
				fatal("Port number broken: %i", server->port);
			break;
		case 'g':
			free(config->vx32sdk_gcc_command);
			config->vx32sdk_gcc_command = strdup(optarg);
			break;
		case 's':
			config->vx32sdk_path = optarg;
			break;
		case 't':
			config->tmpdir = optarg;
			break;
		case 'e':
			engine_name = optarg;
			break;
		case 'n':
			config->vx32_disabled = 1;
			break;
		case 0:
		default:
			fatal("\nUnknown option: \"%s\"\n", argv[optind-1]);
		}
	}
	
	int i;
	storage_engine_create *engine_create = NULL;
	storage_engine_destroy *engine_destroy = NULL;
	for(i=0; i<NELEM(engines); i++) {
		if(engine_name && 0 == strcmp(engine_name, engines[i].name)) {
			engine_create = engines[i].create;
			engine_destroy = engines[i].destroy;
		}
	}
	if(NULL == engine_create)
		fatal("\nYou must specify a storage engine:"
		" --engine=[%s]\n", flatten_engine_names() );

	log_info("Process pid %i", getpid());
	signal(SIGPIPE, SIG_IGN);
	
	commands_initialize();
	process_initialize(config);
	char *params = flatten_argv(argc-optind, &argv[optind], ", ");
	log_info("Loading database engine \"%s\" with parameters \"%s\"", engine_name, params);
	
	config->api = engine_create(argc-optind, &argv[optind]);
	
	do_event_loop(server);
	
	log_info("Quit");
	process_destroy();
	commands_destroy();
	pool_free();
	
	engine_destroy(config->api);
	free(config->vx32sdk_gcc_command);
	free(config);
	free(server);
	
	exit(0);
	return(0);
}
Example #20
0
int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  log_level = INFO;

  const char* usage =
    "\n--duration=(10,3600]\n"
    "[--n_worker=[1,16]]\n"
    "[--start_period=[1000000,1000000000]] [--dec_ppm=[0,1000]]\n"
    "[--outfile=<CSV file to record the result>]\n"
    "[--verbosity=[0,2]]\n"
    "Example: --duration=600 --start_period=100000000 --dec_ppm=200 --outfile=1.csv\n";
  static struct option long_options[] = {
    /* explanation of struct option {
       const char *name;
       int has_arg;
       int *flag; NULL: getopt_long returns val
                  else: returns 0, and flag points to a variable that is set to val
		  if option is found, but otherwise left unchanged if option not found
       int val;
       }; */
    {"duration", required_argument, NULL, 'd'},
    {"n_worker", required_argument, NULL, 'w'},
    {"start_period", required_argument, NULL, 's'},
    {"dec_ppm", required_argument, NULL, 'p'},
    {"outfile", required_argument, NULL, 'f'},
    {"verbosity", optional_argument, NULL, 'v'},
    {NULL, no_argument, NULL, 0} /* brackets the end of the options */
  };
  int option_index = 0, c;

  while((c = getopt_long_only(argc, argv, ""/* Not intuitive: cannot be NULL */
			      , long_options, &option_index))
	!= -1) {
    /* Remember there are these external variables:
     * extern char *optarg;
     * extern int optind, opterr, optopt;
     */
    //int this_option_optind = optind ? optind : 1;
    switch (c) {
    case 'v': /* optarg is NULL if I don't specify an arg */
      g_verbosity = optarg ? atoi(optarg) : 1;
      log_info("verbosity: %d", g_verbosity);
      break;
    case 'd':
      duration = atoi(optarg);
      log_info("duration: %d s", duration);
      break;
    case 'w':
      n_worker = atoi(optarg);
      log_info("worker: %d", n_worker);
      break;
    case 's':
      start_period = atoi(optarg);
      log_info("start_period: %d ns", start_period);
      break;
    case 'p':
      dec_ppm = atoi(optarg);
      log_info("dec_ppm: 0.%04d %%", dec_ppm);
      break;
    case 'f':
      g_outfn = optarg;
      log_info("outfile: %s", g_outfn);
      break;
    case 0: {
      char line[160];
      sprintf(line, "option %s", long_options[option_index].name);
      if(optarg) sprintf(line, " with arg %s", optarg);
      log_info(line);
    }
      break;
    case '?':/* ambiguous match or extraneous param */
    default:
      log_error("?? getopt returned character code 0%o ??", c);
      break;
    }
  }
  if (optind < argc) {
    char line[160];
    sprintf(line, "non-option ARGV-elements: ");
    while (optind < argc) sprintf(line, "%s ", argv[optind++]);
    log_warn(line);
  }
  /*
  else {
    fprintf(stderr, "Expected argument after options\n");
    return optind;
  }
  */

  /*
     If there are no more option characters, getopt() returns -1. Then optind is
     the index in argv of the first argv-element that is not an option. 
  */

  if(duration < 10 || duration > 3600
     || n_worker < 1 || n_worker > 16
     || start_period < 1000000 || start_period > 1000000000
     || dec_ppm < 0 || dec_ppm > 1000) {
    log_fatal("Invalid argument.  Usage:\n%s", usage);
    return -1;
  }

  return RUN_ALL_TESTS();
}
Example #21
0
static void
decode_options (int argc, char **argv)
{
  alternate_editor = egetenv ("ALTERNATE_EDITOR");

  while (1)
    {
      int opt = getopt_long_only (argc, argv,
#ifndef NO_SOCKETS_IN_FILE_SYSTEM
			     "VHneqa:s:f:d:F:tc",
#else
			     "VHneqa:f:d:F:tc",
#endif
			     longopts, 0);

      if (opt == EOF)
	break;

      switch (opt)
	{
	case 0:
	  /* If getopt returns 0, then it has already processed a
	     long-named option.  We should do nothing.  */
	  break;

	case 'a':
	  alternate_editor = optarg;
	  break;

#ifndef NO_SOCKETS_IN_FILE_SYSTEM
	case 's':
	  socket_name = optarg;
	  break;
#endif

	case 'f':
	  server_file = optarg;
	  break;

	  /* We used to disallow this argument in w32, but it seems better
	     to allow it, for the occasional case where the user is
	     connecting with a w32 client to a server compiled with X11
	     support.  */
	case 'd':
	  display = optarg;
	  break;

	case 'n':
	  nowait = 1;
	  break;

	case 'e':
	  eval = 1;
	  break;

	case 'q':
	  quiet = 1;
	  break;

	case 'V':
	  message (FALSE, "emacsclient %s\n", VERSION);
	  exit (EXIT_SUCCESS);
	  break;

        case 't':
          tty = 1;
	  current_frame = 0;
          break;

        case 'c':
          current_frame = 0;
          break;

	case 'p':
	  parent_id = optarg;
          current_frame = 0;
	  break;

	case 'H':
	  print_help_and_exit ();
	  break;

        case 'F':
          frame_parameters = optarg;
          break;

	default:
	  message (TRUE, "Try `%s --help' for more information\n", progname);
	  exit (EXIT_FAILURE);
	  break;
	}
    }

  /* If the -c option is used (without -t) and no --display argument
     is provided, try $DISPLAY.
     Without the -c option, we used to set `display' to $DISPLAY by
     default, but this changed the default behavior and is sometimes
     inconvenient.  So we force users to use "--display $DISPLAY" if
     they want Emacs to connect to their current display.

     Some window systems have a notion of default display not
     reflected in the DISPLAY variable.  If the user didn't give us an
     explicit display, try this platform-specific after trying the
     display in DISPLAY (if any).  */
  if (!current_frame && !tty && !display)
    {
      /* Set these here so we use a default_display only when the user
         didn't give us an explicit display.  */
#if defined (NS_IMPL_COCOA)
      alt_display = "ns";
#elif defined (HAVE_NTGUI)
      alt_display = "w32";
#endif

      display = egetenv ("DISPLAY");
    }

  if (!display)
    {
      display = alt_display;
      alt_display = NULL;
    }

  /* A null-string display is invalid.  */
  if (display && strlen (display) == 0)
    display = NULL;

  /* If no display is available, new frames are tty frames.  */
  if (!current_frame && !display)
    tty = 1;

#ifdef WINDOWSNT
  /* Emacs on Windows does not support graphical and text terminal
     frames in the same instance.  So, treat the -t and -c options as
     equivalent, and open a new frame on the server's terminal.
     Ideally, we would only set tty = 1 when the serve is running in a
     console, but alas we don't know that.  As a workaround, always
     ask for a tty frame, and let server.el figure it out.  */
  if (!current_frame)
    {
      display = NULL;
      tty = 1;
    }

  if (alternate_editor && alternate_editor[0] == '\0')
    {
      message (TRUE, "--alternate-editor argument or ALTERNATE_EDITOR variable cannot be\n\
an empty string");
      exit (EXIT_FAILURE);
    }
Example #22
0
int main(int argc, char** argv)
{
	const char* usageString = 
		"[-l] [-t <track-id>] [-s <sample-id>] [-v [<level>]] <file-name>\n";
	bool doList = false;
	bool doSamples = false;
	MP4TrackId trackId = MP4_INVALID_TRACK_ID;
	MP4SampleId sampleId = MP4_INVALID_SAMPLE_ID;
	char* dstFileName = NULL;
	u_int32_t verbosity = MP4_DETAILS_ERROR;

fprintf(stderr, "You don't want to use this utility - use mp4creator --extract instead\n");
fprintf(stderr, "If you really want to use it, remove this warning and the exit call\n");
fprintf(stderr, "from the source file\n");
	exit(-1);
	/* begin processing command line */
	ProgName = argv[0];
	while (true) {
		int c = -1;
		int option_index = 0;
		static struct option long_options[] = {
			{ "list", 0, 0, 'l' },
			{ "track", 1, 0, 't' },
			{ "sample", 2, 0, 's' },
			{ "verbose", 2, 0, 'v' },
			{ "version", 0, 0, 'V' },
			{ NULL, 0, 0, 0 }
		};

		c = getopt_long_only(argc, argv, "lt:s::v::V",
			long_options, &option_index);

		if (c == -1)
			break;

		switch (c) {
		case 'l':
			doList = true;
			break;
		case 's':
			doSamples = true;
			if (optarg) {
				if (sscanf(optarg, "%u", &sampleId) != 1) {
					fprintf(stderr, 
						"%s: bad sample-id specified: %s\n",
						 ProgName, optarg);
				}
			}
			break;
		case 't':
			if (sscanf(optarg, "%u", &trackId) != 1) {
				fprintf(stderr, 
					"%s: bad track-id specified: %s\n",
					 ProgName, optarg);
				exit(1);
			}
			break;
		case 'v':
			verbosity |= MP4_DETAILS_READ;
			if (optarg) {
				u_int32_t level;
				if (sscanf(optarg, "%u", &level) == 1) {
					if (level >= 2) {
						verbosity |= MP4_DETAILS_TABLE;
					} 
					if (level >= 3) {
						verbosity |= MP4_DETAILS_SAMPLE;
					} 
					if (level >= 4) {
						verbosity = MP4_DETAILS_ALL;
					}
				}
			}
			break;
		case '?':
			fprintf(stderr, "usage: %s %s", ProgName, usageString);
			exit(0);
		case 'V':
		  fprintf(stderr, "%s - %s version %s\n", 
			  ProgName, MPEG4IP_PACKAGE, MPEG4IP_VERSION);
		  exit(0);
		default:
			fprintf(stderr, "%s: unknown option specified, ignoring: %c\n", 
				ProgName, c);
		}
	}

	/* check that we have at least one non-option argument */
	if ((argc - optind) < 1) {
		fprintf(stderr, "usage: %s %s", ProgName, usageString);
		exit(1);
	}
	
	if (verbosity) {
		fprintf(stderr, "%s version %s\n", ProgName, MPEG4IP_VERSION);
	}

	/* point to the specified file names */
	Mp4PathName = argv[optind++];

	/* get dest file name for a single track */
	if (trackId && (argc - optind) > 0) {
		dstFileName = argv[optind++];
	}

	char* lastSlash = strrchr(Mp4PathName, '/');
	if (lastSlash) {
		Mp4FileName = lastSlash + 1;
	} else {
		Mp4FileName = Mp4PathName; 
	}

	/* warn about extraneous non-option arguments */
	if (optind < argc) {
		fprintf(stderr, "%s: unknown options specified, ignoring: ", ProgName);
		while (optind < argc) {
			fprintf(stderr, "%s ", argv[optind++]);
		}
		fprintf(stderr, "\n");
	}

	/* end processing of command line */


	MP4FileHandle mp4File = MP4Read(Mp4PathName, verbosity);

	if (!mp4File) {
		exit(1);
	}

	if (doList) {
		MP4Info(mp4File);
		exit(0);
	}

	if (trackId == 0) {
		u_int32_t numTracks = MP4GetNumberOfTracks(mp4File);

		for (u_int32_t i = 0; i < numTracks; i++) {
			trackId = MP4FindTrackId(mp4File, i);
			ExtractTrack(mp4File, trackId, doSamples, sampleId);
		}
	} else {
		ExtractTrack(mp4File, trackId, doSamples, sampleId, dstFileName);
	}

	MP4Close(mp4File);

	return(0);
}
Example #23
0
File: fmagic.c Project: cbsd/cbsd
int
main(int argc, char *argv[])
{
	int optcode = 0;
	int option_index = 0, ret = 0;
	char *file = NULL;
	int method = MAGIC_DEVICES;
	char *tmp_method = NULL;
	char *type = NULL;
	const char *magic_full;
	magic_t magic_cookie;

	static struct option long_options[] = {
		{"file", required_argument, 0, C_FILE},
		{"method", required_argument, 0, C_METHOD},
		{"type", required_argument, 0, C_TYPE},
		/* End of options marker */
		{0, 0, 0, 0}
	};

	if (argc <2 )
		usage();

	while (TRUE) {
		optcode = getopt_long_only(argc, argv, "", long_options, &option_index);
		if (optcode == -1)
			break;
		switch (optcode) {
		case C_FILE:
			file = malloc(strlen(optarg) + 1);
			memset(file, 0, strlen(optarg) + 1);
			strcpy(file, optarg);
			break;
		case C_METHOD:
			tmp_method = malloc(strlen(optarg) + 1);
			memset(tmp_method, 0, strlen(optarg) + 1);
			strcpy(tmp_method, optarg);
			method = magicIndex(tmp_method);
			if (method == 0) {
				method = MAGIC_DEVICES;
				warn("Magic index not found for %s, forcing to MAGIC_DEVICES\n",tmp_method);
				}
			free(tmp_method);
			break;
		case C_TYPE:
			file = malloc(strlen(optarg) + 1);
			memset(file, 0, strlen(optarg) + 1);
			strcpy(file, optarg);
			break;
		}
	}

	// init cookie, can be logical operand, e.g: " MAGIC_DEVICES|MAGIC_NO_CHECK_COMPRESS|MAGIC_NO_CHECK_ENCODING "
	magic_cookie = magic_open(method);
	if (magic_cookie == NULL) {
		printf("unable to initialize magic library\n");
		return 1;
	}

	// load magic database
	if (magic_load(magic_cookie, NULL) != 0) {
		printf("cannot load magic database - %s\n", magic_error(magic_cookie));
		magic_close(magic_cookie);
		return 1;
	}

	magic_full = magic_file(magic_cookie, file);
	printf("%s\n", magic_full);
	magic_close(magic_cookie);
	return 0;
}
Example #24
0
int
main(int argc, char **argv)
{
    DWORD dwProcessId = 0;
    int c;    /* Character of the parsed option.  */

    debug_options.first_chance = 1;

    while (1)
    {
        int option_index = 0;
        static const struct option long_options[] =
        {
            { "help", 0, NULL, 'h'},
            { "version", 0, NULL, 'V'},
            { "install", 0, NULL, 'i'},
            { "auto", 0, NULL, 'a'},
            { "uninstall", 0, NULL, 'u'},
            { "process-id", 1, NULL, 'p'},
            { "event", 1, NULL, 'e'},
            { "tid", 1, NULL, 't'},
            { "breakpoint", 0, NULL, 'b'},
            { "verbose", 0, NULL, 'v'},
            { "debug", 0, NULL, 'd'},
            { NULL, 0, NULL, 0}
        };

        c = getopt_long_only(argc, argv, "?hViaup:e:t:vbd", long_options, &option_index);

        if (c == -1)
            break;    /* Exit from `while (1)' loop.  */

        switch (c) {
            case '?':
                if (optopt != '?') {
                    /* Invalid option.  */
                    char szErrMsg[512];
                    sprintf(szErrMsg, "Invalid option '%c'", optopt);
                    MessageBoxA(
                        NULL,
                        szErrMsg,
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 1;
                }
                /* fall-through */
            case 'h':    /* Print help and exit.  */
                help();
                return 0;

            case 'V':    /* Print version and exit.  */
                MessageBoxA(
                    NULL,
                    PACKAGE " " VERSION,
                    PACKAGE,
                    MB_OK | MB_ICONINFORMATION
                );
                return 0;

            case 'i':    /* Install as the default JIT debugger.  */
                if (uninstall_given)
                {
                    MessageBoxA(
                        NULL,
                        "conficting options `--uninstall' (`-u') and `--install' (`-i')",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 0;
                }
                install_given = 1;
                break;

            case 'a':    /* Automatically start.  */
                if (uninstall_given)
                {
                    MessageBoxA(
                        NULL,
                        "conficting options `--uninstall' (`-u') and `--auto' (`-a')",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 0;
                }
                auto_given = 1;
                break;

            case 'u':    /* Uninstall.  */
                if (install_given)
                {
                    MessageBoxA(
                        NULL,
                        "conficting options `--install' (`-i') and `--uninstall' (`-u')",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 0;
                }
                if (auto_given)
                {
                    MessageBoxA(
                        NULL,
                        "conficting options `--auto' (`-a') and `--uninstall' (`-u')",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 0;
                }
                uninstall_given = 1;
                break;

            case 'p':    /* Attach to the process with the given identifier.  */
                if (process_id_given)
                {
                    MessageBoxA(
                        NULL,
                        "`--process-id' (`-p') option redeclared",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 1;
                }
                process_id_given = 1;
                if (optarg[0] >= '0' && optarg[0] <= '9') {
                    dwProcessId = strtoul(optarg, NULL, 0);
                } else {
                    debug_options.breakpoint_flag = 1;
                    dwProcessId = getProcessIdByName(optarg);
                }
                if (!dwProcessId) {
                    MessageBoxA(
                        NULL,
                        "Invalid process",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 1;
                }
                break;

            case 'e':    /* Signal an event after process is attached.  */
                if (debug_options.hEvent)
                {
                    MessageBoxA(
                        NULL,
                        "`--event' (`-e') option redeclared",
                        PACKAGE,
                        MB_OK | MB_ICONSTOP
                    );
                    return 1;
                }
                debug_options.hEvent = (HANDLE) (INT_PTR) atol (optarg);
                break;

            case 't': {
                /* Thread id.  Used when debugging WinRT apps. */
                debug_options.dwThreadId = strtoul(optarg, NULL, 0);
                break;
            }

            case 'b':    /* Treat debug breakpoints as exceptions */
                debug_options.breakpoint_flag = 1;
                break;

            case 'v':    /* Verbose output.  */
                debug_options.verbose_flag = 1;
                break;

            case 'd':    /* Debug output.  */
                debug_options.debug_flag = 1;
                break;

            default:    /* bug: option not considered.  */
            {
                char szErrMsg[512];
                sprintf(szErrMsg, "Unexpected option '-%c'", c);
                MessageBoxA(
                    NULL,
                    szErrMsg,
                    PACKAGE,
                    MB_OK | MB_ICONSTOP
                );
                return 1;
            }
        }
    }

    if (install_given) {
        DWORD dwRet = install(0);
#if defined(_WIN64)
        if (dwRet == ERROR_SUCCESS) {
            dwRet = install(KEY_WOW64_32KEY);
        }
#endif
        if (dwRet != ERROR_SUCCESS) {
            MessageBoxA(
                NULL,
                dwRet == ERROR_ACCESS_DENIED
                ? "You must have administrator privileges to install Dr. Mingw as the default application debugger" 
                : "Unexpected error when trying to install Dr. Mingw as the default application debugger",
                "DrMingw",
                MB_OK | MB_ICONERROR
            );
            return 1;
        }
        MessageBoxA(
            NULL,
            "Dr. Mingw has been installed as the default application debugger",
            "DrMingw",
            MB_OK | MB_ICONINFORMATION
        );
        return 0;
    }

    if (uninstall_given) {
        DWORD dwRet = uninstall(0);
#if defined(_WIN64)
        if (dwRet == ERROR_SUCCESS) {
            dwRet = uninstall(KEY_WOW64_32KEY);
        }
#endif
        if (dwRet != ERROR_SUCCESS) {
            MessageBoxA(
                NULL,
                dwRet == ERROR_ACCESS_DENIED
                ? "You must have administrator privileges to uninstall Dr. Mingw as the default application debugger" 
                : "Unexpected error when trying to uninstall Dr. Mingw as the default application debugger",
                "DrMingw",
                MB_OK | MB_ICONERROR
            );
            return 1;
        }
        MessageBoxA(
            NULL,
            "Dr. Mingw has been uninstalled",
            "DrMingw",
            MB_OK | MB_ICONINFORMATION
        );
        return 0;
    }

    if (process_id_given) {
        SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);

        if(!ObtainSeDebugPrivilege())
            MessageBoxA(
                NULL,
                "An error occured while obtaining debug privileges.\nDrMingw will not debug system processes.",
                "DrMingw",
                MB_OK | MB_ICONERROR
            );

        createDialog();

        _beginthread(debugThread, 0, (void *)(UINT_PTR)dwProcessId);

        return mainLoop();
    } else {
        help();
    }

    return 0;
}
Example #25
0
int main(int argc, char *argv[]) {
    option_flags oflags = 0;
    int exit_status = 0;
    metadata_op meta_op = -1;
    char *json_file = NULL;
    FILE     *input = NULL;

    while (1) {
        static struct option long_options[] = {
            // Flag options
            {"debug",      no_argument, &debug_flag,      1},
            {"help",       no_argument, &help_flag,       1},
            {"silent",     no_argument, &silent_flag,     1},
            {"unbuffered", no_argument, &unbuffered_flag, 1},
            {"unsafe",     no_argument, &unsafe_flag,     1},
            {"verbose",    no_argument, &verbose_flag,    1},
            {"version",    no_argument, &version_flag,    1},
            // Indexed options
            {"file",      required_argument, NULL, 'f'},
            {"operation", required_argument, NULL, 'o'},
            {0, 0, 0, 0}
        };

        int option_index = 0;
        int c = getopt_long_only(argc, argv, "f:o:",
                                 long_options, &option_index);

        /* Detect the end of the options. */
        if (c == -1) break;

        switch (c) {
            case 'f':
                json_file = optarg;
                break;

            case 'o':
                if (strcmp("add", optarg) ==  0) {
                    meta_op = META_ADD;
                }
                if (strcmp("rem", optarg) == 0) {
                    meta_op = META_REM;
                }

                break;

            case '?':
                // getopt_long already printed an error message
                break;

            default:
                // Ignore
                break;
        }
    }

    const char *help =
        "Name\n"
        "    baton-metamod\n"
        "\n"
        "Synopsis\n"
        "\n"
        "    baton-metamod [--file <JSON file>] --operation <operation>\n"
        "                  [--silent] [--unbuffered] [--unsafe]\n"
        "                  [--verbose] [--version]\n"
        "\n"
        "Description\n"
        "    Modifies metadata AVUs on collections and data objects\n"
        "described in a JSON input file.\n"
        "\n"
        "    --file        The JSON file describing the data objects and\n"
        "                  collections. Optional, defaults to STDIN.\n"
        "    --operation   Operation to perform. One of [add, rem].\n"
        "                  Required.\n"
        "    --silent      Silence error messages.\n"
        "    --unbuffered  Flush print operations for each JSON object.\n"
        "    --unsafe      Permit unsafe relative iRODS paths.\n"
        "    --verbose     Print verbose messages to STDERR.\n"
        "    --version     Print the version number and exit.\n";

    if (help_flag) {
        printf("%s\n", help);
        exit(0);
    }

    if (version_flag) {
        printf("%s\n", VERSION);
        exit(0);
    }

    if (unsafe_flag) oflags = oflags | UNSAFE_RESOLVE;

    if (debug_flag)   set_log_threshold(DEBUG);
    if (verbose_flag) set_log_threshold(NOTICE);
    if (silent_flag)  set_log_threshold(FATAL);

    declare_client_name(argv[0]);

    switch (meta_op) {
        case META_ADD:
        case META_REM:
            input = maybe_stdin(json_file);
            int status = do_modify_metadata(input, meta_op, oflags);
            if (status != 0) exit_status = 5;
            break;

        default:
            fprintf(stderr, "No valid operation was specified; valid "
                    "operations are: [add rem]\n");
            goto args_error;
    }

    exit(exit_status);

args_error:
    exit_status = 4;

    exit(exit_status);
}
Example #26
0
int
main(int argc, char *argv[])
{
    const char     *allowed_args = "hl:x:p:o:sv:i:r:V";
    char           *node = NULL;
    int             retval;
    int             async = 1;
    val_log_t      *logp;
    char           *label_str = NULL;
    struct val_daneparams daneparams;
    struct val_danestatus *danestatus = NULL;
    struct val_ssl_data *ssl_dane_data = NULL;
    int port = 443;
    int proto = DANE_PARAM_PROTO_TCP;
    val_context_t *context = NULL;
    val_status_t val_status;
    struct addrinfo *val_ainfo = NULL;
    struct addrinfo hints;
    int ret = 0;
    int dane_retval = VAL_DANE_INTERNAL_ERROR;
    int ai_retval = 0;
    int err;

    /* Parse the command line */
    while (1) {
        int             c;
#ifdef HAVE_GETOPT_LONG
        int             opt_index = 0;
#ifdef HAVE_GETOPT_LONG_ONLY
        c = getopt_long_only(argc, argv, allowed_args,
                             prog_options, &opt_index);
#else
        c = getopt_long(argc, argv, allowed_args, prog_options, &opt_index);
#endif
#else                           /* only have getopt */
        c = getopt(argc, argv, allowed_args);
#endif

        if (c == -1) {
            break;
        }

        switch (c) {
        case 'h':
            usage(argv[0]);
            return -1;
        case 'l':
            label_str = optarg;
            break;
        case 'o':
            logp = val_log_add_optarg(optarg, 1);
            if (NULL == logp) { /* err msg already logged */
                usage(argv[0]);
                return -1;
            }
            break;

        case 's':
            async = 0;
            break;

        case 'p':
            port = atoi(optarg);
            break;

        case 'x':
            if(strncmp(optarg, DANE_PARAM_PROTO_STR_TCP,
                       strlen(DANE_PARAM_PROTO_STR_TCP)))
                proto = DANE_PARAM_PROTO_TCP;
            else if (strncmp(optarg, DANE_PARAM_PROTO_STR_UDP,
                        strlen(DANE_PARAM_PROTO_STR_UDP)))
                proto = DANE_PARAM_PROTO_UDP;
            else if (strncmp(optarg, DANE_PARAM_PROTO_STR_SCTP, 
                        strlen(DANE_PARAM_PROTO_STR_SCTP)))
                proto = DANE_PARAM_PROTO_SCTP;
            else {
                usage(argv[0]);
                return -1;
            }
            break;

        case 'v':
            dnsval_conf_set(optarg);
            break;

        case 'i':
            root_hints_set(optarg);
            break;

        case 'r':
            resolv_conf_set(optarg);
            break;

        case 'V':
            version();
            return 0;
        default:
            fprintf(stderr, "Invalid option %s\n", argv[optind - 1]);
            usage(argv[0]);
            return -1;
        }
    }

    if (optind < argc) {
        node = argv[optind++];
    } else {
        fprintf(stderr, "Error: node name not specified\n");
        usage(argv[0]);
        return -1;
    }

    if (VAL_NO_ERROR != (retval = 
                val_create_context(label_str, &context))) {
        fprintf(stderr, "Cannot create context %s(%d)\n", 
                p_val_error(retval), retval);
        return -1;
    }

    daneparams.port = port;
    daneparams.proto = proto;
    memset(&hints, 0, sizeof(struct addrinfo));
#ifdef AI_ADDRCONFIG
    hints.ai_flags = AI_ADDRCONFIG;
#endif

    if (!async) {
        /* synchronous lookup and validation */
        ai_retval = val_getaddrinfo(context, node, NULL, &hints,
                                    &val_ainfo, &val_status);
        dane_retval = val_getdaneinfo(context, node, &daneparams, &danestatus); 
    }
    else {
#ifdef VAL_NO_ASYNC
        fprintf(stderr, "async support not available\n");
#else
        struct dane_cb cb_data_dane = { &dane_retval, &danestatus, 0 };
        val_dane_callback my_dane_cb = &_danecallback;
        struct timeval tv;
        val_async_status *das = NULL; /* helps us cancel the lookup if we need to */

        struct getaddr_s cb_data_ai = { &ai_retval, &val_ainfo, &val_status, 0 };
        val_gai_callback my_ai_cb = &_aicallback;
        val_gai_status *status = NULL;

        /*
         * submit requests
         */
        if (VAL_NO_ERROR != val_dane_submit(context, node, &daneparams,
                                 my_dane_cb, &cb_data_dane, &das) ||
            VAL_NO_ERROR != val_getaddrinfo_submit(context, node, NULL,
                                &hints, my_ai_cb, &cb_data_ai, 0, &status)) {
            dane_retval = VAL_DANE_INTERNAL_ERROR; 
            goto done;
        }

        /*
         * wait for it to complete
         */
#if 0
        while(0 == cb_data_dane.done ||
              0 == cb_data_ai.done) {
            tv.tv_sec = 10;
            tv.tv_usec = 0;
            val_async_check_wait(context, NULL, NULL, &tv, 0);
        }
#endif

#if 1
        while(0 == cb_data_dane.done || 
              0 == cb_data_ai.done) {
            fd_set  activefds;
            int nfds = 0;
            int ready;

            FD_ZERO(&activefds);

            tv.tv_sec = 10; /* 10 sec */
            tv.tv_usec = 0;

            val_async_select_info(context, &activefds, &nfds, &tv);
            ready = select(nfds+1, &activefds, NULL, NULL, &tv);
            if (ready < 0) {
                continue;
            } 
            val_async_check(context, &activefds, &nfds, 0);
        }
#endif

#endif
    }

done:
    if (ai_retval != 0) {
        fprintf(stderr, "Error in val_getaddrinfo(): %d\n", ai_retval);
        return -1;
    }

    if (!val_istrusted(val_status)) {
        fprintf(stderr, 
                "Address lookup information could not be validated: %s\n", 
                p_val_status(val_status));

    } else if(dane_retval == VAL_DANE_NOERROR && 
              proto == DANE_PARAM_PROTO_TCP) {

        /* Set up the SSL connection */
        SSL_library_init();
        SSL_load_error_strings();

        const SSL_METHOD *meth = SSLv23_client_method();
        SSL_CTX *sslctx = SSL_CTX_new(meth);

        struct addrinfo *ai = NULL;
        int presetup_okay;

        /*
         * OpenSSL only does protocol negotiation on SSLv23_client_method;
         * we need to set SNI to get the correct certificate from many
         * modern browsers, so we disable both SSLv2 and SSLv3 if we can.
         * That leaves (currently) TLSv1.0 TLSv1.1 TLSv1.2
         */
        long ssl_options = 0
#ifdef SSL_OP_NO_SSLv2
            | SSL_OP_NO_SSLv2
#endif
#ifdef SSL_OP_NO_SSLv3
            | SSL_OP_NO_SSLv3
#endif
            ;

        if (!SSL_CTX_set_options(sslctx, ssl_options)) {
            fprintf(stderr, "Failed to set SSL context options (%ld): %s\n",
              ssl_options, ssl_error());
            presetup_okay = 0;
        } else {
            presetup_okay = 1;
        }

        if (VAL_NO_ERROR != (err = val_enable_dane_ssl(context, sslctx, node,
                                        danestatus, &ssl_dane_data))) {
            fprintf(stderr,
                    "Could not set danestatus for SSL connection %s\n",
                    p_val_error(err));
        }

        ai = val_ainfo;
        while(presetup_okay && ai && (ai->ai_protocol == IPPROTO_TCP) && 
             (ai->ai_family == AF_INET || ai->ai_family == AF_INET6)) {

            int sock;
            char buf[INET6_ADDRSTRLEN];
            size_t buflen = sizeof(buf);
            const char *addr = NULL;

            if (ai->ai_family == AF_INET) {
                sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
                ((struct sockaddr_in *)(ai)->ai_addr)->sin_port = htons(port);
            } else {
                sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
                ((struct sockaddr_in6 *)(ai)->ai_addr)->sin6_port = htons(port);
            }

            INET_NTOP(ai->ai_family, ai->ai_addr, sizeof(ai->ai_addr), buf, buflen, addr);
            fprintf(stderr, "Connecting to %s\n", addr);

            if (0 == connect(sock, ai->ai_addr, ai->ai_addrlen)) {
                SSL *ssl = SSL_new(sslctx);
                BIO * sbio = BIO_new_socket(sock,BIO_NOCLOSE);


#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
                SSL_set_tlsext_host_name(ssl, node);
#endif

                SSL_set_bio(ssl,sbio,sbio);

                if ((err = SSL_connect(ssl)) != 1) {
                    fprintf(stderr, "SSL Connect to %s failed: %d\n", node, err);
                } 
                SSL_shutdown(ssl);
                SSL_free(ssl);
            } else {
                fprintf(stderr, "TCP Connect to %s failed\n", node);
            }

            ai = (struct addrinfo *) (ai->ai_next);
        }

    } else if (dane_retval == VAL_DANE_IGNORE_TLSA) {
        fprintf(stderr, "TLSA is either provably non-existant or provably insecure. It will be ignored.\n");
    } else {
        fprintf(stderr, "TLSA record could not be validated.\n");
        ret = 1;
    }

    if (danestatus != NULL)
        val_free_dane(danestatus);

    if (val_ainfo != NULL)
        val_freeaddrinfo(val_ainfo);    

    val_free_dane_ssl(ssl_dane_data);/* MUST happen before we free the context*/
    val_free_context(context);
    val_free_validator_state();

    return ret;
}
Example #27
0
int main( int argc, char **argv )
{
   int32_t ret;
   char optstring[OPTSTRING_LEN];
   int  opt;
   int  opt_preferred = 0;
   int  opt_explicit = 0;
   int  opt_sdtvon = 0;
   int  opt_off = 0;
   int  opt_modes = 0;
   int  opt_monitor = 0;
   int  opt_status = 0;
   int  opt_audiosup = 0;
   int  opt_dumpedid = 0;
   int  opt_showinfo = 0;
   int  opt_3d = 0;
   int  opt_json = 0;
   int  opt_name = 0;

   char *dumpedid_filename = NULL;
   VCHI_INSTANCE_T    vchi_instance;
   VCHI_CONNECTION_T *vchi_connection;
   HDMI_RES_GROUP_T power_on_explicit_group = HDMI_RES_GROUP_INVALID;
   uint32_t         power_on_explicit_mode;
   uint32_t         power_on_explicit_drive = HDMI_MODE_HDMI;
   HDMI_RES_GROUP_T get_modes_group = HDMI_RES_GROUP_INVALID;
   SDTV_MODE_T sdtvon_mode;
   SDTV_ASPECT_T sdtvon_aspect;

   // Initialize VCOS
   vcos_init();

   // Create the option string that we will be using to parse the arguments
   create_optstring( optstring );

   // Parse the command line arguments
   while (( opt = getopt_long_only( argc, argv, optstring, long_opts,
                                    NULL )) != -1 )
   {
      switch ( opt )
      {
         case 0:
         {
            // getopt_long returns 0 for entries where flag is non-NULL
            break;
         }
         case OPT_PREFERRED:
         {
            opt_preferred = 1;
            break;
         }
         case OPT_EXPLICIT:
         {
            char group_str[32], drive_str[32];

            /* coverity[secure_coding] String length specified, so can't overflow */
            int s = sscanf( optarg, "%31s %u %31s", group_str, &power_on_explicit_mode, drive_str );
            if ( s != 2 && s != 3 )
            {
               LOG_ERR( "Invalid arguments '%s'", optarg );
               goto err_out;
            }

            // Check the group first
            if ( vcos_strcasecmp( "CEA", group_str ) == 0 )
            {
               power_on_explicit_group = HDMI_RES_GROUP_CEA;
            }
            else if ( vcos_strcasecmp( "DMT", group_str ) == 0 )
            {
               power_on_explicit_group = HDMI_RES_GROUP_DMT;
            }
            else if ( vcos_strcasecmp( "CEA_3D", group_str ) == 0  ||
                      vcos_strcasecmp( "CEA_3D_SBS", group_str ) == 0)
            {
               power_on_explicit_group = HDMI_RES_GROUP_CEA;
               opt_3d = 1;
            }
            else if ( vcos_strcasecmp( "CEA_3D_TB", group_str ) == 0 )
            {
               power_on_explicit_group = HDMI_RES_GROUP_CEA;
               opt_3d = 2;
            }
            else
            {
               LOG_ERR( "Invalid group '%s'", group_str );
               goto err_out;
            }
            if (s==3)
            {
               if (vcos_strcasecmp( "HDMI", drive_str ) == 0 )
               {
                  power_on_explicit_drive = HDMI_MODE_HDMI;
               }
               else if (vcos_strcasecmp( "DVI", drive_str ) == 0 )
               {
                  power_on_explicit_drive = HDMI_MODE_DVI;
               }
               else
               {
                  LOG_ERR( "Invalid drive '%s'", drive_str );
                  goto err_out;
               }
            }
            // Then check if mode is a sane number
            if ( power_on_explicit_mode > MAX_MODE_ID )
            {
               LOG_ERR( "Invalid mode '%u'", power_on_explicit_mode );
               goto err_out;
            }

            opt_explicit = 1;
            break;
         }
         case OPT_SDTVON:
         {
            char mode_str[32], aspect_str[32];

            if ( sscanf( optarg, "%s %s", mode_str,
                         aspect_str ) != 2 )
            {
               LOG_ERR( "Invalid arguments '%s'", optarg );
               goto err_out;
            }

            // Check the group first
            if ( vcos_strcasecmp( "NTSC", mode_str ) == 0 )
            {
               sdtvon_mode = SDTV_MODE_NTSC;
            }
            else if ( vcos_strcasecmp( "NTSC_J", mode_str ) == 0 )
            {
               sdtvon_mode = SDTV_MODE_NTSC_J;
            }
            else if ( vcos_strcasecmp( "PAL", mode_str ) == 0 )
            {
               sdtvon_mode = SDTV_MODE_PAL;
            }
            else if ( vcos_strcasecmp( "PAL_M", mode_str ) == 0 )
            {
               sdtvon_mode = SDTV_MODE_PAL_M;
            }
            else
            {
               LOG_ERR( "Invalid mode '%s'", mode_str );
               goto err_out;
            }

            if ( vcos_strcasecmp( "4:3", aspect_str ) == 0 )
            {
               sdtvon_aspect = SDTV_ASPECT_4_3;
            }
            else if ( vcos_strcasecmp( "14:9", aspect_str ) == 0 )
            {
               sdtvon_aspect = SDTV_ASPECT_14_9;
            }
            else if ( vcos_strcasecmp( "16:9", aspect_str ) == 0 )
            {
               sdtvon_aspect = SDTV_ASPECT_16_9;
            }

            opt_sdtvon = 1;
            break;
         }
         case OPT_OFF:
         {
            opt_off = 1;
            break;
         }
         case OPT_MODES:
         {
            if ( vcos_strcasecmp( "CEA", optarg ) == 0 )
            {
               get_modes_group = HDMI_RES_GROUP_CEA;
            }
            else if ( vcos_strcasecmp( "DMT", optarg ) == 0 )
            {
               get_modes_group = HDMI_RES_GROUP_DMT;
            }
            else
            {
               LOG_ERR( "Invalid group '%s'", optarg );
               goto err_out;
            }

            opt_modes = 1;
            break;
         }
         case OPT_MONITOR:
         {
            opt_monitor = 1;
            break;
         }
         case OPT_STATUS:
         {
            opt_status = 1;
            break;
         }
         case OPT_AUDIOSUP:
         {
            opt_audiosup = 1;
            break;
         }
         case OPT_DUMPEDID:
         {
            opt_dumpedid = 1;
            dumpedid_filename = optarg;
            break;
         }
         case OPT_SHOWINFO:
         {
            opt_showinfo = atoi(optarg)+1;
            break;
         }
         case OPT_JSON:
         {
            opt_json = 1;
            break;
         }
         case OPT_NAME:
         {
            opt_name = 1;
            break;
         }
         default:
         {
            LOG_ERR( "Unrecognized option '%d'\n", opt );
            goto err_usage;
         }
         case '?':
         case OPT_HELP:
         {
            goto err_usage;
         }
      } // end switch
   } // end while

   argc -= optind;
   argv += optind;

   if (( optind == 1 ) || ( argc > 0 ))
   {
      if ( argc > 0 )
      {
         LOG_ERR( "Unrecognized argument -- '%s'", *argv );
      }

      goto err_usage;
   }

   if (( opt_preferred + opt_explicit + opt_sdtvon > 1 ))
   {
      LOG_ERR( "Conflicting power on options" );
      goto err_usage;
   }

   if ((( opt_preferred == 1 ) || ( opt_explicit == 1 ) || ( opt_sdtvon == 1)) && ( opt_off == 1 ))
   {
      LOG_ERR( "Cannot power on and power off simultaneously" );
      goto err_out;
   }

   // Initialize the VCHI connection
   ret = vchi_initialise( &vchi_instance );
   if ( ret != 0 )
   {
      LOG_ERR( "Failed to initialize VCHI (ret=%d)", ret );
      goto err_out;
   }

   ret = vchi_connect( NULL, 0, vchi_instance );
   if ( ret != 0)
   {
      LOG_ERR( "Failed to create VCHI connection (ret=%d)", ret );
      goto err_out;
   }

//   LOG_INFO( "Starting tvservice" );

   // Initialize the tvservice
   vc_vchi_tv_init( vchi_instance, &vchi_connection, 1 );

   if ( opt_monitor == 1 )
   {
      LOG_STD( "Starting to monitor for HDMI events" );

      if ( start_monitor() != 0 )
      {
         goto err_stop_service;
      }
   }

   if ( opt_modes == 1 )
   {
      if ( get_modes( get_modes_group, opt_json ) != 0 )
      {
         goto err_stop_service;
      }
   }

   if ( opt_preferred == 1 )
   {
      if ( power_on_preferred() != 0 )
      {
         goto err_stop_service;
      }
   }
   else if ( opt_explicit == 1 )
   {
      //Distinguish between turning on 3D side by side and 3D top/bottom
      if(opt_3d == 1 && set_property( HDMI_PROPERTY_3D_STRUCTURE, HDMI_3D_FORMAT_SBS_HALF, 0) != 0)
      {
         goto err_stop_service;
      }
      else if(opt_3d == 2 && set_property( HDMI_PROPERTY_3D_STRUCTURE, HDMI_3D_FORMAT_TB_HALF, 0) != 0)
      {
         goto err_stop_service;
      }

      if ( power_on_explicit( power_on_explicit_group,
                              power_on_explicit_mode, power_on_explicit_drive ) != 0 )
      {
         goto err_stop_service;
      }
   }
   else if ( opt_sdtvon == 1 )
   {
      if ( power_on_sdtv( sdtvon_mode,
                              sdtvon_aspect ) != 0 )
      {
         goto err_stop_service;
      }
   }
   else if (opt_off == 1 )
   {
      if ( power_off() != 0 )
      {
         goto err_stop_service;
      }
   }

   if ( opt_status == 1 )
   {
      if ( get_status() != 0 )
      {
         goto err_stop_service;
      }
   }
   
   if ( opt_audiosup == 1 )
   {
      if ( get_audiosup() != 0 )
      {
         goto err_stop_service;
      }
   }
   
   if ( opt_dumpedid == 1 )
   {
      if ( dump_edid(dumpedid_filename) != 0 )
      {
         goto err_stop_service;
      }
   }

   if ( opt_showinfo )
   {
      if ( show_info(opt_showinfo-1) != 0 )
      {
         goto err_stop_service;
      }
   }

   if ( opt_name == 1 )
   {
      TV_DEVICE_ID_T id;
      memset(&id, 0, sizeof(id));
      if(vc_tv_get_device_id(&id) == 0) {
         if(id.vendor[0] == '\0' || id.monitor_name[0] == '\0') {
            LOG_ERR( "No device present" );
         } else {
            LOG_STD( "device_name=%s-%s", id.vendor, id.monitor_name);
         }
      } else {
         LOG_ERR( "Failed to obtain device name" );
      }
   }

   if ( opt_monitor == 1 )
   {
      // Wait until we get the signal to exit
      vcos_event_wait( &quit_event );

      vcos_event_delete( &quit_event );
   }

err_stop_service:
//   LOG_INFO( "Stopping tvservice" );

   // Stop the tvservice
   vc_vchi_tv_stop();

   // Disconnect the VCHI connection
   vchi_disconnect( vchi_instance );

   exit( 0 );

err_usage:
   show_usage();

err_out:
   exit( 1 );
}
void config_parse(int argc, char* argv[], PCONFIGURATION config) {
  config->stream.width = 1280;
  config->stream.height = 720;
  config->stream.fps = 60;
  config->stream.bitrate = -1;
  config->stream.packetSize = 1024;
  config->stream.streamingRemotely = 0;

  config->platform = "default";
  config->app = "Steam";
  config->action = NULL;
  config->address = NULL;
  config->config_file = NULL;
  config->sops = true;
  config->localaudio = false;

  config->inputsCount = 0;
  config->mapping = get_path("mappings/default.conf", getenv("XDG_DATA_DIRS"));
  config->key_dir[0] = 0;

  char* config_file = get_path("moonlight.conf", "/etc");
  if (config_file)
    config_file_parse(config_file, config);
  
  if (argc == 2 && access(argv[1], F_OK) == 0) {
    config->action = "stream";
    if (!config_file_parse(argv[1], config))
      exit(EXIT_FAILURE);

  } else {
    int option_index = 0;
    int c;
    while ((c = getopt_long_only(argc, argv, "-abc:d:efg:h:i:j:k:lm:no:p:q:r:s", long_options, &option_index)) != -1) {
      parse_argument(c, optarg, config);
    }
  }

  if (config->config_file != NULL)
    config_save(config->config_file, config);

  if (config->key_dir[0] == 0x0) {
    const char *xdg_cache_dir = getenv("XDG_CACHE_DIR");
    if (xdg_cache_dir != NULL)
      sprintf(config->key_dir, "%s" MOONLIGHT_PATH, xdg_cache_dir);
    else {
      const char *home_dir = getenv("HOME");
      sprintf(config->key_dir, "%s" DEFAULT_CACHE_DIR MOONLIGHT_PATH, home_dir);
    }
  }

  if (config->stream.bitrate == -1) {
    if (config->stream.height >= 1080 && config->stream.fps >= 60)
      config->stream.bitrate = 20000;
    else if (config->stream.height >= 1080 || config->stream.fps >= 60)
      config->stream.bitrate = 10000;
    else
      config->stream.bitrate = 5000;
  }

  if (inputAdded && !mapped) {
    fprintf(stderr, "Mapping option should be followed by the input to be mapped.\n");
    exit(-1);
  }
}
Example #29
0
int main( int argc, char *argv[] )
{
  static LALStatus      status;

  INT4  startTime = -1;
  LIGOTimeGPS startTimeGPS = {0,0};
  INT4  endTime = -1;
  LIGOTimeGPS endTimeGPS = {0,0};
  CHAR  inputIFO[LIGOMETA_IFO_MAX];
  CHAR  outputIFO[LIGOMETA_IFO_MAX];
  CHAR  comment[LIGOMETA_COMMENT_MAX];
  CHAR *userTag = NULL;
  CHAR *ifoTag = NULL;

  CHAR  fileName[FILENAME_MAX];

  INT4  numTriggers = 0;

  SnglInspiralTable    *inspiralEventList=NULL;
  SnglInspiralTable    *currentTrigger = NULL;

  SearchSummvarsTable  *inputFiles = NULL;
  SearchSummvarsTable  *thisInputFile = NULL;

  SearchSummaryTable   *searchSummList = NULL;
  SearchSummaryTable   *thisSearchSumm = NULL;

  MetadataTable         proctable;
  MetadataTable         processParamsTable;
  MetadataTable         searchsumm;
  MetadataTable         searchSummvarsTable;
  MetadataTable         inspiralTable;
  ProcessParamsTable   *this_proc_param = NULL;
  LIGOLwXMLStream       xmlStream;
  INT4                  outCompress = 0;

  long int              gpstime;

  trigScanType trigScanMethod = trigScanNone;
                                          /* Switch for clustering        */
                                          /* triggers in template         */
                                          /* parameters and end time      */
  REAL8  trigScanMetricScalingFac = -1.0;
  /* Use this scaling factor for the volume spanned by a trigger in the   */
  /* parameter space. When set to x, the volume is taken to be that of the*/
  /* ambiguity ellipsoid at a 'minimal match' of (1.0-x).                 */
                                          /* original bank entered at the */
                                          /* command line                 */
  INT2  trigScanAppendStragglers = -1;    /* Switch to append cluster     */
                                          /* out-liers (stragglers)       */

  INT4                  i;

  /* getopt arguments */
  struct option long_options[] =
  {
    {"verbose",                no_argument,           &vrbflg,            1 },
    {"write-compress",         no_argument,           &outCompress,       1 },
    {"gps-start-time",         required_argument,     0,                 'q'},
    {"gps-end-time",           required_argument,     0,                 'r'},
    {"help",                   no_argument,           0,                 'h'}, 
    {"version",                no_argument,           0,                 'V'},
    {"user-tag",               required_argument,     0,                 'Z'},
    {"ifo",                    required_argument,     0,                 'I'},
    {"ts-cluster",             required_argument,     0,                 '*'},
    {"ts-metric-scaling",      required_argument,     0,                 '>'},
    {0, 0, 0, 0}
  };
  int c;

  /*
   * 
   * initialize things
   *
   */

  lal_errhandler = LAL_ERR_EXIT;
  setvbuf( stdout, NULL, _IONBF, 0 );

  /* create the process and process params tables */
  proctable.processTable = (ProcessTable *) calloc( 1, sizeof(ProcessTable) );
  XLALGPSTimeNow(&(proctable.processTable->start_time));
  XLALPopulateProcessTable(proctable.processTable, PROGRAM_NAME, LALAPPS_VCS_IDENT_ID,
      LALAPPS_VCS_IDENT_STATUS, LALAPPS_VCS_IDENT_DATE, 0);
  this_proc_param = processParamsTable.processParamsTable = 
    (ProcessParamsTable *) calloc( 1, sizeof(ProcessParamsTable) );
  memset( comment, 0, LIGOMETA_COMMENT_MAX * sizeof(CHAR) );

  /* create the search summary and zero out the summvars table */
  searchsumm.searchSummaryTable = (SearchSummaryTable *)
    calloc( 1, sizeof(SearchSummaryTable) );


  /* parse the arguments */
  while ( 1 )
  {
    /* getopt_long stores long option here */
    int option_index = 0;
    size_t optarg_len;

    c = getopt_long_only( argc, argv, 
        "a:b:hq:r:s:A:I:VZ:", long_options, 
        &option_index );

    /* detect the end of the options */
    if ( c == -1 )
    {
      break;
    }

    switch ( c )
    {
      case 0:
        /* if this option set a flag, do nothing else now */
        if ( long_options[option_index].flag != 0 )
        {
          break;
        }
        else
        {
          fprintf( stderr, "Error parsing option %s with argument %s\n",
              long_options[option_index].name, optarg );
          exit( 1 );
        }
        break;

      case 's':
        if ( strlen( optarg ) > LIGOMETA_COMMENT_MAX - 1 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "comment must be less than %d characters\n",
              long_options[option_index].name, LIGOMETA_COMMENT_MAX );
          exit( 1 );
        }
        else
        {
          snprintf( comment, LIGOMETA_COMMENT_MAX, "%s", optarg);
        }
        break;

      case 'h':
        /* help message */
        print_usage(argv[0]);
        exit( 1 );
        break;

      case 'Z':
        /* create storage for the usertag */
        optarg_len = strlen(optarg) + 1;
        userTag = (CHAR *) calloc( optarg_len, sizeof(CHAR) );
        memcpy( userTag, optarg, optarg_len );

        this_proc_param = this_proc_param->next = (ProcessParamsTable *)
          calloc( 1, sizeof(ProcessParamsTable) );
        snprintf( this_proc_param->program, LIGOMETA_PROGRAM_MAX, "%s", 
            PROGRAM_NAME );
        snprintf( this_proc_param->param, LIGOMETA_PARAM_MAX, "-userTag" );
        snprintf( this_proc_param->type, LIGOMETA_TYPE_MAX, "string" );
        snprintf( this_proc_param->value, LIGOMETA_VALUE_MAX, "%s",
            optarg );
        break;

      case 'I':
        /* create storage for the ifo-tag */
        optarg_len = strlen(optarg) + 1;
        ifoTag = (CHAR *) calloc( optarg_len, sizeof(CHAR) );
        memcpy( ifoTag, optarg, optarg_len );
        ADD_PROCESS_PARAM( "string", "%s", optarg );

        snprintf(inputIFO,  LIGOMETA_IFO_MAX, "%s", optarg);
        snprintf(outputIFO, LIGOMETA_IFO_MAX, "%s", optarg);
        break;
      case 'V':
        /* print version information and exit */
        fprintf( stdout, "TrigScan Cluster \n" 
            "Larne Pekowsky\n"
            "Based on trigbank and inspiral by Patrick Brady, Duncan Brown and Steve Fairhurst\n");
        XLALOutputVersionString(stderr, 0);
        exit( 0 );
        break;

      case '?':
        print_usage(argv[0]);
        exit( 1 );
        break;
      case 'q':
        /* start time */
        gpstime = atol( optarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        startTime = (INT4) gpstime;
        startTimeGPS.gpsSeconds = startTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, startTime );
        break;

      case 'r':
        /* end time  */
        gpstime = atol( optarg );
        if ( gpstime < 441417609 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "GPS start time is prior to " 
              "Jan 01, 1994  00:00:00 UTC:\n"
              "(%ld specified)\n",
              long_options[option_index].name, gpstime );
          exit( 1 );
        }
        endTime = (INT4) gpstime;
        endTimeGPS.gpsSeconds = endTime;
        ADD_PROCESS_PARAM( "int", "%" LAL_INT4_FORMAT, endTime );
        break;

      case '*':
        /* store trigSanClustering method */
        if ( ! strcmp( "T0T3Tc", optarg ) )
        {
            trigScanMethod = T0T3Tc;
            trigScanAppendStragglers = 0;
        }
        else if ( ! strcmp( "T0T3TcAS", optarg ) )
        {
            trigScanMethod = T0T3Tc;
            trigScanAppendStragglers = 1;
        }
        else if ( ! strcmp( "Psi0Psi3Tc", optarg ) )
        {
            trigScanMethod = Psi0Psi3Tc;
            trigScanAppendStragglers = 0;
        }
        else if ( ! strcmp( "Psi0Psi3TcAS", optarg ) )
        {
            trigScanMethod = Psi0Psi3Tc;
            trigScanAppendStragglers = 1;
        }
        else
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "unknown scan method specified: %s\n"
              "(Must be one of T0T3Tc, T0T3TcAS, Psi0Psi3Tc, Psi0Psi3TcAS)\n",
              long_options[option_index].name, optarg );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "string", "%s", optarg );
        break;

      case '>':
        /* TrigScan Template Metric Scaling Factor */
        trigScanMetricScalingFac = atof( optarg );
        if ( trigScanMetricScalingFac <= 0.0 )
        {
          fprintf( stderr, "invalid argument to --%s:\n"
              "ts-volume-safety must be > 0.0 : "
              "(%f specified)\n",
              long_options[option_index].name, trigScanMetricScalingFac );
          exit( 1 );
        }
        ADD_PROCESS_PARAM( "float", "%s", optarg );
        break;
      default:
        fprintf( stderr, "Error: Unknown error while parsing options\n" );
        print_usage(argv[0]);
        exit( 1 );
    }
  }


  /* check the values of the arguments */
  if ( startTime < 0 )
  {
    fprintf( stderr, "Error: --gps-start-time must be specified\n" );
    exit( 1 );
  }

  if ( endTime < 0 )
  {
    fprintf( stderr, "Error: --gps-end-time must be specified\n" );
    exit( 1 );
  }

  /* Check the trigScan input parameters */
  if ( ! trigScanMethod )
  {
      fprintf ( stderr, "You must specify --ts-method\n" );
      exit(1);
  }

  if ( trigScanMetricScalingFac <= 0.0 )
  {
    fprintf ( stderr, "You must specify --ts-metric-scaling\n" );
    exit(1);
  }


  /* fill the comment, if a user has specified one, or leave it blank */
  if ( ! *comment )
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX, " " );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX, 
        " " );
  } 
  else 
  {
    snprintf( proctable.processTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
    snprintf( searchsumm.searchSummaryTable->comment, LIGOMETA_COMMENT_MAX,
        "%s", comment );
  }

  /* delete the first, empty process_params entry */
  this_proc_param = processParamsTable.processParamsTable;
  processParamsTable.processParamsTable = 
    processParamsTable.processParamsTable->next;
  free( this_proc_param );

  /*
   *
   * read in the input data from the rest of the arguments
   *
   */

  if ( optind < argc )
  {
    for( i = optind; i < argc; ++i )
    {
      INT4 numFileTriggers = 0;

      numFileTriggers = XLALReadInspiralTriggerFile( &inspiralEventList,
          &currentTrigger, &searchSummList, &inputFiles, argv[i] );
      if (numFileTriggers < 0)
      {
        fprintf(stderr, "Error reading triggers from file %s",
            argv[i]);
        exit( 1 );
      }
      
      numTriggers += numFileTriggers;
    }
  }
  else
  {
    fprintf( stderr, "Error: No trigger files specified.\n" );
    exit( 1 );
  }

  if ( vrbflg ) fprintf( stdout, "Read in a total of %d triggers.\n",
      numTriggers );


  if ( ! inspiralEventList )
  {
    /* no triggers read in so triggered bank will be empty */
    fprintf( stdout, "No triggers read in\n");
    exit( 0 );
  }


  /* trigScanClustering */ 
  /* Call the clustering routine */ 
  if (XLALTrigScanClusterTriggers( &(inspiralEventList),
                                 trigScanMethod,
                                 trigScanMetricScalingFac,
                                 trigScanAppendStragglers ) == XLAL_FAILURE )
  {
    fprintf( stderr, "New trig scan has failed!!\n" );
    exit(1);
  }

  /* time sort the triggers */
  if ( vrbflg ) fprintf( stdout, "Sorting triggers\n" );
  LAL_CALL( LALSortSnglInspiral( &status, &inspiralEventList,
        LALCompareSnglInspiralByTime ), &status );

  if( !inspiralEventList )
  {
    if ( vrbflg ) fprintf( stdout, 
        "No triggers remain after time and playground cuts.\n" );

    /* set numTriggers after cuts were applied */
    numTriggers = 0;
  }

  /*
   *
   * write the output xml file
   *
   */

  /* search summary entries: */
  searchsumm.searchSummaryTable->in_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->in_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->out_start_time = startTimeGPS;
  searchsumm.searchSummaryTable->out_end_time = endTimeGPS;
  searchsumm.searchSummaryTable->nevents = numTriggers;

  if ( vrbflg ) fprintf( stdout, "writing output file... " );

  /* set the file name correctly */
  if ( userTag && !outCompress )
 {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%s-%d-%d.xml", 
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else if ( !userTag && !outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%d-%d.xml", 
        outputIFO, startTime, endTime - startTime );
  }
  else if ( userTag && outCompress )
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%s-%d-%d.xml.gz",
        outputIFO, userTag, startTime, endTime - startTime );
  }
  else 
  {
    snprintf( fileName, FILENAME_MAX, "%s-TRIGSCAN_%d-%d.xml.gz",
        outputIFO, startTime, endTime - startTime );
  }

  memset( &xmlStream, 0, sizeof(LIGOLwXMLStream) );
  LAL_CALL( LALOpenLIGOLwXMLFile( &status , &xmlStream, fileName ), 
      &status );

  /* write process table */
  snprintf( proctable.processTable->ifos, LIGOMETA_IFOS_MAX, "%s", 
      inputIFO );
  XLALGPSTimeNow(&(proctable.processTable->end_time));
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, process_table ), 
      &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, proctable, 
        process_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write process_params table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        process_params_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, processParamsTable, 
        process_params_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write search_summary table */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status, &xmlStream, 
        search_summary_table ), &status );
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchsumm, 
        search_summary_table ), &status );
  LAL_CALL( LALEndLIGOLwXMLTable ( &status, &xmlStream ), &status );

  /* write the search_summvars tabls */
  LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
        search_summvars_table), &status );
  searchSummvarsTable.searchSummvarsTable = inputFiles;
  LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, searchSummvarsTable,
        search_summvars_table), &status );
  LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );

  /* write the sngl_inspiral table */
  if ( inspiralEventList )
  {
    LAL_CALL( LALBeginLIGOLwXMLTable( &status ,&xmlStream, 
          sngl_inspiral_table), &status );
    inspiralTable.snglInspiralTable = inspiralEventList;
    LAL_CALL( LALWriteLIGOLwXMLTable( &status, &xmlStream, inspiralTable,
          sngl_inspiral_table), &status );
    LAL_CALL( LALEndLIGOLwXMLTable( &status, &xmlStream), &status );
  }

  LAL_CALL( LALCloseLIGOLwXMLFile( &status, &xmlStream), &status );


  if ( vrbflg ) fprintf( stdout, "done\n" );


  /*
   *
   * clean up the memory that has been allocated 
   *
   */


  if ( vrbflg ) fprintf( stdout, "freeing memory... " );

  free( proctable.processTable );
  free( searchsumm.searchSummaryTable );

  while ( processParamsTable.processParamsTable )
  {
    this_proc_param = processParamsTable.processParamsTable;
    processParamsTable.processParamsTable = this_proc_param->next;
    free( this_proc_param );
  }

  while ( inputFiles )
  {
    thisInputFile = inputFiles;
    inputFiles = thisInputFile->next;
    LALFree( thisInputFile );
  }

  while ( searchSummList )
  {
    thisSearchSumm = searchSummList;
    searchSummList = searchSummList->next;
    LALFree( thisSearchSumm );
  }


  while ( inspiralEventList )
  {
    currentTrigger = inspiralEventList;
    inspiralEventList = inspiralEventList->next;
    LAL_CALL( LALFreeSnglInspiral( &status, &currentTrigger ), &status );
  }

  if ( userTag ) free( userTag );
  if ( ifoTag ) free( ifoTag );

  if ( vrbflg ) fprintf( stdout, "done\n" );

  LALCheckMemoryLeaks();

  exit( 0 );
}
int main(int argc,char**argv)
{
    int i;
	int uses = 0;
    //int pid;
    char *addr;
    //int len = 100000*0x1000;
    //addr = malloc(len);
    //memset(addr,0,len);
    while(1) {
        int option_index = 0, c = 0;
        static struct option long_options[] = {
            {"h", no_argument, 0, 0 },
            {"help", no_argument, 0, 0},
            {"t", required_argument, 0, 0},
            {"threads", required_argument, 0, 0},
            {"i", required_argument, 0, 0},
            {"iterators", required_argument, 0, 0},
            {"p", required_argument, 0, 0},
            {"pages", required_argument, 0, 0},
            {"m", required_argument, 0, 0},
            {"mallocs", required_argument, 0, 0},
            {0, 0, 0, 0}
        };

        c = getopt_long_only(argc, argv, "", long_options, &option_index);

        /* no more options to parse */
        if(c == -1) break;

        /* unrecognized option */
        if(c == '?') {
            help();
            return 0;
        }

        switch(option_index) {
            /* h, help */
        case 0:
        case 1:
            help();
            return 0;
            break;

            /* t, threads */
        case 2:
        case 3:
            n = atoi(optarg);
            break;

            /* i, iterators */
        case 4:
        case 5:
            iters = atoi(optarg);
            break;

        case 6:
        case 7:
            pages = atoi(optarg);
            break;
		case 8:
        case 9:
            uses = atoi(optarg);
            break;
default:
			help();
			break;
        }
    }

    if(n<=0)
        n = 100;
    if(iters<=0)
        iters = 100;
    if(pages <= 0)
        pages = 1;
	if(uses <=0)
		uses = 0;

	DBG("n=%d,iters=%d,pages=%d,uses=%d",n,iters,pages,uses);
	DBG("using uses:%dM,ram:%dM",uses,n*iters*pages*4/1000);
	if(uses > 0){
		addr = malloc(uses*1000*1000);
		if(addr){
			memset(addr,0,uses*1000*1000);
		}else{
			fprintf(stderr,"malloc error\n");
		}
	}

    thread_info *threads;
    threads = malloc(sizeof(thread_info) * n);
    for(i=0; i<n; i++) {
        threads[i].id = i;
        pthread_create(&threads[i].pthreadId,NULL,worker,&threads[i]);
    }
    for(i=0; i<n; i++) {
        pthread_join(threads[i].pthreadId,NULL);
    }
    //fprintf(stderr,"len=%d\n",len);
    fprintf(stderr,"exit\n");
    return 0;
}