示例#1
0
文件: cf-execd.c 项目: mvpel/core
static GenericAgentConfig *CheckOpts(EvalContext *ctx, int argc, char **argv)
{
    extern char *optarg;
    int optindex = 0;
    int c;
    char ld_library_path[CF_BUFSIZE];
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_EXECUTOR);

    while ((c = getopt_long(argc, argv, "dvnKIf:D:N:VxL:hFOV1gMWlC::", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'l':
            LEGACY_OUTPUT = true;
            break;

        case 'f':

            if (optarg && strlen(optarg) < 5)
            {
                Log(LOG_LEVEL_ERR, " -f used but argument '%s' incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            LogSetGlobalLevel(LOG_LEVEL_DEBUG);
            break;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            LogSetGlobalLevel(LOG_LEVEL_INFO);
            break;

        case 'v':
            LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
            NO_FORK = true; // TODO: really?
            break;

        case 'n':
            DONTDO = true;
            IGNORELOCK = true;
            EvalContextHeapAddHard(ctx, "opt_dry_run");
            break;

        case 'L':
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            if (putenv(xstrdup(ld_library_path)) != 0)
            {
            }
            break;

        case 'W':
            WINSERVICE = false;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'O':
            ONCE = true;
            NO_FORK = true;
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            PrintHelp("cf-execd", OPTIONS, HINTS, true);
            exit(0);

        case 'M':
            {
                Writer *out = FileWriter(stdout);
                ManPageWrite(out, "cf-execd", time(NULL),
                             CF_EXECD_SHORT_DESCRIPTION,
                             CF_EXECD_MANPAGE_LONG_DESCRIPTION,
                             OPTIONS, HINTS,
                             true);
                FileWriterDetach(out);
                exit(EXIT_SUCCESS);
            }

        case 'x':
            Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
            exit(0);

        case 'C':
            if (!GenericAgentConfigParseColor(config, optarg))
            {
                exit(EXIT_FAILURE);
            }
            break;

        default:
            PrintHelp("cf-execd", OPTIONS, HINTS, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}
示例#2
0
/*************************************************************************************************
 *************************************************************************************************
 *
 *  Start of Main Function
 *
 *************************************************************************************************
 ************************************************************************************************/
int main (int argc, char *argv[])
{
  init_salute();

  ofstream null_ostream("/dev/null"); // must stay live for entire scope, or crash when writing
  TheSilenceOfTheArmadillos(null_ostream);

  TrackProgress my_progress;  
  DumpStartingStateOfProgram (argc,argv,my_progress);

  if(argc < 2)
  {
      PrintHelp();
  }

  for(int i = 1; i < argc; ++i)
  {
	  string s = argv[i];
	  if(s == "-" || s == "--")
	  {
	      cerr << "ERROR: command line input \"-\" must be followed by a short option name (a letter) and \"--\" must be followed by a long option name." << endl; 
		  exit ( EXIT_FAILURE );
	  }
	  else if(s == "-?" || s == "-h" || s == "--help")
	  {
	      PrintHelp();
	  }
  }

  ValidateOpts validater;
  validater.Validate(argc, argv);

  char** argv2 = new char*[argc];
  int datind = TrapAndDeprecateOldArgs(argc, argv, argv2);

  OptArgs opts;
  opts.ParseCmdLine(argc, (const char**)argv2);

  for(int k = 0; k < argc ; ++k)
  {
	  delete [] argv2[k];
  }
  delete [] argv2;
   
  Json::Value json_params;
  CommandLineOpts inception_state;
  inception_state.SetOpts(opts, json_params);

  if(datind < 0) // there is no "--dat-source-directory"
  {
	  inception_state.sys_context.dat_source_directory = argv[argc - 1];
	  cout << "dat_source_directory = " << inception_state.sys_context.dat_source_directory << endl;
  }

  inception_state.PostProcessArgs(opts);

  SeqListClass my_keys;
  ImageSpecClass my_image_spec;
  SlicedPrequel my_prequel_setup;

  SetUpOrLoadInitialState(inception_state, my_keys, my_progress, my_image_spec, my_prequel_setup);
  
  // Start logging process parameters & timing now that we have somewhere to log
  my_progress.InitFPLog(inception_state);

  // Write processParameters.parse file now that processing is about to begin
  my_progress.WriteProcessParameters(inception_state);

  // Do background model
  RealImagesToWells ( opts, inception_state, my_keys, my_progress, my_image_spec, my_prequel_setup);

  my_progress.ReportState ("Analysis (wells file only) Complete");

  exit (ExitCode::GetExitCode());
}
示例#3
0
int main( int argc, char *argv[])
{
double (* f)();
void *MsgCtx = 0; /* This is the context of the message-passing operation */
void *outctx;
int  reps,len,error_flag;
double t;
int  first,last,incr, svals[3];
char     units[32];         /* Name of units of length */

MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &__NUMNODES );
MPI_Comm_rank( MPI_COMM_WORLD, &__MYPROCID );
;
strcpy( units, "" );

if (SYArgHasName( &argc, argv, 1, "-help" )) {
  return PrintHelp( argv );
  }

if (__NUMNODES < 2) {
    fprintf( stderr, "Must run goptest with at least 2 nodes\n" );
    return 1;
    }

/* Get the output context */
outctx = SetupGraph( &argc, argv );
if (SYArgHasName( &argc, argv, 1, "-noinfo" ))    doinfo    = 0;
if (SYArgHasName( &argc, argv, 1, "-nohead" ))    doheader  = 0;
if (SYArgHasName( &argc, argv, 1, "-notail" ))    dotail    = 0;

reps          = DEFAULT_REPS;
error_flag    = 0;
if (SYArgHasName( &argc, argv, 0, "-sync") ) {
    svals[0] = svals[1] = svals[2] = 0;
    }
else {
    /* We use fewer values because we are generating them on the same line. */
    svals[0]      = 0;
    svals[1]      = 1024;
    svals[2]      = 256;
    }

SYArgGetIntVec( &argc, argv, 1, "-size", 3, svals );
nsizes = SYArgGetIntList( &argc, argv, 1, "-sizelist", MAX_SIZE_LIST, 
                          sizelist );
/* We ALWAYS use sizelist */
if (nsizes == 0) {
    /* Generate the size list from the svals list */
    sizelist[0] = svals[0];
    for (nsizes=1; sizelist[nsizes-1] < svals[1] && nsizes<MAX_SIZE_LIST; 
	 nsizes++) {
	sizelist[nsizes] = sizelist[nsizes-1] + svals[2];
	}
    if (sizelist[nsizes] > svals[1]) nsizes--;
    }

SYArgGetInt(    &argc, argv, 1, "-reps", &reps );
if (SYArgHasName( &argc, argv, 1, "-autoreps" ))  AutoReps  = 1;
if (SYArgGetDouble( &argc, argv, 1, "-tgoal", &Tgoal )) {
    AutoReps = 1;
    if (TgoalMin > 0.1 * Tgoal) TgoalMin = 0.1 * Tgoal;
    }
SYArgGetDouble( &argc, argv, 1, "-rthresh", &repsThresh );

f      = GetGOPFunction( &argc, argv, test_name, units );
MsgCtx = GOPInit( &argc, argv );
first = svals[0];
last  = svals[1];
incr  = svals[2];
if (incr == 0) incr = 1;

/*
   Finally, we are ready to run the tests.  We want to report times as
   the times for a single link, and rates as the aggregate rate.
   To do this, we need to know how to scale both the times and the rates.

   Times: scaled by the number of one-way trips measured by the base testing
   code.  This is often 2 trips, or a scaling of 1/2.

   Rates: scaled by the number of simultaneous participants (as well as
   the scaling in times).  Compute the rates based on the updated time, 
   then multiply by the number of participants.  Note that, for a single
   sender, time and rate are inversely proportional (that is, if TimeScale 
   is 0.5, RateScale is 2.0).

 */

if (doinfo && doheader &&__MYPROCID == 0) {
    HeaderForGopGraph( outctx, test_name, (char *)0, units );
    }
time_function(reps,first,last,incr,f,outctx,MsgCtx);

/* 
   Generate the "end of page".  This allows multiple graphs on the
   same plot 
 */
if (doinfo && dotail && __MYPROCID == 0) 
    EndPageGraph( outctx );

MPI_Finalize();
return 0;
}
示例#4
0
void XYUVHeader::Run(const ::options & options) {

    // If help has been requested, print it and quit.
    if (options.print_help) {
        PrintHelp();
        return;
    }

    // Otherwise do something useful.
#ifdef INSTALL_FORMATS_PATH
    // Load base formats from installation path
    config_manager_.load_configurations(INSTALL_FORMATS_PATH);
#endif

    // Load all additional formats supplied on the command line.
    for (const auto & path : options.additional_config_directories) {
        config_manager_.load_configurations(path);
    }

    // If a list of all formats has been requested, print it and quit.
    if (options.list_all_formats) {
        PrintAllFormats();
        return;
    }

    // Try to aquire each output stream.
    bool detect_concatinate = options.concatinate;
    std::vector<std::string> output_names;

    if (options.writeout) {
        // Make a set of output names to do argument validation.
        std::unordered_set<std::string> out_name_set;

        if ( options.output_name.size() == 0 ) {
            // If concatinating, use first file name as output.
            if (detect_concatinate) {
                std::string out_path = strip_suffix(options.input_files[0]) + ".xyuv";
                out_name_set.emplace(out_path);
                output_names.emplace_back(out_path);
            }
            else {
                for (const auto & in_file : options.input_files ) {
                    std::string out_path = strip_suffix(in_file) + ".xyuv";

                    out_name_set.insert(out_path);
                    output_names.emplace_back(out_path);
                }
            }
        }
        else {
            for (const auto & out_path : options.output_name ) {
                out_name_set.insert(out_path);
                output_names.emplace_back(out_path);
            }
        }

        // Check that no two output files overwrite one another.
        if (out_name_set.size() != output_names.size()) {
            throw std::invalid_argument("The same output name is given more than once. This is illegal for one invocation of the program.");
        }

        // Check that no input file is the same as an output file.
        // We don't account for relative paths etc here, but we won't care for now.
        for (const auto & in_path : options.input_files) {
            if (out_name_set.find(in_path) != out_name_set.end()) {
                throw std::invalid_argument("File '" + in_path + "' given as both an input and an output file, this is illegal.");
            }
        }

        // Check that the number of output files matches the number of input files
        // or one.
        if (output_names.size() != 1 && output_names.size() != options.input_files.size() ) {
            throw std::invalid_argument("If supplied, the number of output files must exactly match the number of input files or one.");
        }

        if (output_names.size() == 1 && options.input_files.size() > 1) {
            detect_concatinate = true;
        }
    }

    // Check validity of formats:
    std::vector<xyuv::format_template> format_templates;
    std::vector<xyuv::chroma_siting> sitings;
    std::vector<xyuv::conversion_matrix> matrices;

    for (const auto & format_template : options.output_formats ) {
        try {
            // Try to load the format-template from file.
            format_templates.push_back(xyuv::config_manager::load_format_template(format_template));
        } catch (std::runtime_error & e) {
            try {
                // If that failed look it up in the config manager.
                format_templates.push_back(config_manager_.get_format_template(format_template));
            } catch (std::exception e2) {
                std::string err_msg = std::string("Could not load format template ") + format_template +
                        ": " + e.what() + " and " + e2.what() + ". Please check the spelling of the argument.";
                throw std::invalid_argument(std::string(err_msg));
            }
        }
    }
    if (format_templates.size() != 1 && format_templates.size() != options.input_files.size()) {
        throw std::invalid_argument("The number of format templates must exactly match the number of input files or one (which implies all input files have the same format).");
    }

    for (const auto & siting : options.output_siting ) {
        try {
            // Try to load the siting from file.
            sitings.push_back(xyuv::config_manager::load_chroma_siting(siting));
        } catch (std::runtime_error & e) {
            try {
                // If that failed look it up in the config manager.
                sitings.push_back(config_manager_.get_chroma_siting(siting));
            } catch (std::exception e2) {
                std::string err_msg = std::string("Could not load chroma siting ") + siting +
                                      ": " + e.what() + " and " + e2.what() + ". Please check the spelling of the argument.";
                throw std::invalid_argument(std::string(err_msg));
            }
        }
    }
    if (sitings.size() != 1 && sitings.size() != options.input_files.size()) {
        throw std::invalid_argument("The number of chroma sitings must exactly match the number of input files or one (which implies all input files have the same chroma siting).");
    }

    for (const auto & matrix : options.output_matrix ) {
        try {
            // Try to load the matrix from file.
            matrices.push_back(xyuv::config_manager::load_conversion_matrix(matrix));
        } catch (std::runtime_error & e) {
            try {
                // If that failed look it up in the config manager.
                matrices.push_back(config_manager_.get_conversion_matrix(matrix));
            } catch (std::exception e2) {
                std::string err_msg = std::string("Could not load conversion matrix ") + matrix +
                                      ": " + e.what() + " and " + e2.what() + ". Please check the spelling of the argument.";
                throw std::invalid_argument(std::string(err_msg));
            }
        }
    }
    if (matrices.size() != 1 && matrices.size() != options.input_files.size()) {
        throw std::invalid_argument("The number of conversion matrices must exactly match the number of input files or one (which implies all input files have the same conversion matrix).");
    }

    // Do some extra checking for the chroma siting, which must match the subsampling mode of the format.
    if (sitings.size() == 1 && format_templates.size() > 1) {
        for (std::size_t i = 0; i < format_templates.size(); i++) {
            if (!(sitings[0].subsampling == format_templates[i].subsampling)) {
                throw std::invalid_argument("Sub-sampling mismatch, for format template #"
                                            + std::to_string(i) + "'" + options.output_formats[i] + "'"
                                            + " corresponding chroma siting expects subsampling mode: "
                                            + std::to_string(sitings[0].subsampling.macro_px_w) + "x" + std::to_string(sitings[0].subsampling.macro_px_h)
                                            + " got: "
                                            + std::to_string(format_templates[i].subsampling.macro_px_w) + "x" + std::to_string(format_templates[i].subsampling.macro_px_h)
                );
            }
        }
    }

    if (options.display && options.input_files.size() != 1 ) {
        throw std::invalid_argument("--display only supported for a single input.");
    }

    if (options.input_files.size() == 0) {
        throw std::logic_error("Missing input files.");
    }

    if (options.input_files.size() > 0 && options.image_w * options.image_h == 0) {
        throw std::logic_error("Image size must be non-zero.");
    }

    std::unique_ptr<std::ofstream> fout;
    if (detect_concatinate) {
        fout.reset(new std::ofstream(output_names[0], std::ios::binary | std::ios::app ));
        if (!(*fout)) {
            throw std::runtime_error("Could not open output file: '" + output_names[0] + "' for writing");
        }
    }

    // At this point everything looks good :) Lets load some formats.
    for ( std::size_t i = 0; i < options.input_files.size(); i++) {
        xyuv::format target_format = xyuv::create_format(
                options.image_w,
                options.image_h,
                format_templates.size() == 1 ? format_templates[0] : format_templates[i],
                matrices.size() == 1 ? matrices[0] : matrices[i],
                sitings.size() == 1 ? sitings[0] : sitings[i]
        );

        xyuv::frame frame = LoadConvertFrame(target_format, options.input_files[i]);

        // If --flip-y is set then change the image origin to the inverse.
        if (options.flip_y) {
            switch (frame.format.origin) {
                case xyuv::image_origin::UPPER_LEFT:
                    frame.format.origin = xyuv::image_origin::LOWER_LEFT;
                    break;
                case xyuv::image_origin::LOWER_LEFT:
                    frame.format.origin = xyuv::image_origin::UPPER_LEFT;
                    break;
                default:
                    break;
            }
        }

        if (options.writeout) {
            if (options.concatinate) {
                // Append file at end of concatinated string.
                xyuv::write_frame(*fout, frame);
            }
            else {
                try {
                    WriteFrame(frame, output_names[i]);
                } catch (std::exception & e) {
                    std::cout << "[Warning] Error occured while writing file '" <<
                                 output_names[i] << "'\n   " <<
                                 e.what() << "\n   Skipping file." << std::endl;
                }
            }
        }

        if (options.display) {
            Display(frame);
        }
    }
}
示例#5
0
uint8_t RNETA_ParseCommand(const unsigned char *cmd, bool *handled, const CLS1_StdIOType *io) {
  uint8_t res = ERR_OK;
  const uint8_t *p;
  uint16_t val16;
  uint8_t val8;

  if (UTIL1_strcmp((char*)cmd, (char*)CLS1_CMD_HELP)==0 || UTIL1_strcmp((char*)cmd, (char*)"rapp help")==0) {
    PrintHelp(io);
    *handled = TRUE;
  } else if (UTIL1_strcmp((char*)cmd, (char*)CLS1_CMD_STATUS)==0 || UTIL1_strcmp((char*)cmd, (char*)"rapp status")==0) {
    *handled = TRUE;
    return PrintStatus(io);
  } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp saddr", sizeof("rapp saddr")-1)==0) {
    p = cmd + sizeof("rapp saddr")-1;
    *handled = TRUE;
    if (UTIL1_ScanHex16uNumber(&p, &val16)==ERR_OK) {
      (void)RNWK_SetThisNodeAddr((RNWK_ShortAddrType)val16);
    } else {
      CLS1_SendStr((unsigned char*)"ERR: wrong address\r\n", io->stdErr);
      return ERR_FAILED;
    }
  } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp send val", sizeof("rapp send val")-1)==0) {
    p = cmd + sizeof("rapp send val")-1;
    *handled = TRUE;
    if (UTIL1_ScanDecimal8uNumber(&p, &val8)==ERR_OK) {
      (void)RAPP_SendPayloadDataBlock(&val8, sizeof(val8), (uint8_t)RAPP_MSG_TYPE_DATA, APP_dstAddr, RPHY_PACKET_FLAGS_NONE); /* only send low byte */
    } else {
      CLS1_SendStr((unsigned char*)"ERR: wrong number format\r\n", io->stdErr);
      return ERR_FAILED;
    }
  } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp daddr", sizeof("rapp daddr")-1)==0) {
    p = cmd + sizeof("rapp daddr")-1;
    *handled = TRUE;
    if (UTIL1_ScanHex16uNumber(&p, &val16)==ERR_OK) {
      APP_dstAddr = val16;
    } else {
      CLS1_SendStr((unsigned char*)"ERR: wrong address\r\n", io->stdErr);
      return ERR_FAILED;
    }
#if RNET_CONFIG_REMOTE_STDIO
  } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp send", sizeof("rapp send")-1)==0) {
    unsigned char buf[32];
    RSTDIO_QueueType queue;
    
    if (UTIL1_strncmp((char*)cmd, (char*)"rapp send in", sizeof("rapp send in")-1)==0) {
      queue = RSTDIO_QUEUE_TX_IN;
      cmd += sizeof("rapp send in");
    } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp send out", sizeof("rapp send out")-1)==0) {
      queue = RSTDIO_QUEUE_TX_OUT;      
      cmd += sizeof("rapp send out");
    } else if (UTIL1_strncmp((char*)cmd, (char*)"rapp send err", sizeof("rapp send err")-1)==0) {
      queue = RSTDIO_QUEUE_TX_ERR;      
      cmd += sizeof("rapp send err");
    } else {
      return ERR_OK; /* not handled */
    }
    UTIL1_strcpy(buf, sizeof(buf), cmd);
    UTIL1_chcat(buf, sizeof(buf), '\n');
    buf[sizeof(buf)-2] = '\n'; /* have a '\n' in any case */
    if (RSTDIO_SendToTxStdio(queue, buf, UTIL1_strlen((char*)buf))!=ERR_OK) {
      CLS1_SendStr((unsigned char*)"failed!\r\n", io->stdErr);
    }
    *handled = TRUE;
#endif
  }
  return res;
}
示例#6
0
// ------------------------------------------------------------------------------------------------
int PrintHelpAndExit(int _argNum, int _argc, char* _argv[], Options* _outOptions, size_t _byteOffset)
{
    PrintHelp(0);
    return 1;
}
TCGbool TCGClient::ParseArgv(TCGint argc, TCGchar* argv[], stCmdArgs& args)
{
    for (TCGint i=1; i<argc; ++i)
    {
        const TCGchar* arg = argv[i];
        if (!strcmp(arg, "--verbose"))
        {
            args.verbose = TCG_TRUE;
        }
        else if (!strcmp(arg, "--no-compress"))
        {
            args.compressedFile = TCG_FALSE;
        }
        else if (!strcmp(arg, "--compress"))
        {
            args.compressedFile = TCG_TRUE;
        }
        else if (!strcmp(arg, "--dumpPath"))
        {
            sprintf(args.strDumpPath, "%s", argv[++i]);
        }
        else if (!strcmp(arg, "--runFile"))
        {
            sprintf(args.strRunFile, "%s", argv[++i]);
        }
        else if (!strcmp(arg, "--retrace"))
        {
            args.retracedFile = TCG_TRUE;
        }
        else if (!strcmp(arg, "--showFPS"))
        {
            args.showFPS = TCG_TRUE;
        }
        else if (!strcmp(arg, "--showFrameTime"))
        {
            args.showFrameTime = TCG_TRUE;
        }
        else if (!strcmp(arg, "--targetkey"))
        {
            args.readterminal = TCG_TRUE;
        }
        else if (!strcmp(arg, "--width"))
        {
            args.width = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--height"))
        {
            args.height = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--swapInterval"))
        {
            args.swapInterval = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--start"))
        {
            args.start = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--end"))
        {
            args.end = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--runFrames"))
        {
            args.runFrames = atoi(argv[++i]);
        }
        else if (!strcmp(arg, "--dumpDraw"))
        {
            args.dumpDraw = TCG_TRUE;
        }
        else if (!strcmp(arg, "--dumpFrame"))
        {
            args.dumpFrame = TCG_TRUE;
        }
        else if (!strcmp(arg, "--finish"))
        {
            args.finish = TCG_TRUE;
        }
        else if (!strcmp(arg, "--swapbuf"))
        {
            args.swapbuf= TCG_TRUE;
        }
        else if (!strcmp(arg, "--rendertime"))
        {
            args.renderingtime= TCG_TRUE;
        }
        else if (!strcmp(arg, "--zoom"))
        {
            args.zoom= TCG_TRUE;
        }
        else if (!strcmp(arg, "--analyze"))
        {
            args.analyze = TCG_TRUE;
        }
        else if (!strcmp(arg, "--default-context"))
        {
            args.default_context= TCG_TRUE;
        }
        else if (!strcmp(arg, "--fps"))
        {
            if (!(i + 1 < argc))
            {
                PrintHelp();
                return TCG_FALSE;
            }
            if (!from_string<TCGint>(args.fpsinterval, argv[i+1]) || args.fpsinterval < 0)
            {
                TCGLOG(TCG_ERROR, TCG_CLIENT_OS, "%s is not a valid fps interval\n\n", argv[i+1]);
                return TCG_FALSE;
            }
            ++i;
        }
        else if (!strcmp(arg, "--config"))
        {
            if (!(i + 1 < argc))
            {
                PrintHelp();
                return TCG_FALSE;
            }
            if (!from_string<EGLint>(args.configid, argv[i+1]))
            {
                TCGLOG(TCG_ERROR, TCG_CLIENT_OS, "'%s' is not a valid config id\n\n.", argv[i+1]);
                return TCG_FALSE;
            }
            ++i;
        }
        else if (!strcmp(arg, "--patchid"))
        {
            if (!(i + 1 < argc))
            {
                PrintHelp();
                return TCG_FALSE;
            }
            if (!from_string<EGLenum>(args.patchid, argv[i+1]))
            {
                TCGLOG(TCG_ERROR, TCG_CLIENT_OS, "'%s' is not a valid patch id\n\n.", argv[i+1]);
                return TCG_FALSE;
            }
            ++i;
        }
        else if (!strcmp(arg, "--help")||!strcmp(arg, "-h")||(arg[0] == '-'))
        {
            PrintHelp();
            return TCG_FALSE;
        }
    }

    return TCG_TRUE;
}
示例#8
0
int main (int argc, char *argv[])
{
#ifndef _DEBUG
	if(argc == 1)
	{
		PrintHelp();
		return 0;
	}
	if(argc != 4)
	{
		printf("Too few arguments provided.  Specify a patch file to create and the updated and original files for comparison.");
		PrintHelp();
		return 0;
	}
#endif

	FILE *updated, *original, *patch;
#if _DEBUG
	updated = fopen("UWASA1patched.BIN", "rb");
#else
	updated = fopen(argv[2], "rb");
#endif
	if(!updated)
	{
		printf("Error opening updated file %s", argv[2]);
		return 0;
	}

#if _DEBUG
	original = fopen("UWASA1.BIN", "rb");
#else
	original = fopen(argv[3], "rb");
#endif
	if(!original)
	{
		printf("Error opening original file %s", argv[3]);
		return 0;
	}

#if _DEBUG
	patch = fopen("uwasa_1.ppf", "wb");
#else
	patch = fopen(argv[1], "wb");
#endif
	if(!patch)
	{
		printf("Error opening patch file %s", argv[1]);
		return 0;
	}

	PatchHeader header;
	header.Serialize(patch);

	PatchData pd;
	u8 updbyte, origbyte;
	fread(&updbyte, 1, 1, updated);
	fread(&origbyte, 1, 1, original);
	while(!feof(updated))
	{
		if(!feof(original))
		{
			if(origbyte != updbyte)
			{
				if(pd.command != 0)
				{
					printf("Critical Error:  Difference found, but command is add.\n");
					return 0;
				}
				if(pd.size == 0) pd.offset = ftell(original) - 1;
				pd.data[pd.size] = updbyte;
				pd.size++;
				if(pd.size == PATCH_DATA_MAXSIZE)
				{
					pd.Serialize(patch);
					pd.Reset();
				}
			}
			else if(pd.size > 0)
			{
				pd.Serialize(patch);
				pd.Reset();
			}
			fread(&origbyte, 1, 1, original);
			fread(&updbyte, 1, 1, updated);
		}
		else
		{
			// process remainder of updated data as additions
			if(pd.size > 0)
			{
				pd.Serialize(patch);
			}
			pd.Reset();
			pd.command = PATCH_CMD_ADD;

			while(!feof(updated))
			{
				pd.data[pd.size] = updbyte;
				pd.size++;
				if(pd.size == PATCH_DATA_MAXSIZE)
				{
					pd.Serialize(patch);
					pd.Reset();
					pd.command = PATCH_CMD_ADD;
				}
				fread(&updbyte, 1, 1, updated);
			}
			if(pd.size > 0 && pd.size < PATCH_DATA_MAXSIZE)
			{
				pd.Serialize(patch);
			}
		}
	}
	if(pd.size > 0 && pd.size < PATCH_DATA_MAXSIZE)
	{
		pd.Serialize(patch);
	}

	fclose(patch);
	fclose(updated);
	fclose(original);

	return 0;
}
示例#9
0
GenericAgentConfig *CheckOpts(int argc, char **argv)
{
    extern char *optarg;
    char ld_library_path[CF_BUFSIZE];
    int optindex = 0;
    int c;
    GenericAgentConfig *config = GenericAgentConfigNewDefault(AGENT_TYPE_SERVER);

    while ((c = getopt_long(argc, argv, "dvIKf:D:N:VSxLFMhAlC::", OPTIONS, &optindex)) != EOF)
    {
        switch ((char) c)
        {
        case 'l':
            LEGACY_OUTPUT = true;
            break;

        case 'f':

            if (optarg && (strlen(optarg) < 5))
            {
                Log(LOG_LEVEL_ERR, " -f used but argument '%s' incorrect", optarg);
                exit(EXIT_FAILURE);
            }

            GenericAgentConfigSetInputFile(config, GetWorkDir(), optarg);
            MINUSF = true;
            break;

        case 'd':
            LogSetGlobalLevel(LOG_LEVEL_DEBUG);
            NO_FORK = true;

        case 'K':
            IGNORELOCK = true;
            break;

        case 'D':
            config->heap_soft = StringSetFromString(optarg, ',');
            break;

        case 'N':
            config->heap_negated = StringSetFromString(optarg, ',');
            break;

        case 'I':
            LogSetGlobalLevel(LOG_LEVEL_INFO);
            break;

        case 'v':
            LogSetGlobalLevel(LOG_LEVEL_VERBOSE);
            NO_FORK = true;
            break;

        case 'F':
            NO_FORK = true;
            break;

        case 'L':
            Log(LOG_LEVEL_VERBOSE, "Setting LD_LIBRARY_PATH to '%s'", optarg);
            snprintf(ld_library_path, CF_BUFSIZE - 1, "LD_LIBRARY_PATH=%s", optarg);
            putenv(ld_library_path);
            break;

        case 'V':
            PrintVersion();
            exit(0);

        case 'h':
            PrintHelp("cf-serverd", OPTIONS, HINTS, true);
            exit(0);

        case 'M':
            {
                Writer *out = FileWriter(stdout);
                ManPageWrite(out, "cf-serverd", time(NULL),
                             CF_SERVERD_SHORT_DESCRIPTION,
                             CF_SERVERD_MANPAGE_LONG_DESCRIPTION,
                             OPTIONS, HINTS,
                             true);
                FileWriterDetach(out);
                exit(EXIT_SUCCESS);
            }

        case 'x':
            Log(LOG_LEVEL_ERR, "Self-diagnostic functionality is retired.");
            exit(0);
        case 'A':
#ifdef HAVE_AVAHI_CLIENT_CLIENT_H
#ifdef HAVE_AVAHI_COMMON_ADDRESS_H
            Log(LOG_LEVEL_NOTICE, "Generating Avahi configuration file.");
            if (GenerateAvahiConfig("/etc/avahi/services/cfengine-hub.service") != 0)
            {
                exit(1);
            }
            cf_popen("/etc/init.d/avahi-daemon restart", "r", true);
            Log(LOG_LEVEL_NOTICE, "Avahi configuration file generated successfuly.");
            exit(0);
#endif
#endif
            Log(LOG_LEVEL_ERR, "Generating avahi configuration can only be done when avahi-daemon and libavahi are installed on the machine.");
            exit(0);

        case 'C':
            if (!GenericAgentConfigParseColor(config, optarg))
            {
                exit(EXIT_FAILURE);
            }
            break;

        default:
            PrintHelp("cf-serverd", OPTIONS, HINTS, true);
            exit(1);

        }
    }

    if (!GenericAgentConfigParseArguments(config, argc - optind, argv + optind))
    {
        Log(LOG_LEVEL_ERR, "Too many arguments");
        exit(EXIT_FAILURE);
    }

    return config;
}
// ---------------------------------------------------------
// CPosPSYListView::HandleKeyEventL
// 
// (other items were commented in a header).
// ---------------------------------------------------------
//
void CPosPSYListView::HandleKeyEventL(
    TKeyCode aKey)
    {
    _LIT(KAlreadyRunning, "\r\nAlready running.");
	_LIT(KNoTestsRunning, "\r\nNo test running.");

	if (aKey == EKeyRightArrow)
        {
        iViewManager->SwitchViewL(KPSYSettingsView);
        }
	else if (IsHelpRequested(aKey))
        {
        PrintHelp();
        }

    if (iReadBuf.Count() < KMaxBufSize)
        {
        if (IsNumeric(aKey))
   		    {
			if (iReadBuf.Count() == 0) 
				{
				_LIT(KMsg, "\r\nPSY: ");
				iConsole->Printf(KMsg);
				}
			_LIT(KKey, "%c");
			TBuf<10> buf;
			buf.Format(KKey, aKey);
			iConsole->Printf(buf);
            iReadBuf.Append((static_cast<TInt> (aKey)) - '0');
   		    }
        else if ((aKey == 'R') || (aKey == 'r'))
            {
			if (iTestHandler->TestsRunning())
				{
				iConsole->Printf(KAlreadyRunning);				
				}
			else
				{
				iTestHandler->StartPSYTesterL(KTestAllPSYs);
				}
			}
		else if ((aKey == 'C') || (aKey == 'c'))
   		    {
			if (iTestHandler->TestsRunning())
				{
				iTestHandler->Cancel();
				_LIT(KMsg, "\r\nTests canceled.");
				iConsole->Printf(KMsg);
				}
			else 
				{
				iConsole->Printf(KNoTestsRunning);				
				}
			}
        else if (aKey == 'L' ||			// "L"
				 aKey == 'l')			// "l"
            {
            iCurrentIndex = 0;
            iTestHandler->UpdatePSYListL();
            iConsole->ClearScreen();
            ListPSYs(KListStart);
            }
        else if (aKey == 'X' ||	
				 aKey == 'x' ||
				 aKey == EKeyDevice1)		// right softkey (S60)
            {
            CActiveScheduler::Stop();
			}
        else if (aKey == 'F' ||       // "F"
				 aKey == 'f' ||		  // "f"
				 aKey == EKeyUpArrow) // joy-stick up (S60)
            {
            iConsole->ClearScreen();
            ListPSYs(KListPrevious);
			}
        else if (aKey == 'N' ||			// "N"
				 aKey == 'n' ||			// "n"
				 aKey == EKeyDownArrow) // joy-stick down (S60)
            {
            iConsole->ClearScreen();
            ListPSYs(KListNext);
			}
        else if (aKey == 'U' ||			// "U"
				 aKey == 'u')			// "u"
            {
            iReadBuf.Reset();
            iCurrentIndex = 0;
            iTestHandler->UpdatePSYListL();
            iConsole->ClearScreen();
            ListPSYs(KListStart);
			}
		else if (aKey == EKeyEnter || // enter
				 aKey == EKeyDevice3) // stick down (S60)
            {
			if (iTestHandler->TestsRunning())
				{
				iConsole->Printf(KAlreadyRunning);
				}
			else 
				{
				TInt number = ParseBufferL();
				iReadBuf.Reset();

				if (number > 0) //Because readbuffer can't be flushed
					{
					iTestHandler->StartPSYTesterL(number);
					}
				}
            }
        else
            {
            //Ignore character
            }    
        }
    else
        {
        iReadBuf.Reset();
        }
    }
示例#11
0
int main(int argc, char* argv[]) {
  int retval = 0;
  int i;

  char* progname = strrchr(argv[0], '/');
  if (progname)
    progname++;
  else
    progname = argv[0];

  if (VbArchInit()) {
    fprintf(stderr, "Failed to initialize\n");
    return -1;
  }

  /* If no args specified, print all params */
  if (argc == 1)
    return PrintAllParams(0);
  /* --all or -a prints all params including normally hidden ones */
  if (!strcasecmp(argv[1], "--all") || !strcmp(argv[1], "-a"))
    return PrintAllParams(1);

  /* Print help if needed */
  if (!strcasecmp(argv[1], "-h") || !strcmp(argv[1], "-?")) {
    PrintHelp(progname);
    return 0;
  }

  /* Otherwise, loop through params and get/set them */
  for (i = 1; i < argc && retval == 0; i++) {
    char* has_set = strchr(argv[i], '=');
    char* has_expect = strchr(argv[i], '?');
    char* name = strtok(argv[i], "=?");
    char* value = strtok(NULL, "=?");
    const Param* p;

    /* Make sure args are well-formed. '' or '=foo' or '?foo' not allowed. */
    if (!name || has_set == argv[i] || has_expect == argv[i]) {
      fprintf(stderr, "Poorly formed parameter\n");
      PrintHelp(progname);
      return 1;
    }
    if (!value)
      value=""; /* Allow setting/checking an empty string ('foo=' or 'foo?') */
    if (has_set && has_expect) {
      fprintf(stderr, "Use either = or ? in a parameter, but not both.\n");
      PrintHelp(progname);
      return 1;
    }

    /* Find the parameter */
    p = FindParam(name);
    if (!p) {
      fprintf(stderr, "Invalid parameter name: %s\n", name);
      PrintHelp(progname);
      return 1;
    }

    if (i > 1)
      printf(" ");  /* Output params space-delimited */
    if (has_set)
      retval = SetParam(p, value);
    else if (has_expect)
      retval = CheckParam(p, value);
    else
      retval = PrintParam(p);
  }

  return retval;
}
示例#12
0
byte MCP4728_ParseCommand(const unsigned char *cmd, bool *handled, const CLS1_StdIOType *io) {
  const unsigned char *p;

  if (UTIL1_strcmp((char*)cmd, CLS1_CMD_HELP)==0 || UTIL1_strcmp((char*)cmd, "MCP4728 help")==0) {
    *handled = TRUE;
    return PrintHelp(io);
  } else if ((UTIL1_strcmp((char*)cmd, CLS1_CMD_STATUS)==0) || (UTIL1_strcmp((char*)cmd, "MCP4728 status")==0)) {
    *handled = TRUE;
    return PrintStatus(io);
  } else if (UTIL1_strcmp((char*)cmd, "MCP4728 reset")==0) {
    *handled = TRUE;
    if (MCP4728_Reset()!=ERR_OK) {
      return ERR_FAILED;
    } else {
      return ERR_OK;
    }
  } else if (UTIL1_strcmp((char*)cmd, "MCP4728 wakeup")==0) {
    *handled = TRUE;
    if (MCP4728_Wakeup()!=ERR_OK) {
      return ERR_FAILED;
    } else {
      return ERR_OK;
    }
  } else if (UTIL1_strcmp((char*)cmd, "MCP4728 update")==0) {
    *handled = TRUE;
    if (MCP4728_Update()!=ERR_OK) {
      return ERR_FAILED;
    } else {
      return ERR_OK;
    }
  } else if (UTIL1_strncmp((char*)cmd, "MCP4728 fastwrite all ", sizeof("MCP4728 fastwrite all ")-1)==0) {
    uint16_t dac[4];
    uint8_t pd[4];
    int i;
    
    *handled = TRUE;
    p = cmd+sizeof("MCP4728 fastwrite all ")-1;
    for(i=0;i<4;i++) { /* init */
      dac[i] = 0;
      pd[i] = 0;
    }
    for(i=0;i<4;i++) {
      if (UTIL1_ScanHex16uNumber(&p, &dac[i])!=ERR_OK) {
        break;
      }
      dac[i] &= MCP4728_MAX_DAC_VAL; /* ensure it is 12 bits */
    }
    if (i!=4) {
      CLS1_SendStr((unsigned char*)"**** Not enough values, 4 expected!\r\n", io->stdErr);
      return ERR_FAILED;
    }
    if (MCP4728_FastWriteAllDAC(dac, sizeof(dac), pd, sizeof(pd))!=ERR_OK) {
      CLS1_SendStr((unsigned char*)"**** FastWrite failed.\r\n", io->stdErr);
      return ERR_FAILED;
    } else {
      return ERR_OK;
    }
  } else if (UTIL1_strncmp((char*)cmd, "MCP4728 fastwrite ", sizeof("MCP4728 fastwrite ")-1)==0) {
    /* e.g. MCP4728 fastwrite 2 0x512 */
    uint16_t dac=0;
    uint8_t channel=0;

    *handled = TRUE;
    p = cmd+sizeof("MCP4728 fastwrite ")-1;
    if (UTIL1_ScanDecimal8uNumber(&p, &channel)!=ERR_OK || channel>3) {
      CLS1_SendStr((unsigned char*)"**** error parsing channel, must be 0, 1, 2 or 3!\r\n", io->stdErr);
      return ERR_FAILED;
    }
    if (UTIL1_ScanHex16uNumber(&p, &dac)!=ERR_OK || dac>MCP4728_MAX_DAC_VAL) {
      CLS1_SendStr((unsigned char*)"**** error parsing 12bit hex value, must start with 0x!\r\n", io->stdErr);
      return ERR_FAILED;
    }
    dac &= MCP4728_MAX_DAC_VAL; /* ensure it is 12 bits */
    if (MCP4728_FastWriteDAC(channel, dac)!=ERR_OK) {
      CLS1_SendStr((unsigned char*)"**** Write channel DAC failed!\r\n", io->stdErr);
      return ERR_FAILED;
    } else {
      return ERR_OK;
    }
  } else if (UTIL1_strncmp((char*)cmd, "MCP4728 write ", sizeof("MCP4728 write ")-1)==0) {
    uint16_t dac;
    uint8_t ch, res;
    
    *handled = TRUE;
    res = ERR_OK;
    p = cmd+sizeof("MCP4728 write ")-1;
    if (UTIL1_ScanDecimal8uNumber(&p, &ch)!=ERR_OK || ch>3) {
      CLS1_SendStr((unsigned char*)"**** Failed reading channel. Must be 0, 1, 2 or 3\r\n", io->stdErr);
      res = ERR_FAILED;
    } else {
      if (UTIL1_ScanHex16uNumber(&p, &dac)!=ERR_OK) {
        CLS1_SendStr((unsigned char*)"**** Failed DAC value, must start with 0x\r\n", io->stdErr);
        res = ERR_FAILED;
      } else {
        if (MCP4728_WriteDACandEE(ch, dac)!=ERR_OK) {
          CLS1_SendStr((unsigned char*)"**** Write failed.\r\n", io->stdErr);
          res = ERR_FAILED;
        }
      }
    }
    return res;
  }
  return ERR_OK;
}
示例#13
0
int
main(int argc, char **argv)
{
    register afs_int32 code;
    char op[8];
    char name[PR_MAXNAMELEN];
    afs_int32 id, oid = ANONYMOUSID, gid;
    afs_int32 pos;
    unsigned int i;
    int n;
    struct prentry entry;
    prlist alist;
    idlist lid;
    namelist lnames;
    struct hostent *hostinfo;
    struct in_addr *hostaddr;
    afs_int32 *ptr;
    char *foo;
    afs_int32 over;
    char *cell;

#ifdef	AFS_AIX32_ENV
    /*
     * The following signal action for AIX is necessary so that in case of a 
     * crash (i.e. core is generated) we can include the user's data section 
     * in the core dump. Unfortunately, by default, only a partial core is
     * generated which, in many cases, isn't too useful.
     */
    struct sigaction nsa;

    sigemptyset(&nsa.sa_mask);
    nsa.sa_handler = SIG_DFL;
    nsa.sa_flags = SA_FULLDUMP;
    sigaction(SIGSEGV, &nsa, NULL);
#endif
    whoami = argv[0];

    initialize_PT_error_table();

    strcpy(confdir, AFSDIR_CLIENT_ETC_DIRPATH);
    cell = 0;
    n = 1;
    while (n < argc) {
	int arglen = strlen(argv[n]);
	char arg[256];
	lcstring(arg, argv[n], sizeof(arg));
#define IsArg(a) (strncmp (arg,a, arglen) == 0)
	if (IsArg("-testconfdir"))
	    strncpy(confdir, argv[++n], sizeof(confdir));
	else if (IsArg("client"))
	    strncpy(confdir, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confdir));
	else if (IsArg("server"))
	    strncpy(confdir, AFSDIR_SERVER_ETC_DIRPATH, sizeof(confdir));
	else if (IsArg("0") || IsArg("1") || IsArg("2"))
	    security = atoi(argv[n]);
	else if (IsArg("-ignoreexist"))
	    ignoreExist++;
	else if (IsArg("-cell"))
	    cell = argv[++n];
	else {
	    printf
		("Usage is: 'prclient [-testconfdir <dir> | server | client] [0 | 1 | 2] [-ignoreExist] [-cell <cellname>]\n");
	    exit(1);
	}
	n++;
    }

    printf("Using CellServDB file in %s\n", confdir);
    if (security == 0)
	printf("Making unauthenticated connection to prserver\n");

    code = pr_Initialize(security, confdir, cell);
    if (code) {
	afs_com_err(whoami, code, "Couldn't initialize protection library");
	exit(1);
    }

    while (1) {
	char *s;

	printf("pr> ");
	s = fgets(line, sizeof(line), stdin);
	if (s == NULL)
	    break;
	lineProgress = 0;

	code = GetString(op, sizeof(op));
	if (code) {
	    afs_com_err(whoami, PRBADARG,
		    "error reading opcode in line '%s', got '%.*s'", line,
		    sizeof(op), op);
	    exit(1);
	}
	if (strlen(op) == 0)
	    continue;		/* no input */

	if (!strcmp(op, "cr")) {
	    if (GetString(name, sizeof(name)) || GetInt32(&id)
		|| GetInt32(&oid))
		code = PRBADARG;
	    /* use ubik_Call to do the work, finding an up server and handling
	     * the job of finding a sync site, if need be */
	    else
		code = ubik_PR_INewEntry(pruclient, 0, name, id, oid);
	    if (CodeOk(code))
		afs_com_err(whoami, code, "on %s %s %d %d", op, name, id, oid);
	} else if (!strcmp(op, "sf")) {
	    afs_int32 mask, access, gq, uq;
	    if (GetInt32(&id) || GetXInt32(&mask) || GetXInt32(&access)
		|| GetInt32(&gq) || GetInt32(&uq))
		code = PRBADARG;
	    else
		code =
		    ubik_PR_SetFieldsEntry(pruclient, 0, id, mask,
			      access, gq, uq, 0, 0);
	    if (CodeOk(code))
		afs_com_err(whoami, code, "on %s %d %x %x %d %d", op, id, mask,
			access, gq, uq);
	} else if (!strcmp(op, "ce")) {
	    char newname[PR_MAXNAMELEN];
	    afs_int32 newid;
	    if (GetInt32(&id) || GetString(newname, sizeof(newname))
		|| GetInt32(&oid) || GetInt32(&newid))
		code = PRBADARG;
	    else
		code =
		    ubik_PR_ChangeEntry(pruclient, 0, id, newname, oid,
			      newid);
	    if (CodeOk(code))
		afs_com_err(whoami, code, "on %s %d %s %d %d", op, id, newname,
			oid, newid);
	} else if (!strcmp(op, "wh")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_WhereIsIt(pruclient, 0, id, &pos);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    else
		printf("location %d\n", pos);
	} else if (!strcmp(op, "du")) {
	    memset(&entry, 0, sizeof(entry));
	    /* scanf("%d",&pos); */
	    if (GetInt32(&pos))
		code = PRBADARG;
	    else
		code = ubik_PR_DumpEntry(pruclient, 0, pos, (struct prdebugentry *)&entry);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		PrintEntry(pos, &entry, /*indent */ 0);
#if 0
		printf("The contents of the entry for %d are:\n", entry.id);
		printf("flags %d next %d\n", entry.flags, entry.next);
		printf("Groups (or members) \n");
		for (i = 0; i < PRSIZE; i++)
		    printf("%d\n", entry.entries[i]);
		printf("nextID %d nextname %d name %s\n", entry.nextID,
		       entry.nextName, entry.name);
		printf("owner %d creator %d\n", entry.owner, entry.creator);
#endif
	    }
	} else if (!strcmp(op, "add") || !strcmp(op, "au")) {
	    /* scanf("%d %d",&id,&gid); */
	    if (GetInt32(&id) || GetInt32(&gid))
		code = PRBADARG;
	    else
		code = ubik_PR_AddToGroup(pruclient, 0, id, gid);
	    if (CodeOk(code))
		afs_com_err(whoami, code, "on %s %d %d", op, id, gid);
	} else if (!strcmp(op, "iton")) {
	    lid.idlist_val = (afs_int32 *) malloc(20 * sizeof(afs_int32));
	    ptr = lid.idlist_val;
	    lid.idlist_len = 0;
	    foo = line;
	    skip(&foo);
	    while ((lid.idlist_len < 20) && (sscanf(foo, "%d", ptr) != EOF)) {
		lid.idlist_len++;
		skip(&foo);
		ptr++;
	    }
	    if (*foo) {
		fprintf(stderr, "too many values specified; max is %d\n", 20);
	    }
	    lnames.namelist_val = 0;
	    lnames.namelist_len = 0;
	    code = ubik_PR_IDToName(pruclient, 0, &lid, &lnames);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		for (i = 0; i < lnames.namelist_len; i++) {
		    printf("id %d name %s\n", lid.idlist_val[i],
			   lnames.namelist_val[i]);
		}
		free(lnames.namelist_val);
	    }
	    free(lid.idlist_val);
	    lid.idlist_val = 0;
	    lid.idlist_len = 0;
	} else if (!strcmp(op, "ntoi")) {
	    lnames.namelist_val =
		(prname *) malloc(PR_MAXLIST * PR_MAXNAMELEN);
	    lnames.namelist_len = 0;
	    foo = line;
	    skip(&foo);
	    for (i = 0; ((lnames.namelist_len < PR_MAXLIST)
			 && (sscanf(foo, "%s", lnames.namelist_val[i]) !=
			     EOF)); i++) {
		lnames.namelist_len++;
		skip(&foo);
	    }
	    if (*foo) {
		fprintf(stderr, "too many values specified; max is %d\n",
			PR_MAXLIST);
	    }
	    lid.idlist_val = 0;
	    lid.idlist_len = 0;
	    code = ubik_PR_NameToID(pruclient, 0, &lnames, &lid);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		for (i = 0; i < lid.idlist_len; i++)
		    printf("name %s id %d\n", lnames.namelist_val[i],
			   lid.idlist_val[i]);
		free(lid.idlist_val);
	    }
	    free(lnames.namelist_val);
	    lnames.namelist_val = 0;
	    lnames.namelist_len = 0;
	} else if (!strcmp(op, "del")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_Delete(pruclient, 0, id);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	} else if (!strcmp(op, "dg")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_Delete(pruclient, 0, id);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	} else if (!strcmp(op, "rm")) {
	    /* scanf("%d %d",&id,&gid); */
	    if (GetInt32(&id) || GetInt32(&gid))
		code = PRBADARG;
	    else
		code = ubik_PR_RemoveFromGroup(pruclient, 0, id, gid);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	}
#if defined(SUPERGROUPS)
	else if (!strcmp(op, "lsg")) {
	    alist.prlist_len = 0;
	    alist.prlist_val = 0;
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code =
		    ubik_PR_ListSuperGroups(pruclient, 0, id, &alist,
			      &over);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		ptr = alist.prlist_val;
		if (over) {
		    printf("Number of groups greater than PR_MAXGROUPS!\n");
		    printf("Excess of %d.\n", over);
		}
		for (i = 0; i < alist.prlist_len; i++, ptr++)
		    printf("%d\n", *ptr);
		free(alist.prlist_val);
		alist.prlist_len = 0;
		alist.prlist_val = 0;
	    }
	}
#endif /* SUPERGROUPS */
	else if (!strcmp(op, "l")) {
	    alist.prlist_len = 0;
	    alist.prlist_val = 0;
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_GetCPS(pruclient, 0, id, &alist, &over);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		ptr = alist.prlist_val;
		if (over) {
		    printf("Number of groups greater than PR_MAXGROUPS!\n");
		    printf("Excess of %d.\n", over);
		}
		for (i = 0; i < alist.prlist_len; i++, ptr++)
		    printf("%d\n", *ptr);
		free(alist.prlist_val);
		alist.prlist_len = 0;
		alist.prlist_val = 0;
	    }
	} else if (!strcmp(op, "lh")) {
	    alist.prlist_len = 0;
	    alist.prlist_val = 0;
	    /* scanf("%d",&id); */
	    if (GetString(name, sizeof(name)))
		code = PRBADARG;
	    else if (!(hostinfo = gethostbyname(name)))
		code = PRBADARG;
	    else {
		hostaddr = (struct in_addr *)hostinfo->h_addr_list[0];
		id = ntohl(hostaddr->s_addr);
		code =
		    ubik_PR_GetHostCPS(pruclient, 0, id, &alist, &over);
	    }
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		ptr = alist.prlist_val;
		if (over) {
		    printf("Number of groups greater than PR_MAXGROUPS!\n");
		    printf("Excess of %d.\n", over);
		}
		for (i = 0; i < alist.prlist_len; i++, ptr++)
		    printf("%d\n", *ptr);
		free(alist.prlist_val);
		alist.prlist_len = 0;
		alist.prlist_val = 0;
	    }
	}
#if defined(SUPERGROUPS)
	else if (!strcmp(op, "m")) {
	    alist.prlist_len = 0;
	    alist.prlist_val = 0;
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code =
		    ubik_PR_ListElements(pruclient, 0, id, &alist,
			      &over);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS) {
		ptr = alist.prlist_val;
		if (over) {
		    printf("Number of groups greater than PR_MAXGROUPS!\n");
		    printf("Excess of %d.\n", over);
		}
		for (i = 0; i < alist.prlist_len; i++, ptr++)
		    printf("%d\n", *ptr);
		free(alist.prlist_val);
		alist.prlist_len = 0;
		alist.prlist_val = 0;
	    }
	}
#endif /* SUPERGROUPS */
	else if (!strcmp(op, "nu")) {
	    /* scanf("%s",name); */
	    if (GetString(name, sizeof(name)))
		code = PRBADARG;
	    else
		code = pr_CreateUser(name, &id);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS)
		printf("Id is %d.\n", id);
	} else if (!strcmp(op, "ng")) {
	    /* scanf("%s",name); */
	    if (GetString(name, sizeof(name)))
		code = PRBADARG;
	    else
		code = ubik_PR_NewEntry(pruclient, 0, name, 1, oid, &id);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS)
		printf("Id is %d.\n", id);
	} else if (!strcmp(op, "lm")) {
	    code = ubik_PR_ListMax(pruclient, 0, &id, &gid);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS)
		printf("Max user id is %d, max (really min) group is %d.\n",
		       id, gid);
	} else if (!strcmp(op, "smu")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_SetMax(pruclient, 0, id, 0);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	} else if (!strcmp(op, "smg")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = ubik_PR_SetMax(pruclient, 0, id, 1);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	} else if (!strcmp(op, "sin")) {
	    /* scanf("%d",&id); */
	    if (GetInt32(&id))
		code = PRBADARG;
	    else
		code = pr_SIdToName(id, name);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS)
		printf("id %d name %s\n", id, name);
	} else if (!strcmp(op, "sni")) {
	    /* scanf("%s",name); */
	    if (GetString(name, sizeof(name)))
		code = PRBADARG;
	    else
		code = pr_SNameToId(name, &id);
	    if (CodeOk(code))
		printf("%s\n", pr_ErrorMsg(code));
	    if (code == PRSUCCESS)
		printf("name %s id %d\n", name, id);
	} else if (!strcmp(op, "fih")) {
	    char tname[128];
	    struct PrUpdateEntry uentry;
	    memset(&uentry, 0, sizeof(uentry));
	    /* scanf("%s",name); */
	    if (GetString(name, sizeof(name))) {
		code = PRBADARG;
		continue;
	    }
	    code = pr_SNameToId(name, &id);
	    if (CodeOk(code)) {
		printf("%s\n", pr_ErrorMsg(code));
		continue;
	    }
	    code = pr_SIdToName(id, tname);
	    if (code == PRSUCCESS) {
		printf
		    ("Warning: Id hash for %s (id %d) seems correct at the db; rehashing it anyway\n",
		     name, id);
/*		continue;*/
	    }
	    uentry.Mask = PRUPDATE_IDHASH;
	    code = ubik_PR_UpdateEntry(pruclient, 0, 0, name, &uentry);
	    if (code) {
		printf("Failed to update entry %s (err=%d)\n", name, code);
		continue;
	    }
	} else if (!strcmp(op, "fnh")) {
	    int tid;
	    struct PrUpdateEntry uentry;
	    memset(&uentry, 0, sizeof(uentry));
	    /* scanf("%d", &id); */
	    if (GetInt32(&id)) {
		code = PRBADARG;
		continue;
	    }
	    code = pr_SIdToName(id, name);
	    if (CodeOk(code)) {
		printf("%s\n", pr_ErrorMsg(code));
		continue;
	    }
	    code = pr_SNameToId(name, &tid);
	    if (code == PRSUCCESS) {
		printf
		    ("Name hash for %d (name is %s) seems correct at the db; rehashing it anyway\n",
		     id, name);
/*		continue;*/
	    }
	    uentry.Mask = PRUPDATE_NAMEHASH;
	    code =
		ubik_PR_UpdateEntry(pruclient, 0, id, "_foo_", &uentry);
	    if (code) {
		printf("Failed to update entry with id %d (err=%d)\n", id,
		       code);
		continue;
	    }
	}
#if defined(SUPERGROUPS)
	else if (!strcmp(op, "fih")) {
	    char tname[128];
	    struct PrUpdateEntry uentry;
	    memset(&uentry, 0, sizeof(uentry));
	    /* scanf("%s",name); */
	    if (GetString(name, sizeof(name))) {
		code = PRBADARG;
		continue;
	    }
	    code = pr_SNameToId(name, &id);
	    if (CodeOk(code)) {
		printf("%s\n", pr_ErrorMsg(code));
		continue;
	    }
	    code = pr_SIdToName(id, tname);
	    if (code == PRSUCCESS) {
		printf
		    ("Warning: Id hash for %s (id %d) seems correct at the db; rehashing it anyway\n",
		     name, id);
/*		continue;*/
	    }
	    uentry.Mask = PRUPDATE_IDHASH;
	    code = ubik_PR_UpdateEntry(pruclient, 0, 0, name, &uentry);
	    if (code) {
		printf("Failed to update entry %s (err=%d)\n", name, code);
		continue;
	    }
	} else if (!strcmp(op, "fnh")) {
	    int tid;
	    struct PrUpdateEntry uentry;
	    memset(&uentry, 0, sizeof(uentry));
	    /* scanf("%d", &id); */
	    if (GetInt32(&id)) {
		code = PRBADARG;
		continue;
	    }
	    code = pr_SIdToName(id, name);
	    if (CodeOk(code)) {
		printf("%s\n", pr_ErrorMsg(code));
		continue;
	    }
	    code = pr_SNameToId(name, &tid);
	    if (code == PRSUCCESS) {
		printf
		    ("Name hash for %d (name is %s) seems correct at the db; rehashing it anyway\n",
		     id, name);
/*		continue;*/
	    }
	    uentry.Mask = PRUPDATE_NAMEHASH;
	    code =
		ubik_PR_UpdateEntry(pruclient, 0, id, "_foo_", &uentry);
	    if (code) {
		printf("Failed to update entry with id %d (err=%d)\n", id,
		       code);
		continue;
	    }
	}
#endif /* SUPERGROUPS */
	else if (!strcmp(op, "?"))
	    PrintHelp();
	else if (!strcmp(op, "q"))
	    exit(0);
	else
	    printf("Unknown op: '%s'! ? for help\n", op);
    }
}
示例#14
0
文件: ps2.c 项目: TRex22/setedit
//#define PROFILE
int main(int argc, char *argv[])
{
 int i,Frames=0;
 unsigned long t1=0,t2,t3,t4;
 float Time;
 double k=18.334;
 int ForceGeneric=0;
 int Surface=1,UnoMas;

 for (i=1; i<argc; i++)
    {
     UnoMas=i<argc-1;
     if (argv[i][0]=='-')
       {
        switch (argv[i][1])
          {
           case 's':
                WaitSync=0;
                break;
           case 'g':
                ForceGeneric=1;
                break;
           case 'h':
                PrintHelp();
                return 1;
           case 'i':
                ShowInfo();
                return 2;
           case 'n':
                printf("Plasma mixsurf 1\n");
                return 3;
           case 'F':
                Surface=0;
                break;
           case 'k':
                if (UnoMas)
                   k=atof(argv[++i]);
                break;
          }
       }
    }

 AllegroInit();
 CalcuInit();

 // Virtual screen
 BMPAuxScreen=create_bitmap(w,h);
 screen_buffer=BMPAuxScreen->line[0];

 RPF_MakeBlueGreen_RedBars(temp2);

 if (!ForceGeneric)
   {
    t3=rawclock();
    PLA2_InitPlasmaTables();
    t4=rawclock();
    AllegroSetMode();

    RPF_RGBBarsWithCos(temp);
    RPF_SetAllPal(temp);
    t1=rawclock();
    while (!poll_input())
      {
       for (i=0; i<1000 && !poll_input(); i++)
          {
           PLA2_Step2(screen_buffer);
           RPF_RGBBarsWithCos(temp);
           if (WaitSync)
              vsync();
           PS_FullBlitLinear(BMPAuxScreen,screen);
           Frames++;
           RPF_SetAllPal(temp);
          }
       if (i<1000) break;
       RPF_SetAllPal(temp2);
       for (i=0; i<1000 && !poll_input(); i++)
          {
           PLA2_Step2(screen_buffer);
           if (WaitSync)
              vsync();
           PS_FullBlitLinear(BMPAuxScreen,screen);
           Frames++;
          }
       if (i<1000) break;
      }
   }
 else
   {
    t3=rawclock();
    PLA2G_InitPlasmaTables(w,h,screen_buffer,k,Surface,w*2,h*2,CalcuCallBack);
    t4=rawclock();
    AllegroSetMode();
    RPF_RGBBarsWithCos(temp);
    RPF_SetAllPal(temp);
    t1=rawclock();
    while (!poll_input())
      {
       for (i=0; i<1000 && !poll_input(); i++)
          {
           MVS_4SurfSC();
           RPF_RGBBarsWithCos(temp);
           Blit();
           RPF_SetAllPal(temp);
          }
       if (i<1000) break;
       RPF_SetAllPal(temp2);
       for (i=0; i<1000 && !poll_input(); i++)
          {
           MVS_4SurfSC();
           Blit();
          }
       if (i<1000) break;
      }
   }
 t2=rawclock();
 PLA2G_DeInit();
 allegro_exit();

 Time=(t2-t1)/18.2;
 printf("Time: %f Frames: %d => %f fps.\n",Time,Frames,Frames/Time);
 Time=(t4-t3)/18.2;
 printf("Initialization time: %f.\n",Time);

 terminate();
 return 0;
}
示例#15
0
int
main(int argc, char **argv, char **envp)
{
	struct Session session;
	time_t	t1, t2;

	int tmp = 0;

	if(RegisterHandlers() == -1)
	{
		fprintf(stderr, "[!] Cannot register signal handlers, aborting\n");
		goto cleanup;
	}
	
	InitSession(&session, envp, argv);

	if(ParseArguments(argc, argv, &session) == -1)
	{
		PrintHelp(argv[0]);
		goto cleanup;
	}

	if(OpenLogFile(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot open %s for logging, aborting\n",
			session.logfilename);

		goto cleanup;
	}

	if(PrepareArgv(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot parse arguments\n");
		goto cleanup;
	}
	
	if(InitFuzzingStrings(&session) == -1)
	{
		fprintf(stderr, "[!] Error initializing fuzzing variables\n");
		goto cleanup;
	}

	switch(session.mode)
	{
		/* Smart mode read the file structure from a file */ 
		case MODE_SMART:
		{
			fprintf(stdout, "[%%] Reading headers structure from %s\n",
			session.headers);

			session.headercount = Extract_DataFields(&session);
			break;
		}
		/* ASCII mode read a file and tries to get the right file structure =) */
		case MODE_ASCII:
		{
			fprintf(stdout, "[%%] Reading ASCII structure from %s\n",
				session.input);
			
			session.headercount = Extract_ASCII_Structure(&session);
			break;
		}
	}

	if((session.mode == MODE_ASCII) || (session.mode == MODE_SMART))
	{
		if(!session.headercount)
		{
			fprintf(stderr, "[!] Error loading Offsets from input file\n");
			goto cleanup;
		}

		session.range.low   = 0;
		session.range.high  = session.headercount;
		
		fprintf(stdout, "[%%] Loaded %d fields in headers\n",
			session.headercount);
	}

	tmp = CountFuzzingStrings(&session);
	
	fprintf(stdout, "[%%] Loaded %d fuzzing variables\n", tmp);
	fprintf(stdout, "[%%] Fuzzing from %d to %d\n",	session.range.low,
		session.range.high);
	
	if(session.mode == MODE_BRUTE)
	{
		session.byte = session.range.low;
		tmp         *= session.range.high - session.range.low + 1;
	}
	else
	{
		session.curfield = session.d;
		session.byte     = session.curfield->offset;
		tmp             *= session.headercount;
	}

	PrintLogHeader(&session);

	fprintf(stdout, "[%%] Number of files to be generated %d\n", tmp);
	fprintf(stdout, "[%%] Proceding with fuzzing\n");

	time(&t1);
	StartSession(&session);
	time(&t2);

	fprintf(stdout, "[%%] Time elapsed %f\n", difftime(t2, t1));
	fprintf(stdout, "[%%] Number of succesful executions %d\n", session.exec);
	fprintf(stdout, "[%%] Skipped executions due to fuzzing string size %d\n", session.skipped);
	fprintf(stdout, "[%%] Number of \"bugs\" found: %d\n", session.bugs);
	
	/* Cleanup Resources */
	cleanup:
	{
		FreeFuzzingList(session.f);
		FreeMaps(session.maps);
		CloseLogFile(&session);
	}
	
	return 0;
}
示例#16
0
int main(int argc, char** argv)/*{{{*/
{
    bool isNonOptionArg = false;
    if(argc < 2) 
    {
        PrintHelp();
        return 0;
    }
    int i,j;
    char modmfile[MAX_PATH+1] = "";
    char modmfilelist[MAX_PATH+1] = "";
    char outfile[MAX_PATH+1] = "";
    char suppliedAlphabet[SIZE_ALPHABET+1] = ""; /*force supplied alphabet to the alphabet in the output binary file*/
    char outpath[MAX_PATH+1] = ""; /*default output path for the binary file is the same as the ascii file*/
    double value = 0.0;
    int mode = 0;
    const char control_option[] = "bp"; //options which control the program, and does not take parameters

    char tmpfile[MAX_PATH+1] = "/tmp/fileXXXXXX";
    if (mkstemp(tmpfile) == -1)
    {
        fprintf(stderr, "Error! No temporary file can be created\n");
        return -1;
    }
    FILE *fptmp = fopen(tmpfile,"w");
    bool isIDsSet = false;
    bool isOutputTimeInfo = true;

    i = 1;
    while(i < argc)/*{{{*/
    {
        if(argv[i][0] == '-' && !isNonOptionArg) //options
        {
            isNonOptionArg = false;
            if(IsInCharSet(argv[i][1], control_option))//if argv[i][1] is in control_option, it might be used as -aqs
            {
                for(j = 1 ; j < strlen(argv[i]); j++)
                {
                    switch (argv[i][j])
                    {
                        case 'b': isWriteBinaryFile = true; break;
                        case 'p': isPrintOut = true; break;
                        default : fprintf(stderr,"Invalid option, non-control option '%c' can be used together with contorl-option\n", argv[j]); return -1;
                    }
                }
                i ++;
            }
            else if(strcmp(argv[i],"-h") == 0 ||strcmp(argv[i],"--help")==0 )
            {
                PrintHelp(); 
                return 0;
            }
            else if(strcmp(argv[i],"-H") == 0 )
            {
                PrintVerboseHelp();
                return 0;
            }
            else if(strcmp(argv[i],"-a") == 0 )
            {
                my_strcpy(suppliedAlphabet, argv[i+1], SIZE_ALPHABET);
                i += 2;

            }
            else if( (strcmp(argv[i],"-o") == 0) || (strcmp(argv[i], "--out") == 0))  
            {
                if( ( i = option_parser_filename(argc, argv, i, outfile)) == -1)
                    return -1;
            }
            else if( (strcmp(argv[i], "--outpath") == 0))  
            {
                if( ( i = option_parser_filename(argc, argv, i, outpath)) == -1)
                    return -1;
            }
            else if( (strcmp(argv[i],"-l") == 0) )  
            {
                if( ( i = option_parser_filename(argc, argv, i, modmfilelist)) == -1)
                    return -1;
            }
            else if( (strcmp(argv[i], "--mode") == 0))  
            {
                if( ( i = option_parser_numeric(argc, argv, i, mode, true, 0, 1)) == -1)
                    return -1;
            }
            else if (strcmp(argv[i], "--sad") == 0)/*indicating the modm file contains SAD information*/
            {
                isHaveSAD = true;
                i ++;
            }
            else if (strcmp(argv[i], "--notime") == 0)/*do not output time info*/
            {
                isOutputTimeInfo = false;
                i ++;
            }
            else if (strcmp(argv[i], "--") == 0)//next item is non option argument
            {
                isNonOptionArg = true;
                i ++;
                continue;
            }
            else
            {
                fprintf(stderr,"Error! Invalid argument '%s'\n", argv[i]);
                return -1;
            }
        }
        else //non-option argument
        {
            if(!isIDsSet) 
            {
                fptmp = fopen(tmpfile,"w");
                if(fptmp == NULL)
                {
                    fprintf(stderr,"can not open file '%s' for write\n", tmpfile);
                    assert( fptmp != NULL);
                }
            }
            fprintf(fptmp,"%s\n",argv[i]);
            isIDsSet = true;
            i ++;
        }
    }/*}}}*/

    if(isIDsSet) fclose(fptmp);


    if(!isIDsSet && strcmp(modmfilelist, "") == 0)
    {
        fprintf(stderr,"Error! neither ids and idListFile set\n");
        PrintHelp();
        return -1;
    }
    else if(isIDsSet && strcmp(modmfilelist,"") == 0)
    {
        my_strcpy(modmfilelist,tmpfile,MAX_PATH);
    }

    FILE *fpout = NULL;
    if(strcmp(outfile,"") == 0 || strcasecmp(outfile, "stdout") == 0)
    {
        fpout = stdout;
    }
    else
    {
        fpout = fopen(outfile, "w");
        checkfilestream(fpout, outfile,"w");
    }

    clock_t start, finish;
    double duration;
    int tmp;
    start = clock();

    FILE *fpFileList = fopen(modmfilelist, "r");
    checkfilestream(fpFileList, modmfilelist, "r");
    int linesize;
    int maxline = 300;
    Array1D <char> line_1darray(maxline+1);
    char *line = line_1darray.array1D;

    int sizeAlphabet = 0;
    char alphabet[SIZE_ALPHABET+1] = "";
    int numRes = 0;
    Array1D <Profile> profile_1darray(2000);
    Profile *profile = profile_1darray.array1D;
    Array1D <ProfileSAD> profileSAD_1darray(2000);
    ProfileSAD *profileSAD = profileSAD_1darray.array1D;
    double parameter[8];
    int status_sscanf = 0;

    int cntFile  = 0;
    while((linesize = fgetline(fpFileList,line, maxline)) != EOF)
    {
        my_strcpy(modmfile, line, MAX_PATH);

        for(j = 0; j < 8; j ++)
        {
            parameter[j] = 0.0;
        }
        strcpy(alphabet,"");


        if(mode == 0) /*read text file*/
        {
            FILE *fpin = fopen(modmfile,"r");
            checkfilestream(fpin,modmfile,"r");
            char str[100] = "";
            char first_non_blank_char = ' ';
            int cntRes = 0;
            while((linesize = fgetline(fpin, line, maxline)) != EOF)
            {
                if(line[0] == '#' || linesize <=0 ) 
                {
                    continue;
                }
                sscanf(line, " %c", &first_non_blank_char);
                if (first_non_blank_char == 'N')/*alphabet line*/
                {
                    SpanExcluding(line, str);
                    if(!isHaveSAD)
                    {
                        my_strcpy(alphabet, str+5, SIZE_ALPHABET);
                    }
                    else
                    {
                        my_strcpy(alphabet, str+8, SIZE_ALPHABET);
                    }
                }
                else if (isdigit(first_non_blank_char))
                {
                    if(!isHaveSAD)
                    {
                        profile[cntRes].score1 = 0.0;
                        profile[cntRes].score2 = 0.0;
                        status_sscanf = sscanf(line,"%d %c %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",/*{{{*/
                                &profile[cntRes].aaSeqIndex, 
                                &profile[cntRes].aa,
                                &profile[cntRes].p[0],
                                &profile[cntRes].p[1],
                                &profile[cntRes].p[2],
                                &profile[cntRes].p[3],
                                &profile[cntRes].p[4],
                                &profile[cntRes].p[5],
                                &profile[cntRes].p[6],
                                &profile[cntRes].p[7],
                                &profile[cntRes].p[8],
                                &profile[cntRes].p[9],
                                &profile[cntRes].p[10],
                                &profile[cntRes].p[11],
                                &profile[cntRes].p[12],
                                &profile[cntRes].p[13],
                                &profile[cntRes].p[14],
                                &profile[cntRes].p[15],
                                &profile[cntRes].p[16],
                                &profile[cntRes].p[17],
                                &profile[cntRes].p[18],
                                &profile[cntRes].p[19],
                                &profile[cntRes].score1,
                                &profile[cntRes].score2
                                    );/*}}}*/
                        if(status_sscanf < 22)
                        {
                            fprintf(stderr,"current line=%s\n!", line );
                            fprintf(stderr,"The profile maybe incomplete, status_sscanf = %d, number %d, file %s\n!", status_sscanf, cntRes+1, modmfile );
                            assert (status_sscanf >= 22);
                        }
                    }
                    else
                    {
                        profileSAD[cntRes].score1 = 0.0;
                        profileSAD[cntRes].score2 = 0.0;
                        status_sscanf = sscanf(line,"%d %c %1c%1d%1c %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f",/*{{{*/
                                &profileSAD[cntRes].aaSeqIndex, 
                                &profileSAD[cntRes].aa,
                                &profileSAD[cntRes].shape,
                                &profileSAD[cntRes].waterAcc,
                                &profileSAD[cntRes].dsspSec,
                                &profileSAD[cntRes].p[0],
                                &profileSAD[cntRes].p[1],
                                &profileSAD[cntRes].p[2],
                                &profileSAD[cntRes].p[3],
                                &profileSAD[cntRes].p[4],
                                &profileSAD[cntRes].p[5],
                                &profileSAD[cntRes].p[6],
                                &profileSAD[cntRes].p[7],
                                &profileSAD[cntRes].p[8],
                                &profileSAD[cntRes].p[9],
                                &profileSAD[cntRes].p[10],
                                &profileSAD[cntRes].p[11],
                                &profileSAD[cntRes].p[12],
                                &profileSAD[cntRes].p[13],
                                &profileSAD[cntRes].p[14],
                                &profileSAD[cntRes].p[15],
                                &profileSAD[cntRes].p[16],
                                &profileSAD[cntRes].p[17],
                                &profileSAD[cntRes].p[18],
                                &profileSAD[cntRes].p[19],
                                &profileSAD[cntRes].score1,
                                &profileSAD[cntRes].score2
                                    );/*}}}*/
                        if(status_sscanf < 25)
                        {
                            fprintf(stderr,"current line=%s\n!", line );
                            fprintf(stderr,"The profile maybe incomplete, status_sscanf = %d, number %d, file %s\n!", status_sscanf, cntRes+1, modmfile );
                            assert (status_sscanf >= 25);
                        }
                    }
                    cntRes ++;
                }
                else if (first_non_blank_char == 'K')
                {
                    int j = 0 ;
                    while((linesize = fgetline(fpin, line, maxline)) != EOF)
                    {
                        status_sscanf = sscanf(line,"%s %s %lf %lf", str, str, &parameter[j], &parameter[j+1]);
                        if(status_sscanf < 4)
                        {
                            fprintf(stderr,"Warning, file %s may not have psi-blast parameters\n", modmfile);
                        }
                        j += 2;
                        if (j >= 8 ) break;
                    }
                }
            }
            fclose(fpin);
            numRes = cntRes;
            if (isWriteBinaryFile)
            {
                char binaryfile[MAX_PATH+1] = "";
                if(strcmp(outpath, "") == 0)  /*if outpath is not set, output to the same folder as the ascii file*/
                {
                    sprintf(binaryfile, "%sbin", modmfile);   /*if outpath is set*/
                }
                else
                {

                    char rtname[MAX_PATH+1] = "";
                    char fileext[MAX_PATH+1] = "";
                    rootname(modmfile, rtname);
                    getfileext(modmfile, fileext);
                    sprintf(binaryfile, "%s/%s.%sbin", outpath, rtname, fileext);
                }
//                fprintf(stdout,"%d \t write out binary file to %s\n", cntFile, binaryfile) ;
                if(strcmp(suppliedAlphabet,"") != 0)
                {
                    my_strcpy(alphabet, suppliedAlphabet, SIZE_ALPHABET);
                }
                if(!isHaveSAD)
                {
                    WriteBinaryMODM(binaryfile, alphabet, numRes, profile, parameter);
                }
                else
                {
                    WriteBinaryMODM(binaryfile, alphabet, numRes, profileSAD, parameter);
                }
            }
        }
        else if(mode == 1)
        {

            if(!isHaveSAD)
            {
                GetBinaryMODM(modmfile, alphabet, numRes, profile, parameter);
                if (isPrintOut)
                {
                    WriteMODM(alphabet, profile, numRes, parameter, fpout);
                }
            }
            else
            {
                GetBinaryMODM(modmfile, alphabet, numRes, profileSAD, parameter);
                if (isPrintOut)
                {
                    WriteMODM(alphabet, profileSAD, numRes, parameter, fpout);
                }
            }
        }
        cntFile ++;
    }

    finish = clock();
    duration = double(finish-start)  /double(CLOCKS_PER_SEC);
    //printf("CLOCKS_PER_SEC=%d, start=%lf, finish=%lf\n", CLOCKS_PER_SEC, start, finish);
    if (isOutputTimeInfo)
    {
        if(mode == 0)
        {
            fprintf(stdout,"reading text file cost %lf seconds\n", duration);
        }
        else if(mode == 1)
        {
            fprintf(stdout,"reading bindary file cost %lf seconds\n", duration);
        }

    }

    if(fpout != NULL && fpout != stdout) fclose(fpout);

    return 0;
}
示例#17
0
文件: cdogs.c 项目: flags/cdogs-sdl
int main(int argc, char *argv[])
{
	int wait = 0;
	int controllerFlag = SDL_INIT_GAMECONTROLLER;
	credits_displayer_t creditsDisplayer;
	memset(&creditsDisplayer, 0, sizeof creditsDisplayer);
	custom_campaigns_t campaigns;
	memset(&campaigns, 0, sizeof campaigns);
	int forceResolution = 0;
	int err = 0;
	const char *loadCampaign = NULL;
	ENetAddress connectAddr;
	memset(&connectAddr, 0, sizeof connectAddr);

	srand((unsigned int)time(NULL));
	LogInit();

	PrintTitle();

	if (getenv("DEBUG") != NULL)
	{
		debug = true;
		char *dbg;
		if ((dbg = getenv("DEBUG_LEVEL")) != NULL)
		{
			debug_level = CLAMP(atoi(dbg), D_NORMAL, D_MAX);
		}
	}

	SetupConfigDir();
	gConfig = ConfigLoad(GetConfigFilePath(CONFIG_FILE));
	LoadCredits(&creditsDisplayer, colorPurple, colorDarker);
	AutosaveInit(&gAutosave);
	AutosaveLoad(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));

	if (enet_initialize() != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "An error occurred while initializing ENet.");
		err = EXIT_FAILURE;
		goto bail;
	}
	NetClientInit(&gNetClient);

	// Print command line
	char buf[CDOGS_PATH_MAX];
	buf[0] = '\0';
	for (int i = 0; i < argc; i++)
	{
		strcat(buf, " ");
		// HACK: for OS X, blank out the -psn_XXXX argument so that it doesn't
		// break arg parsing
	#ifdef __APPLE__
		if (strncmp(argv[i], "-psn", strlen("-psn")) == 0)
		{
			argv[i] = "";
		}
	#endif
		strcat(buf, argv[i]);
	}
	LOG(LM_MAIN, LL_INFO, "Command line (%d args):%s", argc, buf);
	{
		struct option longopts[] =
		{
			{"fullscreen",	no_argument,		NULL,	'f'},
			{"scale",		required_argument,	NULL,	's'},
			{"screen",		required_argument,	NULL,	'c'},
			{"forcemode",	no_argument,		NULL,	'o'},
			{"nosound",		no_argument,		NULL,	'n'},
			{"nojoystick",	no_argument,		NULL,	'j'},
			{"wait",		no_argument,		NULL,	'w'},
			{"shakemult",	required_argument,	NULL,	'm'},
			{"connect",		required_argument,	NULL,	'x'},
			{"debug",		required_argument,	NULL,	'd'},
			{"log",			required_argument,	NULL,	1000},
			{"help",		no_argument,		NULL,	'h'},
			{0,				0,					NULL,	0}
		};
		int opt = 0;
		int idx = 0;
		while ((opt = getopt_long(argc, argv, "fs:c:onjwm:xd\0h", longopts, &idx)) != -1)
		{
			switch (opt)
			{
			case 'f':
				ConfigGet(&gConfig, "Graphics.Fullscreen")->u.Bool.Value = true;
				break;
			case 's':
				ConfigSetInt(&gConfig, "Graphics.ScaleFactor", atoi(optarg));
				break;
			case 'c':
				sscanf(optarg, "%dx%d",
					&ConfigGet(&gConfig, "Graphics.ResolutionWidth")->u.Int.Value,
					&ConfigGet(&gConfig, "Graphics.ResolutionHeight")->u.Int.Value);
				LOG(LM_MAIN, LL_DEBUG, "Video mode %dx%d set...",
					ConfigGetInt(&gConfig, "Graphics.ResolutionWidth"),
					ConfigGetInt(&gConfig, "Graphics.ResolutionHeight"));
				break;
			case 'o':
				forceResolution = 1;
				break;
			case 'n':
				LOG(LM_MAIN, LL_INFO, "Sound to 0 volume");
				ConfigGet(&gConfig, "Sound.SoundVolume")->u.Int.Value = 0;
				ConfigGet(&gConfig, "Sound.MusicVolume")->u.Int.Value = 0;
				break;
			case 'j':
				debug(D_NORMAL, "nojoystick\n");
				controllerFlag = 0;
				break;
			case 'w':
				wait = 1;
				break;
			case 'm':
				{
					ConfigGet(&gConfig, "Graphics.ShakeMultiplier")->u.Int.Value =
						MAX(atoi(optarg), 0);
					printf("Shake multiplier: %d\n",
						ConfigGetInt(&gConfig, "Graphics.ShakeMultiplier"));
				}
				break;
			case 'h':
				PrintHelp();
				goto bail;
			case 'd':
				// Set debug level
				debug = true;
				debug_level = CLAMP(atoi(optarg), D_NORMAL, D_MAX);
				break;
			case 1000:
				{
					char *comma = strchr(optarg, ',');
					if (comma)
					{
						// Set logging level for a single module
						// The module and level are comma separated
						*comma = '\0';
						const LogLevel ll = StrLogLevel(comma + 1);
						LogModuleSetLevel(StrLogModule(optarg), ll);
						printf("Logging %s at %s\n", optarg, LogLevelName(ll));
					}
					else
					{
						// Set logging level for all modules
						const LogLevel ll = StrLogLevel(optarg);
						for (int i = 0; i < (int)LM_COUNT; i++)
						{
							LogModuleSetLevel((LogModule)i, ll);
						}
						printf("Logging everything at %s\n", LogLevelName(ll));
					}
				}
				break;
			case 'x':
				if (enet_address_set_host(&connectAddr, optarg) != 0)
				{
					printf("Error: unknown host %s\n", optarg);
				}
				break;
			default:
				PrintHelp();
				// Ignore unknown arguments
				break;
			}
		}
		if (optind < argc)
		{
			// non-option ARGV-elements
			for (; optind < argc; optind++)
			{
				// Load campaign
				loadCampaign = argv[optind];
			}
		}
	}

	debug(D_NORMAL, "Initialising SDL...\n");
	const int sdlFlags =
		SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_HAPTIC;
	if (SDL_Init(sdlFlags | controllerFlag) != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "Could not initialise SDL: %s", SDL_GetError());
		err = EXIT_FAILURE;
		goto bail;
	}
	if (SDLJBN_Init() != 0)
	{
		LOG(LM_MAIN, LL_ERROR, "Could not initialise SDLJBN: %s",
			SDLJBN_GetError());
		err = EXIT_FAILURE;
		goto bail;
	}
	SDL_EventState(SDL_DROPFILE, SDL_DISABLE);

	GetDataFilePath(buf, "");
	LOG(LM_MAIN, LL_INFO, "data dir(%s)", buf);
	LOG(LM_MAIN, LL_INFO, "config dir(%s)", GetConfigFilePath(""));

	SoundInitialize(&gSoundDevice, "sounds");
	if (!gSoundDevice.isInitialised)
	{
		LOG(LM_MAIN, LL_ERROR, "Sound initialization failed!");
	}

	LoadHighScores();

	debug(D_NORMAL, "Loading song lists...\n");
	LoadSongs();

	MusicPlayMenu(&gSoundDevice);

	EventInit(&gEventHandlers, NULL, NULL, true);
	NetServerInit(&gNetServer);

	if (wait)
	{
		printf("Press the enter key to continue...\n");
		getchar();
	}
	if (!PicManagerTryInit(
		&gPicManager, "graphics/cdogs.px", "graphics/cdogs2.px"))
	{
		LOG(LM_MAIN, LL_ERROR, "Failed to initialize graphics");
		err = EXIT_FAILURE;
		goto bail;
	}
	memcpy(origPalette, gPicManager.palette, sizeof(origPalette));
	GraphicsInit(&gGraphicsDevice, &gConfig);
	GraphicsInitialize(&gGraphicsDevice, forceResolution);
	if (!gGraphicsDevice.IsInitialized)
	{
		LOG(LM_MAIN, LL_WARN, "Cannot initialise video; trying default config");
		ConfigResetDefault(ConfigGet(&gConfig, "Graphics"));
		GraphicsInit(&gGraphicsDevice, &gConfig);
		GraphicsInitialize(&gGraphicsDevice, forceResolution);
	}
	if (!gGraphicsDevice.IsInitialized)
	{
		LOG(LM_MAIN, LL_ERROR, "Video didn't init!");
		err = EXIT_FAILURE;
		goto bail;
	}
	FontLoadFromJSON(&gFont, "graphics/font.png", "graphics/font.json");
	PicManagerLoadDir(&gPicManager, "graphics");

	ParticleClassesInit(&gParticleClasses, "data/particles.json");
	AmmoInitialize(&gAmmo, "data/ammo.json");
	BulletAndWeaponInitialize(
		&gBulletClasses, &gGunDescriptions,
		"data/bullets.json", "data/guns.json");
	CharacterClassesInitialize(&gCharacterClasses, "data/character_classes.json");
	LoadPlayerTemplates(
		&gPlayerTemplates, &gCharacterClasses, PLAYER_TEMPLATE_FILE);
	PickupClassesInit(
		&gPickupClasses, "data/pickups.json", &gAmmo, &gGunDescriptions);
	MapObjectsInit(&gMapObjects, "data/map_objects.json");
	CollisionSystemInit(&gCollisionSystem);
	CampaignInit(&gCampaign);
	LoadAllCampaigns(&campaigns);
	PlayerDataInit(&gPlayerDatas);

	GrafxMakeRandomBackground(
		&gGraphicsDevice, &gCampaign, &gMission, &gMap);

	debug(D_NORMAL, ">> Entering main loop\n");
	// Attempt to pre-load campaign if requested
	if (loadCampaign != NULL)
	{
		LOG(LM_MAIN, LL_INFO, "Loading campaign %s...", loadCampaign);
		gCampaign.Entry.Mode =
			strstr(loadCampaign, "/" CDOGS_DOGFIGHT_DIR "/") != NULL ?
			GAME_MODE_DOGFIGHT : GAME_MODE_NORMAL;
		CampaignEntry entry;
		if (!CampaignEntryTryLoad(&entry, loadCampaign, GAME_MODE_NORMAL) ||
			!CampaignLoad(&gCampaign, &entry))
		{
			LOG(LM_MAIN, LL_ERROR, "Failed to load campaign %s", loadCampaign);
		}
	}
	else if (connectAddr.host != 0)
	{
		if (NetClientTryScanAndConnect(&gNetClient, connectAddr.host))
		{
			ScreenWaitForCampaignDef();
		}
		else
		{
			printf("Failed to connect\n");
		}
	}
	LOG(LM_MAIN, LL_INFO, "Starting game");
	MainLoop(&creditsDisplayer, &campaigns);

bail:
	debug(D_NORMAL, ">> Shutting down...\n");
	MapTerminate(&gMap);
	PlayerDataTerminate(&gPlayerDatas);
	MapObjectsTerminate(&gMapObjects);
	PickupClassesTerminate(&gPickupClasses);
	ParticleClassesTerminate(&gParticleClasses);
	AmmoTerminate(&gAmmo);
	WeaponTerminate(&gGunDescriptions);
	BulletTerminate(&gBulletClasses);
	CharacterClassesTerminate(&gCharacterClasses);
	MissionOptionsTerminate(&gMission);
	NetClientTerminate(&gNetClient);
	atexit(enet_deinitialize);
	EventTerminate(&gEventHandlers);
	GraphicsTerminate(&gGraphicsDevice);

	PicManagerTerminate(&gPicManager);
	FontTerminate(&gFont);
	AutosaveSave(&gAutosave, GetConfigFilePath(AUTOSAVE_FILE));
	AutosaveTerminate(&gAutosave);
	ConfigSave(&gConfig, GetConfigFilePath(CONFIG_FILE));
	SavePlayerTemplates(&gPlayerTemplates, PLAYER_TEMPLATE_FILE);
	CArrayTerminate(&gPlayerTemplates);
	FreeSongs(&gMenuSongs);
	FreeSongs(&gGameSongs);
	SaveHighScores();
	UnloadCredits(&creditsDisplayer);
	UnloadAllCampaigns(&campaigns);
	CampaignTerminate(&gCampaign);
	SoundTerminate(&gSoundDevice, true);
	ConfigDestroy(&gConfig);

	SDLJBN_Quit();
	SDL_Quit();

	return err;
}
示例#18
0
文件: shagnetron.cpp 项目: garinh/cs
bool Shagnetron::Run ()
{
  csRef<iCommandLineParser> cmdline = csQueryRegistry<iCommandLineParser> (object_reg);
  
  csFIFO<csString> toScan;
  for (size_t i = 0; ; i++)
  {
    csString dir (cmdline->GetName (i));
    if (dir.IsEmpty()) break;
    
    toScan.Push (dir);
  }
  if (toScan.GetSize() == 0)
  {
    PrintHelp ();
    return false;
  }
  
  docsys = csQueryRegistry<iDocumentSystem> (object_reg);
  vfs = csQueryRegistry<iVFS> (object_reg);
  shaderMgr = csQueryRegistry<iShaderManager> (object_reg);
  iHierarchicalCache* shaderCache = shaderMgr->GetShaderCache();
  if (!shaderCache)
  {
    csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,
    	"crystalspace.application.shagnetron",
	"Shader cache is disabled. Please enable to use this tool");
    // @@@ It might be sensible to forcibly enable shader caching
    return false;
  }
  
  if (cmdline->GetBoolOption ("nodefaultcaches", false))
    shaderMgr->RemoveAllSubShaderCaches();
  for (size_t i = 0; ; i++)
  {
    const char* opt = cmdline->GetOption ("cachedir", i);
    if (!opt || !*opt) break;
    
    shaderMgr->AddSubCacheDirectory (opt,
      iShaderManager::cachePriorityHighest);
  }
  if (cmdline->GetBoolOption ("cacheclear", false))
  {
    csPrintf ("Clearing cache ..."); fflush (stdout);
    shaderCache->ClearCache ("/");
    csPrintf (" ok\n");
  }

  bool doQuick = cmdline->GetBoolOption ("quick", false);
  
  csSet<csString> seenDirectories;
  while (toScan.GetSize() > 0)
  {
    csString obj (toScan.PopTop());
    
    if (obj[obj.Length()-1] == '/')
    {
      if (!seenDirectories.Contains (obj))
      {
        csRef<iStringArray> vfsFiles (vfs->FindFiles (obj));
        for (size_t i = 0; i < vfsFiles->GetSize(); i++)
        {
	  const char* file = vfsFiles->Get (i);
  	
	  if (FileBlacklisted (file)) continue;
  	
	  toScan.Push (file);
        }
        seenDirectories.AddNoTest (obj);
      }
    }
    else
      PrecacheShaderFile (obj, doQuick);
  }

  return true;
}
示例#19
0
// ------------------------------------------------------------------------------------------------
void PrintHelp(int _exitCode)
{
    PrintHelp();
    exit(_exitCode);
}
示例#20
0
int main(int argc, char *argv[])
{
  Entity et;
  int error, startupflags, i;
  char *restartname, name[128];
#ifdef PARALLEL
  const ParCommand end = EXIT;
#endif
  InitVarTable();
#ifdef PARALLEL
  IsMaster();
  if (master) {
    printf("MetPhoMod   Rel. 2.2\n" SYSTEM " parallel Version - " DATE "\n\n");
#else
  printf("MetPhoMod   Rel. 2.2\n" SYSTEM " sequential Version - " DATE "\n\n");
#endif
    if (argc > 1 && (!strcmp(argv[1], "-help") || !strcmp(argv[1], "-h")))  {
      McInterface::modmanager.Init1();
      PrintHelp(argc - 2, argv + 2);
      exit (0);
    }
    if (argc > 1 && !strcmp(argv[1], "-genchem"))  {
      if (argc != 3)  goto instant_help;
      GenerateSpecialChem(argv[2]);
      exit (0);
    }
    startupflags = AnalizeOptions(&argc, argv, &restartname);
    if (argc != 2)  {
instant_help :
      printf("Usage : meteochem [-RESTART restart-file [-REOPEN]] [-noexcpt] [-syntax] \\\n"
             "                  [-nooutput] [-debug] [-sequential] inpfile\n"
             "or    : meteochem (-h | -help) [keyword]\n"
             "or    : meteochem -genchem chemfile\n");
      return (1);
    }
    McInterface::modmanager.Init1();
    if (startupflags & SYNTAX_ONLY)  {
      if (ParseInput(argv[1]))  {
        printf("Errors in Input-File\n");
        return (1);
      }
      else  {
        printf("the input-file seems to be OK!\n");
        return (0);
      }
    }
#ifdef PARALLEL
    if (startupflags & SEQUENTIAL)  {
      parallel = FALSE; master = TRUE;
      leftest = rightest = TRUE;
    }
  }
  if (master)  {
#endif
    if (ParseInput(argv[1]))  {
      fprintf(stderr, "Errors parsing Input-File. I don't start the calculation.\n");
      return (1);
    }
    plausible = TRUE;
    if (!(startupflags & NOEXCPT))  InstallFpeHandler();
    tinc = chemtinc = tincmax;
    actime = chemtime = tstart;
#ifdef PARALLEL
    if (!parallel)  printf("\n\n!!! Using sequential mode !!!\n\n");
    else
      McInterface::modmanager.CheckIfReadyForParallel();
  }
  InitializeWorkers(argv[0], startupflags & DEBUG_WORKERS);
  if (parallel && !master)  {
    if (!(startupflags & NOEXCPT))  InstallFpeHandler();
    McInterface::modmanager.Init1();
    ReadDataFromMaster();
    InitializeData();
    plausible = TRUE;
    tinc = chemtinc = tincmax;
    actime = chemtime = tstart;
  }
  if (parallel && master)  {
    printf("Sending Data to workers...\n");
    SendDataToWorkers();
    InitializeData();
  }
  if (!parallel)
#endif
    InitializeData();
  for (et = maxentity; et--; )
    if (g[et])
      CalculateLayerAverage(g[et], pstat, avg+et*nz);
    else
      memset(avg+et*nz, 0, nz*sizeof(double));
  CalcMeanHydrostaticPressure();
#ifdef PARALLEL
  if (!parallel || !master)  {
#endif
    SetAvgMountains();
    SetBoundary(maxentity);
/*    CalcAllKm();  */
#ifdef PARALLEL
  }
  if (parallel && !master)  {
    if (GetRestartName(name))  {
      if (!(ReadFullDump(name, (startupflags & REOPEN)) && actime <= tend))  {
	printf("Error : Restart-file not found\n");
	plausible = FALSE;
      }
    }
  }
  else  {
    if (parallel)
      SendRestartName((startupflags & RESTART) ? restartname : NULL);
#endif
    if (startupflags & RESTART)  {
      if (!ReadFullDump(restartname, (startupflags & REOPEN)))  {
        printf("Error : Restart-file not found\n");
        return (1);
      }
    }
    else if (startupflags & REOPEN)  {
      printf("Error: -REOPEN can only be used together with -RESTART\n");
      return (1);
    }
#ifdef PARALLEL
  }
  if (master)  {
#endif
    if (!(startupflags & NO_OUTPUT))  {
      printf("Opening output-Files...");
      if (OpenOutputFiles(argv[1], (startupflags & RESTART) && (startupflags & REOPEN)))  {
        printf("\nExecution abortet\n");
        exit (1);
      }
      CreateDomainFiles((startupflags & RESTART) && (startupflags & REOPEN));
    }
    InstallSignalHandler();
    printf("\n");
#ifdef PARALLEL
    if (parallel)  printf("Starting calculation...\n");
  }
#else  
  printf("Starting calculation...\n");
#endif
#if PARALLEL
  if (!parallel || master)  
#endif
    if (!(startupflags & NO_OUTPUT))  {
      WriteOutData(tstart, FALSE);
      WriteToDomainFiles(tstart);
    }
/*  TestChemicals("Start");  */
#if PARALLEL
  if (parallel)
    if (master)  MastersLoop(startupflags);
    else	 WorkersLoop(startupflags);
  else
#endif
    SequentialLoop(startupflags);
  printf("Closing output-Files...\n");
  if (plausible)  printf("Calculation terminated successfully\n\n");
  else  {
    if (!(startupflags & NO_OUTPUT))
      WriteOutData(actime, TRUE);
    printf("Calculation stopped because of inplausibilities!\n\n");
  }
  if (!(startupflags & NO_OUTPUT))  {
    CloseOutputFiles();
    CloseDomainFiles();
  }
#ifdef PARALLEL
  if (parallel)  {
    pvm_initsend(PvmDataRaw);
    pvm_pkint((int *)&end, 1, 1);
    SendCommand();
    pvm_exit();
  }
#endif
  return (0);
}
示例#21
0
// Parses command-line arguments to fill up config object. Also performs some
// semantic checks.
static int ParseCommandLine(int argc, const char* argv[],
                            WebPMuxConfig* config) {
  int i = 0;
  int feature_arg_index = 0;
  int ok = 1;

  while (i < argc) {
    Feature* const feature = &config->feature_;
    FeatureArg* const arg = &feature->args_[feature_arg_index];
    if (argv[i][0] == '-') {  // One of the action types or output.
      if (!strcmp(argv[i], "-set")) {
        if (ACTION_IS_NIL) {
          config->action_type_ = ACTION_SET;
        } else {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        }
        ++i;
      } else if (!strcmp(argv[i], "-get")) {
        if (ACTION_IS_NIL) {
          config->action_type_ = ACTION_GET;
        } else {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        }
        ++i;
      } else if (!strcmp(argv[i], "-strip")) {
        if (ACTION_IS_NIL) {
          config->action_type_ = ACTION_STRIP;
          feature->arg_count_ = 0;
        } else {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        }
        ++i;
      } else if (!strcmp(argv[i], "-frame")) {
        CHECK_NUM_ARGS_LESS(3, ErrParse);
        if (ACTION_IS_NIL || config->action_type_ == ACTION_SET) {
          config->action_type_ = ACTION_SET;
        } else {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        }
        if (FEATURETYPE_IS_NIL || feature->type_ == FEATURE_ANMF) {
          feature->type_ = FEATURE_ANMF;
        } else {
          ERROR_GOTO1("ERROR: Multiple features specified.\n", ErrParse);
        }
        arg->subtype_ = SUBTYPE_ANMF;
        arg->filename_ = argv[i + 1];
        arg->params_ = argv[i + 2];
        ++feature_arg_index;
        i += 3;
      } else if (!strcmp(argv[i], "-loop") || !strcmp(argv[i], "-bgcolor")) {
        CHECK_NUM_ARGS_LESS(2, ErrParse);
        if (ACTION_IS_NIL || config->action_type_ == ACTION_SET) {
          config->action_type_ = ACTION_SET;
        } else {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        }
        if (FEATURETYPE_IS_NIL || feature->type_ == FEATURE_ANMF) {
          feature->type_ = FEATURE_ANMF;
        } else {
          ERROR_GOTO1("ERROR: Multiple features specified.\n", ErrParse);
        }
        arg->subtype_ =
            !strcmp(argv[i], "-loop") ? SUBTYPE_LOOP : SUBTYPE_BGCOLOR;
        arg->params_ = argv[i + 1];
        ++feature_arg_index;
        i += 2;
      } else if (!strcmp(argv[i], "-o")) {
        CHECK_NUM_ARGS_LESS(2, ErrParse);
        config->output_ = argv[i + 1];
        i += 2;
      } else if (!strcmp(argv[i], "-info")) {
        CHECK_NUM_ARGS_NOT_EQUAL(2, ErrParse);
        if (config->action_type_ != NIL_ACTION) {
          ERROR_GOTO1("ERROR: Multiple actions specified.\n", ErrParse);
        } else {
          config->action_type_ = ACTION_INFO;
          feature->arg_count_ = 0;
          config->input_ = argv[i + 1];
        }
        i += 2;
      } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help")) {
        PrintHelp();
        DeleteConfig(config);
        exit(0);
      } else if (!strcmp(argv[i], "-version")) {
        const int version = WebPGetMuxVersion();
        printf("%d.%d.%d\n",
               (version >> 16) & 0xff, (version >> 8) & 0xff, version & 0xff);
        DeleteConfig(config);
        exit(0);
      } else if (!strcmp(argv[i], "--")) {
        if (i < argc - 1) {
          ++i;
          if (config->input_ == NULL) {
            config->input_ = argv[i];
          } else {
            ERROR_GOTO2("ERROR at '%s': Multiple input files specified.\n",
                        argv[i], ErrParse);
          }
        }
        break;
      } else {
        ERROR_GOTO2("ERROR: Unknown option: '%s'.\n", argv[i], ErrParse);
      }
    } else {  // One of the feature types or input.
      if (ACTION_IS_NIL) {
示例#22
0
int main(int argc, char **argv)
{
  char *Address = NULL;
  char *btaddr  = NULL;
  int  Port = 9777;

  int NumSamples = WIIREMOTE_SAMPLES;
  float DeadX    = DEADZONE_X;
  float DeadY    = DEADZONE_Y;

  char *JoyMap = NULL;

  for (int i = 0; i < argc; i++)
  {
    if (strcmp(argv[i], "--help") == 0)
    {
      PrintHelp(argv[0]);
      return 0;
    }
    else if (strcmp(argv[i], "--disable-mouseemulation") == 0)
      g_AllowMouse = false;
    else if (strcmp(argv[i], "--disable-reconnect") == 0)
      g_AllowReconnect = false;
    else if (strcmp(argv[i], "--disable-nunchuck") == 0)
      g_AllowNunchuck = false;
    else if (strcmp(argv[i], "--address") == 0 && ((i + 1) <= argc))
      Address = argv[i + 1];
    else if (strcmp(argv[i], "--port") == 0 && ((i + 1) <= argc))
      Port = atoi(argv[i + 1]);
    else if (strcmp(argv[i], "--btaddr") == 0 && ((i + 1) <= argc))
      btaddr = argv[i + 1];
    else if (strcmp(argv[i], "--deadzone-x") == 0 && ((i + 1) <= argc))
      DeadX = ((float)atoi(argv[i + 1]) / 100.0f);
    else if (strcmp(argv[i], "--deadzone-y") == 0 && ((i + 1) <= argc))
      DeadY = ((float)atoi(argv[i + 1]) / 100.0f);
    else if (strcmp(argv[i], "--deadzone") == 0 && ((i + 1) <= argc))
      DeadX = DeadY = ((float)atoi(argv[i + 1]) / 100.0f);
    else if (strcmp(argv[i], "--smoothing-samples") == 0 && ((i + 1) <= argc))
      NumSamples = atoi(argv[i + 1]);
    else if (strcmp(argv[i], "--joystick-map") == 0 && ((i + 1) <= argc))
      JoyMap = argv[i + 1];
  }

  if (NumSamples < 1 || DeadX < 0 || DeadY < 0 || DeadX > 1 || DeadY > 1)
  {
    PrintHelp(argv[0]);
    return -1;
  }

  CAddress my_addr(Address, Port); // Address => localhost on 9777
  int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  if (sockfd < 0)
  {
    printf("Error creating socket\n");
    return -1;
  }

  if (hci_get_route(NULL) < 0)
  {
    CPacketLOG log(LOGERROR, "Error No bluetooth device");
    log.Send(sockfd, my_addr);
    return -1;
  }
  g_Ping = new CPacketHELO("WiiRemote", ICON_PNG, g_BluetoothIconPath.c_str());
  g_WiiRemote.Initialize(my_addr, sockfd);
  g_WiiRemote.SetBluetoothAddress(btaddr);
  g_WiiRemote.SetSensativity(DeadX, DeadY, NumSamples);
  g_WiiRemote.SetSensativity(DeadX, DeadY, NumSamples);
  g_WiiRemote.SetJoystickMap(JoyMap);
  if (g_AllowMouse)
    g_WiiRemote.EnableMouseEmulation();
  else
    g_WiiRemote.DisableMouseEmulation();
 
  g_Ping->Send(sockfd, my_addr);
  bool HaveConnected = false;
  while (true)
  {
    bool Connected = g_WiiRemote.GetConnected();

    while (!Connected)
    {
      if (HaveConnected && !g_AllowReconnect)
        exit(0);

      Connected = g_WiiRemote.Connect();
      HaveConnected = true;
    }
#ifdef CWIID_OLD
//  Update the state of the WiiRemote more often when we have the old lib due too it not telling when disconnected..
    sleep (5);
#else
    sleep (15);
#endif
    g_Ping->Send(sockfd, my_addr);
    g_WiiRemote.Update();
  }
}
示例#23
0
int main(int argc, char* argv[])
{
    signal(SIGPIPE, SIG_IGN);
    const char * strConfigPath = "./conf/"PROJNAME".config.json";
    char configPath[128];
    snprintf(configPath, sizeof(configPath), "%s", strConfigPath);

    char c = '\0';
    while ((c = getopt(argc, argv, "c:vh?")) != -1)
    {
        switch (c)
        {
            case 'c':
                snprintf(configPath, sizeof(configPath), "%s", optarg);
                strConfigPath = configPath;
                break;
            case 'v':
                PrintVersion();
                return 0;
            case 'h':
            case '?':
                PrintHelp();
                return 0;
            default:
                break;
        }
    }
    // read the config and init the process
    myConfig = new Config (configPath);
    if (myConfig == NULL) {
        while(0 != raise(SIGKILL)){}
    }
    ROUTN( "=====================================================================");
    secore* mysecore = new secore(myConfig->PluginConfigPath());
    flexse_plugin* pflexse_plugin = new flexse_plugin(myConfig->PluginConfigPath(), mysecore);
    pthread_t ontime_thread_id;
    pthread_t update_thread_id;
    pthread_t day_merger_thread_id;
    pthread_t his_merger_thread_id;
    // init ontime thread
    MySuicideAssert ( 0 == pthread_create(&ontime_thread_id, NULL, ontime_thread, pflexse_plugin));
    // init update thread
    MySuicideAssert ( 0 == pthread_create(&update_thread_id, NULL, update_thread, pflexse_plugin));
    // init merger thread
    MySuicideAssert ( 0 == pthread_create(&day_merger_thread_id, NULL, day_merger_thread, pflexse_plugin));
    MySuicideAssert ( 0 == pthread_create(&his_merger_thread_id, NULL, his_merger_thread, pflexse_plugin));

    equeue* myequeue = new equeue(myConfig->PollSize(), myConfig->QueryPort());
    // generate service-thread
    thread_data_t* ptd = ServiceThreadInit(myequeue, pflexse_plugin);
    ROUTN( "All Service Threads Init Ok");
    // hold the place and not quit
    myequeue->running();
    for( uint32_t i=0; i<myConfig->ServiceThreadNum(); i++ )
    {
        pthread_join( ptd[i].thandle,NULL );
    }
    pthread_join( ontime_thread_id, NULL );
    pthread_join( update_thread_id, NULL );
    pthread_join( day_merger_thread_id, NULL );
    pthread_join( his_merger_thread_id, NULL );
    delete myConfig;
    delete mysecore;
    delete pflexse_plugin;
    delete myequeue;
    return 0;
}
示例#24
0
void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallback & a_Output)
{
	AStringVector split = StringSplit(a_Cmd, " ");
	if (split.empty())
	{
		return;
	}

	// "stop" and "restart" are handled in cRoot::ExecuteConsoleCommand, our caller, due to its access to controlling variables

	// "help" and "reload" are to be handled by MCS, so that they work no matter what
	if (split[0] == "help")
	{
		PrintHelp(split, a_Output);
		a_Output.Finished();
		return;
	}
	else if (split[0] == "reload")
	{
		cPluginManager::Get()->ReloadPlugins();
		a_Output.Finished();
		return;
	}
	else if (split[0] == "reloadplugins")
	{
		cPluginManager::Get()->ReloadPlugins();
		a_Output.Out("Plugins reloaded");
		a_Output.Finished();
		return;
	}
	else if (split[0] == "load")
	{
		if (split.size() > 1)
		{
			cPluginManager::Get()->RefreshPluginList();  // Refresh the plugin list, so that if the plugin was added just now, it is loadable
			a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin");
		}
		else
		{
			a_Output.Out("Usage: load <PluginFolder>");
		}
		a_Output.Finished();
		return;
	}
	else if (split[0] == "unload")
	{
		if (split.size() > 1)
		{
			cPluginManager::Get()->UnloadPlugin(split[1]);
			a_Output.Out("Plugin unload scheduled");
		}
		else
		{
			a_Output.Out("Usage: unload <PluginFolder>");
		}
		a_Output.Finished();
		return;
	}
	if (split[0] == "destroyentities")
	{
		class WorldCallback : public cWorldListCallback
		{
			virtual bool Item(cWorld * a_World) override
			{
				class EntityCallback : public cEntityCallback
				{
					virtual bool Item(cEntity * a_Entity) override
					{
						if (!a_Entity->IsPlayer())
						{
							a_Entity->Destroy();
						}
						return false;
					}
				} EC;
				a_World->ForEachEntity(EC);
				return false;
			}
		} WC;
		cRoot::Get()->ForEachWorld(WC);
		a_Output.Out("Destroyed all entities");
		a_Output.Finished();
		return;
	}

	// There is currently no way a plugin can do these (and probably won't ever be):
	else if (split[0].compare("chunkstats") == 0)
	{
		cRoot::Get()->LogChunkStats(a_Output);
		a_Output.Finished();
		return;
	}
	#if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER)
	else if (split[0].compare("dumpmem") == 0)
	{
		LeakFinderXmlOutput Output("memdump.xml");
		DumpUsedMemory(&Output);
		return;
	}

	else if (split[0].compare("killmem") == 0)
	{
		for (;;)
		{
			new char[100 * 1024 * 1024];  // Allocate and leak 100 MiB in a loop -> fill memory and kill MCS
		}
	}
	#endif

	else if (cPluginManager::Get()->ExecuteConsoleCommand(split, a_Output, a_Cmd))
	{
		a_Output.Finished();
		return;
	}

	a_Output.Out("Unknown command, type 'help' for all commands.");
	a_Output.Finished();
}
void
GetOptions
	(
	const JSize			argc,
	char*				argv[],
	JPtrArray<JString>*	inputFileList,
	JString*			dataVarName,
	JString*			outputFileName,
	JString*			databaseFileName,
	JBoolean*			debug
	)
{
	inputFileList->CleanOut();
	dataVarName->Clear();
	outputFileName->Clear();
	databaseFileName->Clear();
	*debug = kJFalse;

	JIndex index = 1;
	while (index < argc)
		{
		if (JIsVersionRequest(argv[index]))
			{
			PrintVersion();
			exit(0);
			}
		else if (JIsHelpRequest(argv[index]))
			{
			PrintHelp();
			exit(0);
			}

		else if (strcmp(argv[index], "--code") == 0)
			{
			JCheckForValues(2, &index, argc, argv);
			*dataVarName    = argv[index];
			*outputFileName = argv[index+1];
			index++;
			}

		else if (strcmp(argv[index], "--db") == 0)
			{
			JCheckForValues(1, &index, argc, argv);
			*databaseFileName = argv[index];
			}

		else if (strcmp(argv[index], "--debug") == 0)
			{
			*debug = kJTrue;
			}

		else if (argv[index][0] == '-')
			{
			cerr << argv[0] << ": unknown command line option: " << argv[index] << endl;
			}

		else
			{
			JString* inputFileName = new JString(argv[index]);
			assert( inputFileName != NULL );

			if (inputFileName->EndsWith("~") ||
				inputFileName->BeginsWith("#"))
				{
				delete inputFileName;
				}
			else
				{
				inputFileList->Append(inputFileName);
				}
			}

		index++;
		}

	if (inputFileList->IsEmpty())
		{
		cerr << argv[0] << ": no input files" << endl;
		exit(1);
		}
}
示例#26
0
int main(int argc, char **argv)
{
	Settings & conf = Settings::Get();
	int test = 0;

	DEBUG(DBG_ALL, DBG_INFO, "Free Heroes II, " + conf.GetVersion());

	conf.SetProgramPath(argv[0]);

	InitHomeDir();
	ReadConfigs();

#ifdef WITH_EDITOR
	if(RunEditor(argv[0])) conf.SetEditor();
#endif

	// getopt
	{
	    int opt;
	    while((opt = getopt(argc, argv, "hest:d:")) != -1)
    		switch(opt)
                {
#ifdef WITH_EDITOR
                    case 'e':
			conf.SetEditor();
			break;
#endif			
#ifndef BUILD_RELEASE
                    case 't':
			test = String::ToInt(optarg);
			break;

                    case 'd':
                	conf.SetDebug(optarg ? String::ToInt(optarg) : 0);
                	break;
#endif

#ifdef WITH_NET
                    case 's':
                	      return Network::RunDedicatedServer();
#endif
                    case '?':
                    case 'h': return PrintHelp(argv[0]);

                    default:  break;
		}
	}

	if(conf.SelectVideoDriver().size()) SetVideoDriver(conf.SelectVideoDriver());

	// random init
	Rand::Init();
        if(conf.Music()) SetTimidityEnvPath(conf);

	u32 subsystem = INIT_VIDEO | INIT_TIMER;

        if(conf.Sound() || conf.Music())
            subsystem |= INIT_AUDIO;
#ifdef WITH_AUDIOCD
        if(conf.MusicCD())
            subsystem |= INIT_CDROM | INIT_AUDIO;
#endif
#ifdef WITH_NET
        Network::SetProtocolVersion(static_cast<u16>(MAJOR_VERSION << 8) | MINOR_VERSION);
#endif

	if(SDL::Init(subsystem))
#ifndef ANDROID
	try
#endif
	{
	    std::atexit(SDL::Quit);

	    if(conf.Unicode()) SetLangEnvPath(conf);

	    if(Mixer::isValid())
	    {
		Mixer::SetChannels(8);
                Mixer::Volume(-1, Mixer::MaxVolume() * conf.SoundVolume() / 10);
                Music::Volume(Mixer::MaxVolume() * conf.MusicVolume() / 10);
                if(conf.Music())
		{
		    Music::SetFadeIn(3000);
		}
	    }
	    else
	    if(conf.Sound() || conf.Music())
	    {
		conf.ResetSound();
		conf.ResetMusic();
	    }

	    if(0 == conf.VideoMode().w || 0 == conf.VideoMode().h)
	    	conf.SetAutoVideoMode();

            Display::SetVideoMode(conf.VideoMode().w, conf.VideoMode().h, conf.DisplayFlags());

	    Display::HideCursor();
	    Display::SetCaption(GetCaption());

    	    //Ensure the mouse position is updated to prevent bad initial values.
    	    LocalEvent::Get().GetMouseCursor();

#ifdef WITH_ZLIB
    	    ZSurface zicons;
	    if(zicons.Load(_ptr_08067830.width, _ptr_08067830.height, _ptr_08067830.bpp, _ptr_08067830.pitch,
    		_ptr_08067830.rmask, _ptr_08067830.gmask, _ptr_08067830.bmask, _ptr_08067830.amask, _ptr_08067830.zdata, sizeof(_ptr_08067830.zdata)))
	    Display::SetIcons(zicons);
#endif
	    AGG::Cache & cache = AGG::Cache::Get();

            DEBUG(DBG_GAME, DBG_INFO, conf.String());
            DEBUG(DBG_GAME|DBG_ENGINE, DBG_INFO, Display::GetInfo());

	    // read data dir
	    if(! cache.ReadDataDir())
	    {
		DEBUG(DBG_GAME, DBG_WARN, "data files not found");
		ShowAGGError();
		return EXIT_FAILURE;
	    }

            // load palette
	    cache.LoadPAL();

	    // load font
	    cache.LoadFNT();

#ifdef WITH_ZLIB
	    LoadZLogo();
#endif

	    // init cursor
	    Cursor::Get().SetThemes(Cursor::POINTER);
	    AGG::ICNRegistryEnable(true);

	    // init game data
	    Game::Init();

	    // goto main menu
#ifdef WITH_EDITOR
	    Game::menu_t rs = (test ? Game::TESTING : (conf.Editor() ? Game::EDITMAINMENU : Game::MAINMENU));
#else
	    Game::menu_t rs = (test ? Game::TESTING : Game::MAINMENU);
#endif

	    while(rs != Game::QUITGAME)
	    {
		switch(rs)
		{
#ifdef WITH_EDITOR
	    		case Game::EDITMAINMENU:   rs = Game::Editor::MainMenu();	break;
	    		case Game::EDITNEWMAP:     rs = Game::Editor::NewMaps();	break;
	    		case Game::EDITLOADMAP:    rs = Game::Editor::LoadMaps();       break;
	    		case Game::EDITSTART:      rs = Game::Editor::StartGame();      break;
#endif
	    		case Game::MAINMENU:       rs = Game::MainMenu();		break;
	    		case Game::NEWGAME:        rs = Game::NewGame();		break;
	    		case Game::LOADGAME:       rs = Game::LoadGame();		break;
	    		case Game::HIGHSCORES:     rs = Game::HighScores();		break;
	    		case Game::CREDITS:        rs = Game::Credits();		break;
	    		case Game::NEWSTANDARD:    rs = Game::NewStandard();		break;
	    		case Game::NEWCAMPAIN:     rs = Game::NewCampain();		break;
	    		case Game::NEWMULTI:       rs = Game::NewMulti();		break;
			case Game::NEWHOTSEAT:     rs = Game::NewHotSeat();		break;
		        case Game::NEWNETWORK:     rs = Game::NewNetwork();		break;
		        case Game::NEWBATTLEONLY:  rs = Game::NewBattleOnly();		break;
	    		case Game::LOADSTANDARD:   rs = Game::LoadStandard();		break;
	    		case Game::LOADCAMPAIN:    rs = Game::LoadCampain();		break;
	    		case Game::LOADMULTI:      rs = Game::LoadMulti();		break;
	    		case Game::SCENARIOINFO:   rs = Game::ScenarioInfo();		break;
	    		case Game::SELECTSCENARIO: rs = Game::SelectScenario();		break;
			case Game::STARTGAME:      rs = Game::StartGame();      	break;
		        case Game::TESTING:        rs = Game::Testing(test);		break;

	    		default: break;
		}
	    }
	}
#ifndef ANDROID
	catch(Error::Exception)
	{
    	    AGG::Cache::Get().Dump();
#ifdef WITH_NET
            if(conf.GameType(Game::TYPE_NETWORK)) FH2LocalClient::Get().Logout("internal error");
#endif
	    VERBOSE(std::endl << conf.String());
	}
#endif
	return EXIT_SUCCESS;
}
/*
 * Usage %s [-p <EXE PAYLOAD PATH> [-o <OUT FILE NAME>]]
 */
int main(int argc, char *argv[]) {
	if (argc == 1) {
		// Do the magics.
		if (!Execute()) {
			PRINT_ERROR("The program terminated unsuccessfully.\n");
			return 1;
		}

		PRINT_SUCCESS("The program terminated successfully.\n");
		return 0;
	} else {
		if (argc >= 3 || argc >= 5) {
			BOOL bRet = FALSE;

			int c = 0;
			LPCSTR szPayloadPath = NULL;
			LPCSTR szNewFileName = DEFAULT_NAME;

			while ((c = getopt(argc, argv, "p:o:")) != -1) {
				switch (c) {
					case 'h':
						PrintHelp(argv[0]);
						return 0;
					case 'p':
						szPayloadPath = optarg;
						break;
					case 'o':
						szNewFileName = optarg;
						break;
					case '?':
						PRINT_WARNING("Unknown option: \"-%c\"\n", optopt);
						break;
					default:
						break;
				}
			}

			// Check mandatory payload argument.
			if (argc < 5 && szPayloadPath == NULL) {
				PRINT_ERROR("Payload argument must exist.\n");
				return 1;
			}

			PRINT_INFO("Building payload...\n");
			PRINT_INFO(
				"Out file name: \"%s\"\n",
				szNewFileName
			);
			PRINT_INFO("Payload: \"%s\"\n",
				szPayloadPath
			);

			bRet = BuildLoader(szNewFileName, szPayloadPath);

			if (!bRet) {
				PRINT_ERROR("The program terminated unsuccessfully.\n");
				return 1;
			} else {
				PRINT_SUCCESS("The program terminated successfully.\n");
				return 0;
			}
		}
	}

	PrintHelp(argv[0]);

	return 0;
}
示例#28
0
int main(int argc, char **argv) {

    PrintHelp(argc, argv) ;
    exit(0) ;

} /* end main */
示例#29
0
bool DistFieldGen::Run ()
{
  csRef<iImageIO> imageio = csQueryRegistry<iImageIO> (object_reg);
  csRef<iCommandLineParser> cmdline = csQueryRegistry<iCommandLineParser> (object_reg);

  const char* lowResImageFN = cmdline->GetName (0);
  const char* hiResImageFN = cmdline->GetName (1);
  if ((lowResImageFN == 0) || (hiResImageFN == 0))
  {
    PrintHelp ();
    return false;
  }

  const char* outFile = cmdline->GetOption ("output");
  if (outFile == 0) outFile = lowResImageFN;

  const char* mimeType = cmdline->GetOption ("format");
  if (mimeType == 0) mimeType = "image/png";

  // Read images
  csRef<iImage> loResImage;
  {
    csPhysicalFile file (lowResImageFN, "rb");
    if (file.GetStatus() != VFS_STATUS_OK) return false;
    csRef<iDataBuffer> buf = file.GetAllData();
    if (!buf.IsValid()) return false;
    loResImage = imageio->Load (buf, CS_IMGFMT_TRUECOLOR | CS_IMGFMT_ALPHA);
    if (!loResImage.IsValid()) return false;
  }
  csRef<iImage> hiResImage;
  {
    csPhysicalFile file (hiResImageFN, "rb");
    if (file.GetStatus() != VFS_STATUS_OK) return false;
    csRef<iDataBuffer> buf = file.GetAllData();
    if (!buf.IsValid()) return false;
    hiResImage = imageio->Load (buf, CS_IMGFMT_TRUECOLOR | CS_IMGFMT_ALPHA);
    if (!hiResImage.IsValid()) return false;
  }

  // Actual computation
  {
    ImageWrapper loImage (loResImage);
    ImageWrapper hiImage (hiResImage);

    int lheight = loImage.height;
    ComputationProgress progress (lheight);

    uint numThreads = CS::Platform::GetProcessorCount();
    if (numThreads > 1)
    {
      if (numThreads > (uint)lheight) numThreads = (uint)lheight;

      int linesPerThread = (lheight + numThreads - 1) / numThreads;
      int y1 = 0;
      csPDelArray<DistFieldComputer> computers;
      csPDelArray<CS::Threading::Thread> threads;
      CS::Threading::Barrier barrier (numThreads+1);
      for (uint t = 0; t <numThreads; t++)
      {
	DistFieldComputer* computer = new DistFieldComputer (loImage, hiImage, 
	  y1, csMin (y1 + linesPerThread, lheight), 
	  progress, &barrier);
	computers.Push (computer);
	threads.Push (new CS::Threading::Thread (computer, true));
	y1 += linesPerThread;
      }
      barrier.Wait ();

      bool status = true;
      for (uint t = 0; t <numThreads; t++)
	status &= computers[t]->runStatus;
      if (!status) return false;
    }
    else
    {
      DistFieldComputer computer (loImage, hiImage, 0, lheight, progress);
      if (!computer.Compute ()) return false;
    }
  }

  // Write output
  {
    csRef<iDataBuffer> outData = imageio->Save (loResImage, mimeType);
    if (!outData.IsValid()) return false;
    /* @@@ FIXME: csPhysicalFile can't open nonexisting files.
     * Needs to be fixed there ... */
    FILE* fp = fopen (outFile, "wb");
    csPhysicalFile file (fp, true);
    if (file.GetStatus() != VFS_STATUS_OK) return false;
    if (file.Write (outData->GetData(), outData->GetSize())
	!= outData->GetSize())
      return false;
  }

  return true;
}
示例#30
0
//
// Function	: _tmain
// Role		: Entry point to application
// Notes	: 
//
int _tmain(int argc, _TCHAR* argv[])
{
	
	int	chOpt;
	int	intOptHelp=0, intOptPrintNetDevs=0, intOptInDir=0, intOptOutDir=0, intOptNet=0;
	int	intOptTempDir=0, intOptConfig=0;

	// Extract all the options
	while ((chOpt = getopt(argc, argv, _T("c:f:n:i:o:t:l:v:dhp"))) != EOF) 
	switch(chOpt)
	{
		case _T('f'): // PCAP filter
			break;
		case _T('d'): // Debugging Mode
			bDebug=true;
			break;
		case _T('v'): // Verbose Mode
			bVerbose=true;
			intVerboseLvl=_wtol(optarg);
			break;
		case _T('l'): // Log File
			bLog=true;
			strLogFile=optarg;
			break;
		case _T('i'): // In directory
			intOptInDir=1;
			strInDir=optarg;
			break;
		case _T('o'): // Out directory
			intOptOutDir=1;
			strOutDir=optarg;
			break;
		case _T('n'): // Network device to sniff
			intOptNet=1;
			intNetDevice=_wtol(optarg);
			break;
		case _T('t'): // Temp directory
			intOptTempDir=1;
			strTempDir=optarg;
			break;
		case _T('c'): // Config files
			intOptConfig=1;
			strConfFile=optarg;
			break;
		case _T('h'): // Help
			intOptHelp=1;
			break;
		case _T('p'): // Print network devices
			intOptPrintNetDevs=1;
			break;
		default:
			fwprintf(stderr,L"[!] No handler - %c\n", chOpt);
			break;
	}

	// Print the banner
	PrintBanner();

	// Just print and exit
	if(intOptPrintNetDevs) PrintNetworkDeviceList();

	// Input validation
	if((!intOptInDir || !intOptOutDir || !intOptTempDir || !intOptNet) && !intOptConfig) {
		if(!intOptInDir) fprintf(stderr,"[!] Need to specify the input directory OR configuration file\n");
		if(!intOptOutDir) fprintf(stderr,"[!] Need to specify the output directory OR configuration file\n");
		if(!intOptTempDir) fprintf(stderr,"[!] Need to specify the temporary directory OR configuration file\n");
		if(!intOptNet) fprintf(stderr,"[!] Need to specify the network interface to use OR configuration file\n");
		fprintf(stderr,"\n");
		PrintHelp(argv[0]);
	}

	// Print help if required
	if(intOptHelp) PrintHelp(argv[0]);

	

	// Print some flag status
	if(!bDebug) fwprintf(stdout,L"[i] Debugging: Off\n"); 
	else fwprintf(stdout,L"[i] Debugging: On\n");
	if(!bVerbose) fwprintf(stdout,L"[i] Verbose: Off\n"); 
	else fwprintf(stdout,L"[i] Verbose: On (Level %u)\n",intVerboseLvl);
	if(intOptInDir)   fwprintf(stdout,L"[i] Input Directory : %s\n",strInDir);
    if(intOptOutDir)  fwprintf(stdout,L"[i] Output Directory: %s\n",strOutDir);
	if(intOptTempDir) fwprintf(stdout,L"[i] Temporary Directory: %s\n",strTempDir);

	// Get the required privs
	if(SetPrivilege(GetCurrentProcess(),L"SeLoadDriverPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeLoadDriverPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeLoadDriverPrivilege\n");
		return 1;
	}

	// Get some Windows privs - needs to be run as administrator / 
	// be granted these as required
	if(SetPrivilege(GetCurrentProcess(),L"SeDebugPrivilege")){
		fwprintf(stdout,L"[*] Privilege obtained - SeDebugPrivilege\n");
	} else{
		fwprintf(stderr,L"[!] Failed to obtain privilege - SeDebugPrivilege\n");
		return 1;
	}

	// Open the log file if required
	if(bVerbose && intVerboseLvl >= 5) fwprintf(stdout,L"[i] Log file chosen %s..\n",strLogFile);
    if(bLog && strLogFile!=NULL){
		if(OpenLog(strLogFile)){
			fwprintf(stdout,L"[*] Log file opened\n");
		} else {
			fwprintf(stderr,L"[!] Failed to open log file '%s' - !\n",strLogFile);
			return 1;
		}
	}


	// Call the main engine (vrrrrm!!)
	if(WhiteboxEngine()!=0){
		wbprintf(1,"[!] Engine suffered an unrecoverable error!\n");
		return 1;
	} else {
		wbprintf(0,"[!] Engine exited cleanly..\n");
	}

	//Close the log file if required
	if(bLog && fileLog!=NULL){
		if(CloseLog()){
			fwprintf(stdout,L"[*] Log file closed\n");
		} else {
			fwprintf(stderr,L"[!] Failed to close log file '%s' - !\n",strLogFile);
		}
	}

		
	return 0;
}