Example #1
0
int main(int argc, char *argv[])
{
  int i;
#ifdef COMPILE_WITH_GUI
  bool gui = false;
#endif
#ifdef COMPILE_WITH_MULTI_CORE
  I32 cores = 1;
#endif
  bool verbose = false;
  bool force = false;
  // fixed header changes 
  int set_version_major = -1;
  int set_version_minor = -1;
  int set_point_data_format = -1;
  int set_point_data_record_length = -1;
  int set_gps_time_endcoding = -1;
  // variable header changes
  bool remove_extra_header = false;
  bool remove_all_variable_length_records = false;
  int remove_variable_length_record = -1;
  int remove_variable_length_record_from = -1;
  int remove_variable_length_record_to = -1;
  bool remove_tiling_vlr = false;
  bool remove_original_vlr = false;
  // extract a subsequence
  unsigned int subsequence_start = 0;
  unsigned int subsequence_stop = U32_MAX;
  // fix files with corrupt points
  bool clip_to_bounding_box = false;
  double start_time = 0;

  LASreadOpener lasreadopener;
  GeoProjectionConverter geoprojectionconverter;
  LASwriteOpener laswriteopener;

  if (argc == 1)
  {
#ifdef COMPILE_WITH_GUI
    return las2las_gui(argc, argv, 0);
#else
    fprintf(stderr,"las2las.exe is better run in the command line or via the lastool.exe GUI\n");
    char file_name[256];
    fprintf(stderr,"enter input file: "); fgets(file_name, 256, stdin);
    file_name[strlen(file_name)-1] = '\0';
    lasreadopener.set_file_name(file_name);
    fprintf(stderr,"enter output file: "); fgets(file_name, 256, stdin);
    file_name[strlen(file_name)-1] = '\0';
    laswriteopener.set_file_name(file_name);
#endif
  }
  else
  {
    for (i = 1; i < argc; i++)
    {
      if (argv[i][0] == '–') argv[i][0] = '-';
      if (strcmp(argv[i],"-week_to_adjusted") == 0)
      {
        set_gps_time_endcoding = 1;
      }
      else if (strcmp(argv[i],"-adjusted_to_week") == 0)
      {
        set_gps_time_endcoding = 0;
      }
    }
    if (!geoprojectionconverter.parse(argc, argv)) byebye(true);
    if (!lasreadopener.parse(argc, argv)) byebye(true);
    if (!laswriteopener.parse(argc, argv)) byebye(true);
  }

  for (i = 1; i < argc; i++)
  {
    if (argv[i][0] == '\0')
    {
      continue;
    }
    else if (strcmp(argv[i],"-h") == 0 || strcmp(argv[i],"-help") == 0)
    {
      fprintf(stderr, "LAStools (by [email protected]) version %d\n", LAS_TOOLS_VERSION);
      usage();
    }
    else if (strcmp(argv[i],"-v") == 0 || strcmp(argv[i],"-verbose") == 0)
    {
      verbose = true;
    }
    else if (strcmp(argv[i],"-version") == 0)
    {
      fprintf(stderr, "LAStools (by [email protected]) version %d\n", LAS_TOOLS_VERSION);
      byebye();
    }
    else if (strcmp(argv[i],"-gui") == 0)
    {
#ifdef COMPILE_WITH_GUI
      gui = true;
#else
      fprintf(stderr, "WARNING: not compiled with GUI support. ignoring '-gui' ...\n");
#endif
    }
    else if (strcmp(argv[i],"-cores") == 0)
    {
#ifdef COMPILE_WITH_MULTI_CORE
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: number\n", argv[i]);
        usage(true);
      }
      argv[i][0] = '\0';
      i++;
      cores = atoi(argv[i]);
      argv[i][0] = '\0';
#else
      fprintf(stderr, "WARNING: not compiled with multi-core batching. ignoring '-cores' ...\n");
      i++;
#endif
    }
    else if (strcmp(argv[i],"-force") == 0)
    {
      force = true;
    }
    else if (strcmp(argv[i],"-subseq") == 0)
    {
      if ((i+2) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 2 arguments: start stop\n", argv[i]);
        byebye(true);
      }
      subsequence_start = (unsigned int)atoi(argv[i+1]); subsequence_stop = (unsigned int)atoi(argv[i+2]);
      i+=2;
    }
    else if (strcmp(argv[i],"-start_at_point") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: start\n", argv[i]);
        byebye(true);
      }
      subsequence_start = (unsigned int)atoi(argv[i+1]);
      i+=1;
    }
    else if (strcmp(argv[i],"-stop_at_point") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: stop\n", argv[i]);
        byebye(true);
      }
      subsequence_stop = (unsigned int)atoi(argv[i+1]);
      i+=1;
    }
    else if (strcmp(argv[i],"-set_version") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: major.minor\n", argv[i]);
        byebye(true);
      }
      if (sscanf(argv[i+1],"%d.%d",&set_version_major,&set_version_minor) != 2)
      {
        fprintf(stderr, "ERROR: cannot understand argument '%s' for '%s'\n", argv[i+1], argv[i]);
        usage(true);
      }
      i+=1;
    }
    else if (strcmp(argv[i],"-set_version_major") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: major\n", argv[i]);
        byebye(true);
      }
      set_version_major = atoi(argv[i+1]);
      i+=1;
    }
    else if (strcmp(argv[i],"-set_version_minor") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: minor\n", argv[i]);
        byebye(true);
      }
      set_version_minor = atoi(argv[i+1]);
      i+=1;
    }
    else if (strcmp(argv[i],"-remove_extra") == 0)
    {
      remove_extra_header = true;
    }
    else if (strcmp(argv[i],"-remove_all_vlrs") == 0)
    {
      remove_all_variable_length_records = true;
    }
    else if (strcmp(argv[i],"-remove_vlr") == 0)
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: number\n", argv[i]);
        byebye(true);
      }
      remove_variable_length_record = atoi(argv[i+1]);
      remove_variable_length_record_from = -1;
      remove_variable_length_record_to = -1;
      i++;
    }
    else if (strcmp(argv[i],"-remove_vlrs_from_to") == 0)
    {
      if ((i+2) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 2 arguments: start end\n", argv[i]);
        byebye(true);
      }
      remove_variable_length_record = -1;
      remove_variable_length_record_from = atoi(argv[i+1]);
      remove_variable_length_record_to = atoi(argv[i+2]);
      i+=2;
    }
    else if (strcmp(argv[i],"-remove_tiling_vlr") == 0)
    {
      remove_tiling_vlr = true;
      i++;
    }
    else if (strcmp(argv[i],"-remove_original_vlr") == 0)
    {
      remove_original_vlr = true;
      i++;
    }
    else if (strcmp(argv[i],"-set_point_type") == 0 || strcmp(argv[i],"-set_point_data_format") == 0 || strcmp(argv[i],"-point_type") == 0) 
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: type\n", argv[i]);
        byebye(true);
      }
      set_point_data_format = atoi(argv[i+1]);
      i++;
    }
    else if (strcmp(argv[i],"-set_point_data_record_length") == 0 || strcmp(argv[i],"-set_point_size") == 0 || strcmp(argv[i],"-point_size") == 0) 
    {
      if ((i+1) >= argc)
      {
        fprintf(stderr,"ERROR: '%s' needs 1 argument: size\n", argv[i]);
        byebye(true);
      }
      set_point_data_record_length = atoi(argv[i+1]);
      i++;
    }
    else if (strcmp(argv[i],"-clip_to_bounding_box") == 0 || strcmp(argv[i],"-clip_to_bb") == 0) 
    {
      clip_to_bounding_box = true;
    }
    else if ((argv[i][0] != '-') && (lasreadopener.get_file_name_number() == 0))
    {
      lasreadopener.add_file_name(argv[i]);
      argv[i][0] = '\0';
    }
    else
    {
      fprintf(stderr, "ERROR: cannot understand argument '%s'\n", argv[i]);
      usage(true);
    }
  }

#ifdef COMPILE_WITH_GUI
  if (gui)
  {
    return las2las_gui(argc, argv, &lasreadopener);
  }
#endif

#ifdef COMPILE_WITH_MULTI_CORE
  if (cores > 1)
  {
    if (lasreadopener.get_file_name_number() < 2)
    {
      fprintf(stderr,"WARNING: only %u input files. ignoring '-cores %d' ...\n", lasreadopener.get_file_name_number(), cores);
    }
    else if (lasreadopener.is_merged())
    {
      fprintf(stderr,"WARNING: input files merged on-the-fly. ignoring '-cores %d' ...\n", cores);
    }
    else
    {
      return las2las_multi_core(argc, argv, &geoprojectionconverter, &lasreadopener, &laswriteopener, cores);
    }
  }
#endif

  // check input

  if (!lasreadopener.active())
  {
    fprintf(stderr,"ERROR: no input specified\n");
    usage(true, argc==1);
  }
  
  BOOL extra_pass = laswriteopener.is_piped();

  // for piped output we need an extra pass

  if (extra_pass)
  {
    if (lasreadopener.is_piped())
    {
      fprintf(stderr, "ERROR: input and output cannot both be piped\n");
      usage(true);
    }
  }

  // make sure we do not corrupt the input file

  if (lasreadopener.get_file_name() && laswriteopener.get_file_name() && (strcmp(lasreadopener.get_file_name(), laswriteopener.get_file_name()) == 0))
  {
    fprintf(stderr, "ERROR: input and output file name are identical\n");
    usage(true);
  }
    
  // possibly loop over multiple input files

  while (lasreadopener.active())
  {
    if (verbose) start_time = taketime();

    // open lasreader

    LASreader* lasreader = lasreadopener.open();

    if (lasreader == 0)
    {
      fprintf(stderr, "ERROR: could not open lasreader\n");
      usage(true, argc==1);
    }

    // store the inventory for the header

    LASinventory lasinventory;

    // the point we write sometimes needs to be copied

    LASpoint* point = 0;

    // prepare the header for output

    if (set_gps_time_endcoding != -1)
    {
      if (set_gps_time_endcoding == 0)
      {
        if ((lasreader->header.global_encoding & 1) == 0)
        {
          fprintf(stderr, "WARNING: global encoding indicates file already in GPS week time\n");
          if (force)
          {
            fprintf(stderr, "         forced conversion.\n");
          }
          else
          {
            fprintf(stderr, "         use '-force' to force conversion.\n");
            byebye(true);
          }
        }
        else
        {
          lasreader->header.global_encoding &= ~1;
        }
      }
      else if (set_gps_time_endcoding == 1)
      {
        if ((lasreader->header.global_encoding & 1) == 1)
        {
          fprintf(stderr, "WARNING: global encoding indicates file already in Adjusted Standard GPS time\n");
          if (force)
          {
            fprintf(stderr, "         forced conversion.\n");
          }
          else
          {
            fprintf(stderr, "         use '-force' to force conversion.\n");
            byebye(true);
          }
        }
        else
        {
          lasreader->header.global_encoding |= 1;
        }
      }
    }

    if (set_version_major != -1)
    {
      if (set_version_major != 1)
      {
        fprintf(stderr, "ERROR: unknown version_major %d\n", set_version_major);
        byebye(true);
      }
      lasreader->header.version_major = (U8)set_version_major;
    }

    if (set_version_minor >= 0)
    {
      if (set_version_minor > 4)
      {
        fprintf(stderr, "ERROR: unknown version_minor %d\n", set_version_minor);
        byebye(true);
      }
      if (set_version_minor < 3)
      {
        if (lasreader->header.version_minor == 3)
        {
          lasreader->header.header_size -= 8;
          lasreader->header.offset_to_point_data -= 8;
        }
        else if (lasreader->header.version_minor >= 4)
        {
          lasreader->header.header_size -= (8 + 140);
          lasreader->header.offset_to_point_data -= (8 + 140);
        }
      }
      else if (set_version_minor == 3)
      {
        if (lasreader->header.version_minor < 3)
        {
          lasreader->header.header_size += 8;
          lasreader->header.offset_to_point_data += 8;
          lasreader->header.start_of_waveform_data_packet_record = 0;
        }
        else if (lasreader->header.version_minor >= 4)
        {
          lasreader->header.header_size -= 140;
          lasreader->header.offset_to_point_data -= 140;
        }
      }
      else if (set_version_minor == 4) 
      {
        if (lasreader->header.version_minor < 3)
        {
          lasreader->header.header_size += (8 + 140);
          lasreader->header.offset_to_point_data += (8 + 140);
          lasreader->header.start_of_waveform_data_packet_record = 0;
        }
        else if (lasreader->header.version_minor == 3)
        {
          lasreader->header.header_size += 140;
          lasreader->header.offset_to_point_data += 140;
        }
      }

      if ((set_version_minor <= 3) && (lasreader->header.version_minor >= 4))
      {
        if (lasreader->header.point_data_format > 5)
        {
          switch (lasreader->header.point_data_format)
          {
          case 6:
            fprintf(stderr, "WARNING: downgrading point_data_format from %d to 1\n", lasreader->header.point_data_format);
            lasreader->header.point_data_format = 1;
            fprintf(stderr, "         and point_data_record_length from %d to %d\n", lasreader->header.point_data_record_length, lasreader->header.point_data_record_length - 2);
            lasreader->header.point_data_record_length -= 2;
            break;
          case 7:
            fprintf(stderr, "WARNING: downgrading point_data_format from %d to 3\n", lasreader->header.point_data_format);
            lasreader->header.point_data_format = 3;
            fprintf(stderr, "         and point_data_record_length from %d to %d\n", lasreader->header.point_data_record_length, lasreader->header.point_data_record_length - 2);
            lasreader->header.point_data_record_length -= 2;
            break;
          case 8:
            fprintf(stderr, "WARNING: downgrading point_data_format from %d to 3\n", lasreader->header.point_data_format);
            lasreader->header.point_data_format = 3;
            fprintf(stderr, "         and point_data_record_length from %d to %d\n", lasreader->header.point_data_record_length, lasreader->header.point_data_record_length - 4);
            lasreader->header.point_data_record_length -= 4;
            break;
          case 9:
            fprintf(stderr, "WARNING: downgrading point_data_format from %d to 4\n", lasreader->header.point_data_format);
            lasreader->header.point_data_format = 4;
            fprintf(stderr, "         and point_data_record_length from %d to %d\n", lasreader->header.point_data_record_length, lasreader->header.point_data_record_length - 2);
            lasreader->header.point_data_record_length -= 2;
            break;
          case 10:
            fprintf(stderr, "WARNING: downgrading point_data_format from %d to 5\n", lasreader->header.point_data_format);
            lasreader->header.point_data_format = 5;
            fprintf(stderr, "         and point_data_record_length from %d to %d\n", lasreader->header.point_data_record_length, lasreader->header.point_data_record_length - 4);
            lasreader->header.point_data_record_length -= 4;
            break;
          default:
            fprintf(stderr, "ERROR: unknown point_data_format %d\n", lasreader->header.point_data_format);
            byebye(true);
          }
        }
        point = new LASpoint;
        point->init(&lasreader->header, lasreader->header.point_data_format, lasreader->header.point_data_record_length);
      }

      lasreader->header.version_minor = (U8)set_version_minor;
    }

    // are we supposed to change the point data format

    if (set_point_data_format != -1)
    {
      if (set_point_data_format < 0 || set_point_data_format > 10)
      {
        fprintf(stderr, "ERROR: unknown point_data_format %d\n", set_point_data_format);
        byebye(true);
      }
      // depending on the conversion we may need to copy the point
      if (convert_point_type_from_to[lasreader->header.point_data_format][set_point_data_format])
      {
        if (point == 0) point = new LASpoint;
      }
      lasreader->header.point_data_format = (U8)set_point_data_format;
      lasreader->header.clean_laszip();
      switch (lasreader->header.point_data_format)
      {
      case 0:
        lasreader->header.point_data_record_length = 20;
        break;
      case 1:
        lasreader->header.point_data_record_length = 28;
        break;
      case 2:
        lasreader->header.point_data_record_length = 26;
        break;
      case 3:
        lasreader->header.point_data_record_length = 34;
        break;
      case 4:
        lasreader->header.point_data_record_length = 57;
        break;
      case 5:
        lasreader->header.point_data_record_length = 63;
        break;
      case 6:
        lasreader->header.point_data_record_length = 30;
        break;
      case 7:
        lasreader->header.point_data_record_length = 36;
        break;
      case 8:
        lasreader->header.point_data_record_length = 38;
        break;
      case 9:
        lasreader->header.point_data_record_length = 59;
        break;
      case 10:
        lasreader->header.point_data_record_length = 67;
        break;
      }
    }

    // are we supposed to change the point data record length

    if (set_point_data_record_length != -1)
    {
      I32 num_extra_bytes = 0;
      switch (lasreader->header.point_data_format)
      {
      case 0:
        num_extra_bytes = set_point_data_record_length - 20;
        break;
      case 1:
        num_extra_bytes = set_point_data_record_length - 28;
        break;
      case 2:
        num_extra_bytes = set_point_data_record_length - 26;
        break;
      case 3:
        num_extra_bytes = set_point_data_record_length - 34;
        break;
      case 4:
        num_extra_bytes = set_point_data_record_length - 57;
        break;
      case 5:
        num_extra_bytes = set_point_data_record_length - 63;
        break;
      case 6:
        num_extra_bytes = set_point_data_record_length - 30;
        break;
      case 7:
        num_extra_bytes = set_point_data_record_length - 36;
        break;
      case 8:
        num_extra_bytes = set_point_data_record_length - 38;
        break;
      case 9:
        num_extra_bytes = set_point_data_record_length - 59;
        break;
      case 10:
        num_extra_bytes = set_point_data_record_length - 67;
        break;
      }
      if (num_extra_bytes < 0)
      {
        fprintf(stderr, "ERROR: point_data_format %d needs record length of at least %d\n", lasreader->header.point_data_format, set_point_data_record_length - num_extra_bytes);
        byebye(true);
      }
      if (lasreader->header.point_data_record_length < set_point_data_record_length)
      {
        if (!point) point = new LASpoint;
      }
      lasreader->header.point_data_record_length = (U16)set_point_data_record_length;
      lasreader->header.clean_laszip();
    }

    // if the point needs to be copied set up the data fields

    if (point)
    {
      point->init(&lasreader->header, lasreader->header.point_data_format, lasreader->header.point_data_record_length);
    }

    // maybe we should remove some stuff

    if (remove_extra_header)
    {
      lasreader->header.clean_user_data_in_header();
      lasreader->header.clean_user_data_after_header();
    }

    if (remove_all_variable_length_records)
    {
      lasreader->header.clean_vlrs();
      lasreader->header.clean_evlrs();
    }
    else
    {
      if (remove_variable_length_record != -1)
      {
        lasreader->header.remove_vlr(remove_variable_length_record);
      }
    
      if (remove_variable_length_record_from != -1)
      {
        for (i = remove_variable_length_record_to; i >= remove_variable_length_record_from; i--)
        {
          lasreader->header.remove_vlr(i);
        }
      }
    }

    if (remove_tiling_vlr)
    {
      lasreader->header.clean_lastiling();
    }

    if (remove_original_vlr)
    {
      lasreader->header.clean_lasoriginal();
    }

    // maybe we should add / change the projection information
    LASquantizer* reproject_quantizer = 0;
    LASquantizer* saved_quantizer = 0;
    if (geoprojectionconverter.has_projection(true) || geoprojectionconverter.has_projection(false))
    {
      if (!geoprojectionconverter.has_projection(true) && lasreader->header.vlr_geo_keys)
      {
        geoprojectionconverter.set_projection_from_geo_keys(lasreader->header.vlr_geo_keys[0].number_of_keys, (GeoProjectionGeoKeys*)lasreader->header.vlr_geo_key_entries, lasreader->header.vlr_geo_ascii_params, lasreader->header.vlr_geo_double_params);
      }

      if (geoprojectionconverter.has_projection(true) && geoprojectionconverter.has_projection(false))
      {
        reproject_quantizer = new LASquantizer();
        double point[3];
        point[0] = (lasreader->header.min_x+lasreader->header.max_x)/2;
        point[1] = (lasreader->header.min_y+lasreader->header.max_y)/2;
        point[2] = (lasreader->header.min_z+lasreader->header.max_z)/2;
        geoprojectionconverter.to_target(point);
        reproject_quantizer->x_scale_factor = geoprojectionconverter.get_target_precision();
        reproject_quantizer->y_scale_factor = geoprojectionconverter.get_target_precision();
        reproject_quantizer->z_scale_factor = geoprojectionconverter.get_target_elevation_precision();
        reproject_quantizer->x_offset = ((I64)((point[0]/reproject_quantizer->x_scale_factor)/10000000))*10000000*reproject_quantizer->x_scale_factor;
        reproject_quantizer->y_offset = ((I64)((point[1]/reproject_quantizer->y_scale_factor)/10000000))*10000000*reproject_quantizer->y_scale_factor;
        reproject_quantizer->z_offset = ((I64)((point[2]/reproject_quantizer->z_scale_factor)/10000000))*10000000*reproject_quantizer->z_scale_factor;
      }

      int number_of_keys;
      GeoProjectionGeoKeys* geo_keys = 0;
      int num_geo_double_params;
      double* geo_double_params = 0;

      if (geoprojectionconverter.get_geo_keys_from_projection(number_of_keys, &geo_keys, num_geo_double_params, &geo_double_params, !geoprojectionconverter.has_projection(false)))
      {
        lasreader->header.set_geo_keys(number_of_keys, (LASvlr_key_entry*)geo_keys);
        free(geo_keys);
        if (geo_double_params)
        {
          lasreader->header.set_geo_double_params(num_geo_double_params, geo_double_params);
          free(geo_double_params);
        }
        else
        {
          lasreader->header.del_geo_double_params();
        }
        lasreader->header.del_geo_ascii_params();
      }
    }

    // do we need an extra pass

    BOOL extra_pass = laswriteopener.is_piped();

    // for piped output we need an extra pass

    if (extra_pass)
    {
      if (lasreadopener.is_piped())
      {
        fprintf(stderr, "ERROR: input and output cannot both be piped\n");
        usage(true);
      }

#ifdef _WIN32
      if (verbose) fprintf(stderr, "extra pass for piped output: reading %I64d points ...\n", lasreader->npoints);
#else
      if (verbose) fprintf(stderr, "extra pass for piped output: reading %lld points ...\n", lasreader->npoints);
#endif

      // maybe seek to start position

      if (subsequence_start) lasreader->seek(subsequence_start);

      while (lasreader->read_point())
      {
        if (lasreader->p_count > subsequence_stop) break;

        if (clip_to_bounding_box)
        {
          if (!lasreader->point.inside_box(lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z))
          {
            continue;
          }
        }

        if (reproject_quantizer)
        {
          lasreader->point.compute_coordinates();
          geoprojectionconverter.to_target(lasreader->point.coordinates);
          lasreader->point.compute_XYZ(reproject_quantizer);
        }
        lasinventory.add(&lasreader->point);
      }
      lasreader->close();

      if (reproject_quantizer) lasreader->header = *reproject_quantizer;

      lasinventory.update_header(&lasreader->header);

      if (verbose) { fprintf(stderr,"extra pass took %g sec.\n", taketime()-start_time); start_time = taketime(); }
#ifdef _WIN32
      if (verbose) fprintf(stderr, "piped output: reading %I64d and writing %I64d points ...\n", lasreader->npoints, lasinventory.extended_number_of_point_records);
#else
      if (verbose) fprintf(stderr, "piped output: reading %lld and writing %lld points ...\n", lasreader->npoints, lasinventory.extended_number_of_point_records);
#endif
    }
    else
    {
      if (reproject_quantizer)
      {
        saved_quantizer = new LASquantizer();
        *saved_quantizer = lasreader->header;
        lasreader->header = *reproject_quantizer;
      }
#ifdef _WIN32
      if (verbose) fprintf(stderr, "reading %I64d and writing all surviving points ...\n", lasreader->npoints);
#else
      if (verbose) fprintf(stderr, "reading %lld and writing all surviving points ...\n", lasreader->npoints);
#endif
    }

    // check output

    if (!laswriteopener.active())
    {
      // create name from input name
      laswriteopener.make_file_name(lasreadopener.get_file_name());
    }

    // prepare the header for the surviving points

    strncpy(lasreader->header.system_identifier, "LAStools (c) by rapidlasso GmbH", 32);
    lasreader->header.system_identifier[31] = '\0';
    char temp[64];
    sprintf(temp, "las2las (version %d)", LAS_TOOLS_VERSION);
    strncpy(lasreader->header.generating_software, temp, 32);
    lasreader->header.generating_software[31] = '\0';

    // open laswriter

    LASwriter* laswriter = laswriteopener.open(&lasreader->header);

    if (laswriter == 0)
    {
      fprintf(stderr, "ERROR: could not open laswriter\n");
      byebye(true, argc==1);
    }

    // for piped output we need to re-open the input file

    if (extra_pass)
    {
      if (!lasreadopener.reopen(lasreader))
      {
        fprintf(stderr, "ERROR: could not re-open lasreader\n");
        byebye(true);
      }
    }
    else
    {
      if (reproject_quantizer)
      {
        lasreader->header = *saved_quantizer;
        delete saved_quantizer;
      }
    }

    // maybe seek to start position

    if (subsequence_start) lasreader->seek(subsequence_start);

    // loop over points

    if (point)
    {
      while (lasreader->read_point())
      {
        if (lasreader->p_count > subsequence_stop) break;

        if (clip_to_bounding_box)
        {
          if (!lasreader->point.inside_box(lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z))
          {
            continue;
          }
        }

        if (reproject_quantizer)
        {
          lasreader->point.compute_coordinates();
          geoprojectionconverter.to_target(lasreader->point.coordinates);
          lasreader->point.compute_XYZ(reproject_quantizer);
        }
        *point = lasreader->point;
        laswriter->write_point(point);
        // without extra pass we need inventory of surviving points
        if (!extra_pass) laswriter->update_inventory(point);
      }
      delete point;
      point = 0;
    }
    else
    {
      while (lasreader->read_point())
      {
        if (lasreader->p_count > subsequence_stop) break;

        if (clip_to_bounding_box)
        {
          if (!lasreader->point.inside_box(lasreader->header.min_x, lasreader->header.min_y, lasreader->header.min_z, lasreader->header.max_x, lasreader->header.max_y, lasreader->header.max_z))
          {
            continue;
          }
        }

        if (reproject_quantizer)
        {
          lasreader->point.compute_coordinates();
          geoprojectionconverter.to_target(lasreader->point.coordinates);
          lasreader->point.compute_XYZ(reproject_quantizer);
        }
        laswriter->write_point(&lasreader->point);
        // without extra pass we need inventory of surviving points
        if (!extra_pass) laswriter->update_inventory(&lasreader->point);
      }
    }

    // without the extra pass we need to fix the header now

    if (!extra_pass)
    {
      if (reproject_quantizer) lasreader->header = *reproject_quantizer;
      laswriter->update_header(&lasreader->header, TRUE);
      if (verbose) { fprintf(stderr,"total time: %g sec. written %u surviving points.\n", taketime()-start_time, (U32)laswriter->p_count); }
    }
    else
    {
      if (verbose) { fprintf(stderr,"main pass took %g sec.\n", taketime()-start_time); }
    }

    laswriter->close();
    delete laswriter;

    lasreader->close();
    delete lasreader;

    if (reproject_quantizer) delete reproject_quantizer;

    laswriteopener.set_file_name(0);
  }

  byebye(false, argc==1);

  return 0;
}
Example #2
0
int
main(int argc, char **argv)
{
	FILE *mbox;
	struct passwd *pwd;
	int ch, count, newline;
	const char *file;
	char *sender, *p;
#if MAXPATHLEN > BUFSIZ
	char buf[MAXPATHLEN];
#else
	char buf[BUFSIZ];
#endif

	file = sender = NULL;
	count = -1;
	while ((ch = getopt(argc, argv, "cf:s:")) != -1)
		switch (ch) {
		case 'c':
			count = 0;
			break;
		case 'f':
			file = optarg;
			break;
		case 's':
			sender = optarg;
			for (p = sender; *p; ++p)
				*p = tolower(*p);
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (file == NULL) {
		if (argc) {
			(void)snprintf(buf, sizeof(buf), "%s/%s", _PATH_MAILDIR, *argv);
			file  = buf;
		} else {
			if (!(file = getenv("MAIL"))) {
				if (!(pwd = getpwuid(getuid())))
					errx(1, "no password file entry for you");
				file = pwd->pw_name;
				(void)snprintf(buf, sizeof(buf),
				    "%s/%s", _PATH_MAILDIR, file);
				file = buf;
			}
		}
	}

	/* read from stdin */
	if (strcmp(file, "-") == 0) {
		mbox = stdin;
	} 
	else if ((mbox = fopen(file, "r")) == NULL) {
		errx(1, "can't read %s", file);
	}
	for (newline = 1; fgets(buf, sizeof(buf), mbox);) {
		if (*buf == '\n') {
			newline = 1;
			continue;
		}
		if (newline && !strncmp(buf, "From ", 5) &&
		    (!sender || match(buf + 5, sender))) {
			if (count != -1)
				count++;
			else
				printf("%s", buf);
		}
		newline = 0;
	}
	if (count != -1)
		printf("There %s %d message%s in your incoming mailbox.\n",
		    count == 1 ? "is" : "are", count, count == 1 ? "" : "s"); 
	fclose(mbox);
	exit(0);
}
Example #3
0
static void parse_option(int argc, char ** argv) {
	int ch, rc;
	int argcorig = argc;
#ifdef HAVE_GETOPT_LONG
	/* getopt_long isn't portable, it's GNU extension */
	struct option lo[] = {  {"help", 0, 0, 'h' },
				{"version", 0, 0, 'v'},
				{"debug", 0, 0, 'd'},
				{0, 0, 0, 0}
				};
	while ((ch = getopt_long(argc, argv, "dDhp:vVw:W:", lo, 0)) != -1) {
#else
	while ((ch = getopt(argc, argv, "dDhp:vVw:W:")) != -1) {
#endif
		switch (ch) {
		case 'h':
			usage();
			break;

		case 'd':
		case 'D':
			log_type = LOGTYPE_STDERR;
			increase_debuglevel();
			break;

		case 'p':
			rc = sscanf(optarg, "%u", &port);
			if (rc != 1) {
				fprintf(stderr, "failed to "
					"parse port number.\n");
				usage();
			}
			break;

		case 'v':
		case 'V':
			fprintf(stderr, "flowgrindd version: %s\n", FLOWGRIND_VERSION);
			exit(0);

		case 'w':
		case 'W':
#ifdef HAVE_LIBPCAP
			dump_filename_prefix_server = optarg;
			break;
#endif
		default:
			usage();
		}
	}
	argc = argcorig;

	argc -= optind;

	if (argc != 0)
		usage();
}

int main(int argc, char ** argv)
{
	struct sigaction sa;

	xmlrpc_env env;

	/* update progname from argv[0] */
	if (argc > 0) {
		/* Strip path */
		char *tok = strrchr(argv[0], '/');
		if (tok)
			tok++;
		else
			tok = argv[0];
		if (*tok) {
			strncpy(progname, tok, sizeof(progname));
			progname[sizeof(progname) - 1] = 0;
		}
	}

	if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
		error(ERR_FATAL, "Could not ignore SIGPIPE: %s",
				strerror(errno));
		/* NOTREACHED */
	}

	sa.sa_handler = sighandler;
	sa.sa_flags = 0;
	sigemptyset (&sa.sa_mask);
	sigaction (SIGHUP, &sa, NULL);
	sigaction (SIGALRM, &sa, NULL);
	sigaction (SIGCHLD, &sa, NULL);

	parse_option(argc, argv);
	logging_init();
#ifdef HAVE_LIBPCAP
	fg_pcap_init();
#endif
	if (log_type == LOGTYPE_SYSLOG) {
		/* Need to call daemon() before creating the thread because
		 * it internally calls fork() which does not copy threads. */
		if (daemon(0, 0) == -1) {
			error(ERR_FATAL, "daemon() failed: %s", strerror(errno));
		}
		logging_log(LOG_NOTICE, "flowgrindd daemonized");
	}

	create_daemon_thread();

	xmlrpc_env_init(&env);

	run_rpc_server(&env, port);

	fprintf(stderr, "Control should never reach end of main()\n");

	return 0;
}
Example #4
0
/**********************************************************************
*%FUNCTION: main
*%ARGUMENTS:
* argc, argv -- usual suspects
*%RETURNS:
* EXIT_SUCCESS or EXIT_FAILURE
*%DESCRIPTION:
* Main program.  Options:
* -C ifname           -- Use interface for PPPoE clients
* -S ifname           -- Use interface for PPPoE servers
* -B ifname           -- Use interface for both clients and servers
* -n sessions         -- Maximum of "n" sessions
***********************************************************************/
int
main(int argc, char *argv[])
{
    int opt;
    int nsess = DEFAULT_SESSIONS;
    struct sigaction sa;
    int beDaemon = 1;

    if (getuid() != geteuid() ||
	getgid() != getegid()) {
	fprintf(stderr, "SECURITY WARNING: pppoe-relay will NOT run suid or sgid.  Fix your installation.\n");
	exit(1);
    }


    openlog("pppoe-relay", LOG_PID, LOG_DAEMON);

    while((opt = getopt(argc, argv, "hC:S:B:n:i:F")) != -1) {
	switch(opt) {
	case 'h':
	    usage(argv[0]);
	    break;
	case 'F':
	    beDaemon = 0;
	    break;
	case 'C':
	    addInterface(optarg, 1, 0);
	    break;
	case 'S':
	    addInterface(optarg, 0, 1);
	    break;
	case 'B':
	    addInterface(optarg, 1, 1);
	    break;
	case 'i':
	    if (sscanf(optarg, "%u", &IdleTimeout) != 1) {
		fprintf(stderr, "Illegal argument to -i: should be -i timeout\n");
		exit(EXIT_FAILURE);
	    }
	    CleanPeriod = IdleTimeout / TIMEOUT_DIVISOR;
	    if (CleanPeriod < MIN_CLEAN_PERIOD) CleanPeriod = MIN_CLEAN_PERIOD;
	    break;
	case 'n':
	    if (sscanf(optarg, "%d", &nsess) != 1) {
		fprintf(stderr, "Illegal argument to -n: should be -n #sessions\n");
		exit(EXIT_FAILURE);
	    }
	    if (nsess < 1 || nsess > 65534) {
		fprintf(stderr, "Illegal argument to -n: must range from 1 to 65534\n");
		exit(EXIT_FAILURE);
	    }
	    break;
	default:
	    usage(argv[0]);
	}
    }

#ifdef USE_LINUX_PACKET
#ifndef HAVE_STRUCT_SOCKADDR_LL
    fprintf(stderr, "The PPPoE relay does not work on Linux 2.0 kernels.\n");
    exit(EXIT_FAILURE);
#endif
#endif

    /* Check that at least two interfaces were defined */
    if (NumInterfaces < 2) {
	fprintf(stderr, "%s: Must define at least two interfaces\n",
		argv[0]);
	exit(EXIT_FAILURE);
    }

    /* Make a pipe for the cleaner */
    if (pipe(CleanPipe) < 0) {
	fatalSys("pipe");
    }

    /* Set up alarm handler */
    sa.sa_handler = alarmHandler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGALRM, &sa, NULL) < 0) {
	fatalSys("sigaction");
    }

    /* Allocate memory for sessions, etc. */
    initRelay(nsess);

    /* Daemonize -- UNIX Network Programming, Vol. 1, Stevens */
    if (beDaemon) {
	int i;
	i = fork();
	if (i < 0) {
	    fatalSys("fork");
	} else if (i != 0) {
	    /* parent */
	    exit(0);
	}
	setsid();
	signal(SIGHUP, SIG_IGN);
	i = fork();
	if (i < 0) {
	    fatalSys("fork");
	} else if (i != 0) {
	    exit(0);
	}

	chdir("/");
	closelog();
	for (i=0; i<CLOSEFD; i++) {
	    if (!keepDescriptor(i)) {
		close(i);
	    }
	}
	/* We nuked our syslog descriptor... */
	openlog("pppoe-relay", LOG_PID, LOG_DAEMON);
    }

    /* Kick off SIGALRM if there is an idle timeout */
    if (IdleTimeout) alarm(1);

    /* Enter the relay loop */
    relayLoop();

    /* Shouldn't ever get here... */
    return EXIT_FAILURE;
}
Example #5
0
int
main (int argc, char **argv)
{
  struct jpeg_decompress_struct srcinfo;
  struct jpeg_compress_struct dstinfo;
  struct jpeg_error_mgr jsrcerr, jdsterr;
#ifdef PROGRESS_REPORT
  struct cdjpeg_progress_mgr progress;
#endif
  jvirt_barray_ptr * src_coef_arrays;
  jvirt_barray_ptr * dst_coef_arrays;
  int file_index;
  FILE * input_file;
  FILE * output_file;

  /* On Mac, fetch a command line. */
#ifdef USE_CCOMMAND
  argc = ccommand(&argv);
#endif

  progname = argv[0];
  if (progname == NULL || progname[0] == 0)
    progname = "jpegtran";	/* in case C library doesn't provide it */

  /* Initialize the JPEG decompression object with default error handling. */
  srcinfo.err = jpeg_std_error(&jsrcerr);
  jpeg_create_decompress(&srcinfo);
  /* Initialize the JPEG compression object with default error handling. */
  dstinfo.err = jpeg_std_error(&jdsterr);
  jpeg_create_compress(&dstinfo);

  /* Now safe to enable signal catcher.
   * Note: we assume only the decompression object will have virtual arrays.
   */
#ifdef NEED_SIGNAL_CATCHER
  enable_signal_catcher((j_common_ptr) &srcinfo);
#endif

  /* Scan command line to find file names.
   * It is convenient to use just one switch-parsing routine, but the switch
   * values read here are mostly ignored; we will rescan the switches after
   * opening the input file.  Also note that most of the switches affect the
   * destination JPEG object, so we parse into that and then copy over what
   * needs to affects the source too.
   */

  file_index = parse_switches(&dstinfo, argc, argv, 0, FALSE);
  jsrcerr.trace_level = jdsterr.trace_level;
  srcinfo.mem->max_memory_to_use = dstinfo.mem->max_memory_to_use;

#ifdef TWO_FILE_COMMANDLINE
  /* Must have either -outfile switch or explicit output file name */
  if (outfilename == NULL) {
    if (file_index != argc-2) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
    outfilename = argv[file_index+1];
  } else {
    if (file_index != argc-1) {
      fprintf(stderr, "%s: must name one input and one output file\n",
	      progname);
      usage();
    }
  }
#else
  /* Unix style: expect zero or one file name */
  if (file_index < argc-1) {
    fprintf(stderr, "%s: only one input file\n", progname);
    usage();
  }
#endif /* TWO_FILE_COMMANDLINE */

  /* Open the input file. */
  if (file_index < argc) {
    if ((input_file = fopen(argv[file_index], READ_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, argv[file_index]);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default input file is stdin */
    input_file = read_stdin();
  }

  /* Open the output file. */
  if (outfilename != NULL) {
    if ((output_file = fopen(outfilename, WRITE_BINARY)) == NULL) {
      fprintf(stderr, "%s: can't open %s\n", progname, outfilename);
      exit(EXIT_FAILURE);
    }
  } else {
    /* default output file is stdout */
    output_file = write_stdout();
  }

#ifdef PROGRESS_REPORT
  start_progress_monitor((j_common_ptr) &dstinfo, &progress);
#endif

  /* Specify data source for decompression */
  jpeg_stdio_src(&srcinfo, input_file);

  /* Enable saving of extra markers that we want to copy */
  jcopy_markers_setup(&srcinfo, copyoption);

  /* Read file header */
  (void) jpeg_read_header(&srcinfo, TRUE);

  /* Any space needed by a transform option must be requested before
   * jpeg_read_coefficients so that memory allocation will be done right.
   */
#if TRANSFORMS_SUPPORTED
  jtransform_request_workspace(&srcinfo, &transformoption);
#endif

  /* Read source file as DCT coefficients */
  src_coef_arrays = jpeg_read_coefficients(&srcinfo);

  /* Initialize destination compression parameters from source values */
  jpeg_copy_critical_parameters(&srcinfo, &dstinfo);

  /* Adjust destination parameters if required by transform options;
   * also find out which set of coefficient arrays will hold the output.
   */
#if TRANSFORMS_SUPPORTED
  dst_coef_arrays = jtransform_adjust_parameters(&srcinfo, &dstinfo,
						 src_coef_arrays,
						 &transformoption);
#else
  dst_coef_arrays = src_coef_arrays;
#endif

  /* Adjust default compression parameters by re-parsing the options */
  file_index = parse_switches(&dstinfo, argc, argv, 0, TRUE);

  /* Specify data destination for compression */
  jpeg_stdio_dest(&dstinfo, output_file);

  /* Start compressor (note no image data is actually written here) */
  jpeg_write_coefficients(&dstinfo, dst_coef_arrays);

  /* Copy to the output file any extra markers that we want to preserve */
  jcopy_markers_execute(&srcinfo, &dstinfo, copyoption);

  /* Execute image transformation, if any */
#if TRANSFORMS_SUPPORTED
  jtransform_execute_transformation(&srcinfo, &dstinfo,
				    src_coef_arrays,
				    &transformoption);
#endif

  /* Finish compression and release memory */
  jpeg_finish_compress(&dstinfo);
  jpeg_destroy_compress(&dstinfo);
  (void) jpeg_finish_decompress(&srcinfo);
  jpeg_destroy_decompress(&srcinfo);

  /* Close files, if we opened them */
  if (input_file != stdin)
    fclose(input_file);
  if (output_file != stdout)
    fclose(output_file);

#ifdef PROGRESS_REPORT
  end_progress_monitor((j_common_ptr) &dstinfo);
#endif

  /* All done. */
  exit(jsrcerr.num_warnings + jdsterr.num_warnings ?EXIT_WARNING:EXIT_SUCCESS);
  return 0;			/* suppress no-return-value warnings */
}
Example #6
0
int main(int argc, char **argv)
{
	dev_name = "/dev/video0";

	for (;; ) {
		int idx;
		int c;

		c = getopt_long(argc, argv,
		                short_options, long_options, &idx);

		if (-1 == c)
			break;

		switch (c) {
		case 0: /* getopt_long() flag */
			break;

		case 'd':
			dev_name = optarg;
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);

		case 'm':
			io = IO_METHOD_MMAP;
			break;

		case 'r':
			io = IO_METHOD_READ;
			break;

		case 'u':
			io = IO_METHOD_USERPTR;
			break;

		case 'o':
			out_buf++;
			break;

		case 'f':
			force_format++;
			break;

		case 'c':
			errno = 0;
			frame_count = strtol(optarg, NULL, 0);
			if (errno)
				errno_exit(optarg);
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
		}
	}

	open_device();
	init_device();
	start_capturing();
	mainloop();
	stop_capturing();
	uninit_device();
	close_device();
	fprintf(stderr, "\n");
	return 0;
}
Example #7
0
int main (int argc, char *argv[])
{
  char *oname = nullptr, *dot = nullptr, *filename = nullptr;
  char str[32];

  const char* ext=EXT;

  int
    n, n1,n2,err,
    num_axes,num_blocks,
    num_side_sets,num_node_sets,num_time_steps,
    num_info_lines,num_global_vars,
    num_nodal_vars,num_element_vars,num_nodeset_vars, num_sideset_vars;

  size_t num_nodes = 0;
  size_t num_elements = 0;

  int mat_version = 73;

  /* process arguments */
  for (int j=1; j< argc; j++){
    if ( strcmp(argv[j],"-t")==0){    /* write text file (*.m) */
      del_arg(&argc,argv,j);
      textfile=1;
      j--;
      continue;
    }
    if ( strcmp(argv[j],"-h")==0){    /* write help info */
      del_arg(&argc,argv,j);
      usage();
      exit(1);
    }
    if ( strcmp(argv[j],"-d")==0){    /* write help info */
      del_arg(&argc,argv,j);
      j--;
      debug = 1;
      continue;
    }
    if ( strcmp(argv[j],"-v73")==0){    /* Version 7.3 */
      del_arg(&argc,argv,j);
      mat_version = 73;
      j--;
      continue;
    }
    // This matches the option used in matlab
    if ( (strcmp(argv[j],"-v7.3")==0) || (strcmp(argv[j],"-V7.3")==0)){    /* Version 7.3 */
      del_arg(&argc,argv,j);
      mat_version = 73;
      j--;
      continue;
    }
    if ( strcmp(argv[j],"-v5")==0){    /* Version 5 (default) */
      del_arg(&argc,argv,j);
      mat_version = 50;
      j--;
      continue;
    }
    if ( strcmp(argv[j],"-o")==0){    /* specify output file name */
      del_arg(&argc,argv,j);
      if ( argv[j] ){
        oname=(char*)calloc(strlen(argv[j])+10,sizeof(char));
        strcpy(oname,argv[j]);
        del_arg(&argc,argv,j);
        std::cout << "output file: " << oname << "\n";
      }
      else {
        std::cerr << "ERROR: Invalid output file specification.\n";
        return 2;
      }
      j--;

      continue;
    }
  }

  /* QA Info */
  printf("%s: %s, %s\n", qainfo[0], qainfo[2], qainfo[1]);

  /* usage message*/
  if (argc != 2){
    usage();
    exit(1);
  }

  /* open output file */
  if ( textfile )
    ext=".m";

  if ( !oname ){
    filename = (char*)malloc( strlen(argv[1])+10);
    strcpy(filename,argv[1]);
    dot=strrchr(filename,'.');
    if ( dot ) *dot='\0';
    strcat(filename,ext);
  }
  else {
    filename=oname;
  }

  if ( textfile ){
    m_file = fopen(filename,"w");
    if (!m_file ){
      std::cerr << "ERROR: Unable to open " << filename << "\n";
      exit(1);
    }
  }
  else {
    if (mat_version == 50) {
      mat_file = Mat_CreateVer(filename, nullptr, MAT_FT_MAT5);
    }
    else if (mat_version == 73) {
      mat_file = Mat_CreateVer(filename, nullptr, MAT_FT_MAT73);
    }

    if (mat_file == nullptr) {
      std::cerr << "ERROR: Unable to create matlab file " << filename << "\n";
      exit(1);
    }
  }

  /* word sizes */
  int cpu_word_size=sizeof(double);
  int io_word_size=0;

  /* open exodus file */
  float exo_version;
  int exo_file=ex_open(argv[1],EX_READ,&cpu_word_size,&io_word_size,&exo_version);
  if (exo_file < 0){
    std::cerr << "ERROR: Cannot open " << argv[1] << "\n";
    exit(1);
  }

  /* print */
  std::cout << "\ttranslating " << argv[1] << " to " << filename << "...\n";

  /* read database paramters */
  char *line=(char *) calloc ((MAX_LINE_LENGTH+1),sizeof(char));
  ex_get_init(exo_file,line,
              &num_axes,&num_nodes,&num_elements,&num_blocks,
              &num_node_sets,&num_side_sets);
  num_info_lines = ex_inquire_int(exo_file,EX_INQ_INFO);
  num_time_steps = ex_inquire_int(exo_file,EX_INQ_TIME);
  ex_get_variable_param(exo_file,EX_GLOBAL,&num_global_vars);
  ex_get_variable_param(exo_file,EX_NODAL,&num_nodal_vars);
  ex_get_variable_param(exo_file,EX_ELEM_BLOCK,&num_element_vars);
  ex_get_variable_param(exo_file,EX_NODE_SET,&num_nodeset_vars);
  ex_get_variable_param(exo_file,EX_SIDE_SET,&num_sideset_vars);


  /* export paramters */
  PutInt("naxes",  num_axes);
  PutInt("nnodes", num_nodes);
  PutInt("nelems", num_elements);
  PutInt("nblks",  num_blocks);
  PutInt("nnsets", num_node_sets);
  PutInt("nssets", num_side_sets);
  PutInt("nsteps", num_time_steps);
  PutInt("ngvars", num_global_vars);
  PutInt("nnvars", num_nodal_vars);
  PutInt("nevars", num_element_vars);
  PutInt("nnsvars",num_nodeset_vars);
  PutInt("nssvars",num_sideset_vars);

  /* allocate -char- scratch space*/
  int nstr2 = num_info_lines;
  nstr2 = std::max(nstr2, num_blocks);
  nstr2 = std::max(nstr2, num_node_sets);
  nstr2 = std::max(nstr2, num_side_sets);
  char **str2 = get_exodus_names(nstr2, 512);

  /* title */
  PutStr("Title",line);

  /* information records */
  if (num_info_lines > 0 ){
    ex_get_info(exo_file,str2);
    std::string ostr;
    for (int i=0;i<num_info_lines;i++) {
      if (strlen(str2[i]) > 0) {
        ostr += str2[i];
        ostr += "\n";
      }
    }
    PutStr("info",ostr.c_str());
    ostr = "";
    for (int i=0;i<num_info_lines;i++) {
      if (strlen(str2[i]) > 0 && strncmp(str2[i],"cavi",4)==0) {
        ostr += str2[i];
        ostr += "\n";
      }
    }
    PutStr("cvxp",ostr.c_str());
  }

  /* nodal coordinates */
  {
    if (debug) {logger("Coordinates");}
    std::vector<double> x, y, z;
    x.resize(num_nodes);
    if (num_axes >= 2) y.resize(num_nodes);
    if (num_axes == 3) z.resize(num_nodes);
    ex_get_coord(exo_file,TOPTR(x), TOPTR(y), TOPTR(z));
    PutDbl("x0", num_nodes, 1, TOPTR(x));
    if (num_axes >= 2) {
      PutDbl("y0", num_nodes, 1, TOPTR(y));
    }
    if (num_axes == 3){
      PutDbl("z0",num_nodes,1, TOPTR(z));
    }
  }

  /* side sets */
  std::vector<int> num_sideset_sides(num_side_sets);
  std::vector<int> ids;
  if (num_side_sets > 0) {
    if (debug) {logger("Side Sets");}
    ids.resize(num_side_sets);
    ex_get_ids(exo_file,EX_SIDE_SET,TOPTR(ids));
    PutInt( "ssids",num_side_sets, 1,TOPTR(ids));
    std::vector<int> nssdfac(num_side_sets);
    std::vector<int> iscr;
    std::vector<int> jscr;
    std::vector<double> scr;
    std::vector<int> elem_list;
    std::vector<int> side_list;
    std::vector<int> junk;
    for (int i=0;i<num_side_sets;i++) {
      ex_get_set_param(exo_file,EX_SIDE_SET, ids[i],&n1,&n2);
      num_sideset_sides[i]=n1;
      nssdfac[i]=n2;
      /*
       * the following provision is from Version 1.6 when there are no
       * distribution factors in exodus file
       */
      bool has_ss_dfac = (n2 != 0);
      if (n2==0 || n1==n2){

        std::cerr << "WARNING: Exodus II file does not contain distribution factors.\n";

        /* n1=number of faces, n2=number of df */
        /* using distribution factors to determine number of nodes in the sideset
           causes a lot grief since some codes do not output distribution factors
           if they are all equal to 1. mkbhard: I am using the function call below
           to figure out the total number of nodes in this sideset. Some redundancy
           exists, but it works for now */

        junk.resize(n1);
        ex_get_side_set_node_count(exo_file,ids[i],TOPTR(junk));
        n2=0; /* n2 will be equal to the total number of nodes in the sideset */
        for (int j=0; j<n1; j++)
          n2+=junk[j];
      }

      iscr.resize(n1);
      jscr.resize(n2);
      ex_get_side_set_node_list(exo_file,ids[i],TOPTR(iscr),TOPTR(jscr));
      /* number-of-nodes-per-side list */
      sprintf(str,"ssnum%02d",i+1);
      PutInt(str,n1,1,TOPTR(iscr));
      /* nodes list */
      sprintf(str,"ssnod%02d",i+1);
      PutInt(str,n2,1,TOPTR(jscr));

      /* distribution-factors list */
      scr.resize(n2);
      if (has_ss_dfac) {
        ex_get_side_set_dist_fact(exo_file,ids[i], TOPTR(scr));
      } else {
        for (int j=0; j<n2; j++) {
          scr[j] = 1.0;
        }
      }
      sprintf(str,"ssfac%02d",i+1);
      PutDbl(str,n2,1,TOPTR(scr));

      /* element and side list for side sets (dgriffi) */
      elem_list.resize(n1);
      side_list.resize(n1);
      ex_get_set(exo_file,EX_SIDE_SET,ids[i],TOPTR(elem_list),TOPTR(side_list));
      sprintf(str,"ssside%02d",i+1);
      PutInt(str,n1,1,TOPTR(side_list));
      sprintf(str,"sselem%02d",i+1);
      PutInt(str,n1,1,TOPTR(elem_list));
    }
    /* Store # sides and # dis. factors per side set (dgriffi) */
    PutInt("nsssides",num_side_sets,1,TOPTR(num_sideset_sides));
    PutInt("nssdfac",num_side_sets,1,TOPTR(nssdfac));
  }

  /* node sets (section by dgriffi) */
  std::vector<int> num_nodeset_nodes(num_node_sets);
  if (num_node_sets > 0){
    if (debug) {logger("Node Sets");}
    std::vector<int> iscr;
    std::vector<double> scr;
    ids.resize(num_node_sets);
    ex_get_ids(exo_file,EX_NODE_SET, TOPTR(ids));
    PutInt( "nsids",num_node_sets, 1,TOPTR(ids));

    std::vector<int> num_nodeset_df(num_node_sets);
    for (int i=0;i<num_node_sets;i++){
      ex_get_set_param(exo_file,EX_NODE_SET,ids[i],&n1,&n2);
      iscr.resize(n1);
      ex_get_node_set(exo_file,ids[i],TOPTR(iscr));
      /* nodes list */
      sprintf(str,"nsnod%02d",i+1);
      PutInt(str,n1,1,TOPTR(iscr));
      {
        /* distribution-factors list */
        scr.resize(n2);
        ex_get_node_set_dist_fact(exo_file,ids[i],TOPTR(scr));
        sprintf(str,"nsfac%02d",i+1);
        PutDbl(str,n2,1,TOPTR(scr));
      }
      num_nodeset_nodes[i]=n1;
      num_nodeset_df[i]=n2;
    }

    /* Store # nodes and # dis. factors per node set */
    PutInt("nnsnodes",num_node_sets,1,TOPTR(num_nodeset_nodes));
    PutInt("nnsdfac",num_node_sets,1,TOPTR(num_nodeset_df));
  }

  /* element blocks */
  if (debug) {logger("Element Blocks");}
  std::vector<int> num_elem_in_block(num_blocks);
  {
    ids.resize(num_blocks);
    std::vector<int> iscr;
    ex_get_ids(exo_file,EX_ELEM_BLOCK,TOPTR(ids));
    PutInt( "blkids",num_blocks, 1,TOPTR(ids));
    for (int i=0;i<num_blocks;i++) {
      ex_get_elem_block(exo_file,ids[i],str2[i],&n,&n1,&n2);
      num_elem_in_block[i]=n;
      iscr.resize(n*n1);
      ex_get_conn(exo_file,EX_ELEM_BLOCK,ids[i],TOPTR(iscr), nullptr, nullptr);
      sprintf(str,"blk%02d",i+1);
      PutInt(str,n1,n,TOPTR(iscr));
    }
    str[0]='\0';
    for (int i=0;i<num_blocks;i++) {
      strcat(str, str2[i]);
      strcat(str, "\n");
    }
    PutStr("blknames",str);
  }

  /* time values */
  if (num_time_steps > 0 ) {
    if (debug) {logger("Time Steps");}
    std::vector<double> scr(num_time_steps);
    ex_get_all_times (exo_file, TOPTR(scr));
    PutDbl( "time", num_time_steps, 1, TOPTR(scr));
  }

  /* global variables */
  if (num_global_vars > 0 ) {
    if (debug) {logger("Global Variables");}
    get_put_names(exo_file, EX_GLOBAL, num_global_vars, "gnames");

    std::vector<double> scr(num_time_steps);
    for (int i=0;i<num_global_vars;i++){
      sprintf(str,"gvar%02d",i+1);
      ex_get_glob_var_time(exo_file,i+1,1,num_time_steps,TOPTR(scr));
      PutDbl(str,num_time_steps,1,TOPTR(scr));
    }
  }

  /* nodal variables */
  if (num_nodal_vars > 0 ) {
    if (debug) {logger("Nodal Variables");}
    if (debug) {logger("\tNames");}
    get_put_names(exo_file, EX_NODAL, num_nodal_vars, "nnames");

    std::vector<double> scr(num_nodes*num_time_steps);
    for (int i=0; i<num_nodal_vars; i++){
      sprintf(str,"nvar%02d",i+1);
      if (debug) {logger("\tReading");}
      for (int j=0; j<num_time_steps; j++) {
        ex_get_nodal_var(exo_file,j+1,i+1,num_nodes,
                         &scr[num_nodes*j]);
      }
      if (debug) {logger("\tWriting");}
      PutDbl(str,num_nodes,num_time_steps,TOPTR(scr));
    }
  }

  /* element variables */
  if (num_element_vars > 0 ) {
    if (debug) {logger("Element Variables");}
    get_put_names(exo_file, EX_ELEM_BLOCK, num_element_vars, "enames");

    get_put_vars(exo_file, EX_ELEM_BLOCK,
                 num_blocks, num_element_vars, num_time_steps, num_elem_in_block, "evar%02d");
  }

  /* nodeset variables */
  if (num_nodeset_vars > 0 ) {
    if (debug) {logger("Nodeset Variables");}
    get_put_names(exo_file, EX_NODE_SET, num_nodeset_vars, "nsnames");

    get_put_vars(exo_file, EX_NODE_SET,
                 num_node_sets, num_nodeset_vars, num_time_steps, num_nodeset_nodes, "nsvar%02d");
  }

  /* sideset variables */
  if (num_sideset_vars > 0 ) {
    if (debug) {logger("Sideset Variables");}
    get_put_names(exo_file, EX_SIDE_SET, num_sideset_vars, "ssnames");

    get_put_vars(exo_file, EX_SIDE_SET,
                 num_side_sets, num_sideset_vars, num_time_steps, num_sideset_sides, "ssvar%02d");
  }

  /* node and element number maps */
  if (debug) {logger("Node and Element Number Maps");}
  ex_opts(0);  /* turn off error reporting. It is not an error to have no map*/
  ids.resize(num_nodes);
  err = ex_get_node_num_map(exo_file,TOPTR(ids));
  if ( err==0 ){
    PutInt("node_num_map",num_nodes,1,TOPTR(ids));
  }

  ids.resize(num_elements);
  err = ex_get_elem_num_map(exo_file,TOPTR(ids));
  if ( err==0 ){
    PutInt("elem_num_map",num_elements,1,TOPTR(ids));
  }

  if (debug) {logger("Closing file");}
  ex_close(exo_file);

  if ( textfile )
    fclose(m_file);
  else
    Mat_Close(mat_file);

  std::cout << "done...\n";

  free(filename);
  free(line);

  delete_exodus_names(str2, nstr2);

  /* exit status */
  add_to_log("exo2mat", 0);
  return(0);
}
Example #8
0
File: ball.c Project: taysom/tau
int main (int argc, char *argv[])
{
	msg_s	msg;
	ki_t	key;
	int	c;
	int	rc;
	char	*send_color;
	char	*recv_color;
	unint	i;
	unint	n = 1000;
	u64	start = 0;
	u64	finish;

	setprogname(argv[0]);

	while ((c = getopt(argc, argv, "p?")) != -1) {
		switch (c) {
		case 'p':
			prompt_on();
			break;
		default:
			usage();
			break;
		}
	}
	if (argc < optind+2) usage();

	send_color = argv[optind];
	recv_color = argv[optind+1];

	if (argc > optind+2) {
		n = strtoll(argv[optind+2], NULL, 0);
	}

prompt("start");
	if (init_msg_tau(send_color)) {
		exit(2);
	}
prompt("sw_register");
	sw_register(send_color);

prompt("create_gate_tau");
	key = make_gate(0, REQUEST);

prompt("sw_post");
	rc = sw_post(send_color, key);
	if (rc) failure("sw_post", rc);

prompt("sw_any");
	rc = sw_any(recv_color, &key);
	if (rc) failure("sw_any", rc);

	for (i = 0; i < n; i++) {
		if (i == 2) start = nsecs();
prompt("send_tau");
		rc = send_tau(key, &msg);
		if (rc) failure("send_tau", rc);

prompt("receive_tau");
		rc = receive_tau( &msg);
		if (rc) failure("receive", rc);
	}
	finish = nsecs();
	printf("%s %g nsecs per send/receive\n", send_color,
		((double)(finish - start))/(n-2));
	return 0;
}
Example #9
0
int tool_main(int argc, char** argv) {
    DiffMetricProc diffProc = compute_diff_pmcolor;

    // Maximum error tolerated in any one color channel in any one pixel before
    // a difference is reported.
    int colorThreshold = 0;
    SkString baseFile;
    SkString baseLabel;
    SkString comparisonFile;
    SkString comparisonLabel;
    SkString outputDir;

    bool listFilenames = false;

    bool failOnResultType[DiffRecord::kResultCount];
    for (int i = 0; i < DiffRecord::kResultCount; i++) {
        failOnResultType[i] = false;
    }

    bool failOnStatusType[DiffResource::kStatusCount][DiffResource::kStatusCount];
    for (int base = 0; base < DiffResource::kStatusCount; ++base) {
        for (int comparison = 0; comparison < DiffResource::kStatusCount; ++comparison) {
            failOnStatusType[base][comparison] = false;
        }
    }

    int i;
    int numUnflaggedArguments = 0;
    int numLabelArguments = 0;
    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "--failonresult")) {
            if (argc == ++i) {
                SkDebugf("failonresult expects one argument.\n");
                continue;
            }
            DiffRecord::Result type = DiffRecord::getResultByName(argv[i]);
            if (type != DiffRecord::kResultCount) {
                failOnResultType[type] = true;
            } else {
                SkDebugf("ignoring unrecognized result <%s>\n", argv[i]);
            }
            continue;
        }
        if (!strcmp(argv[i], "--failonstatus")) {
            if (argc == ++i) {
                SkDebugf("failonstatus missing base status.\n");
                continue;
            }
            bool baseStatuses[DiffResource::kStatusCount];
            if (!DiffResource::getMatchingStatuses(argv[i], baseStatuses)) {
                SkDebugf("unrecognized base status <%s>\n", argv[i]);
            }

            if (argc == ++i) {
                SkDebugf("failonstatus missing comparison status.\n");
                continue;
            }
            bool comparisonStatuses[DiffResource::kStatusCount];
            if (!DiffResource::getMatchingStatuses(argv[i], comparisonStatuses)) {
                SkDebugf("unrecognized comarison status <%s>\n", argv[i]);
            }

            for (int base = 0; base < DiffResource::kStatusCount; ++base) {
                for (int comparison = 0; comparison < DiffResource::kStatusCount; ++comparison) {
                    failOnStatusType[base][comparison] |=
                        baseStatuses[base] && comparisonStatuses[comparison];
                }
            }
            continue;
        }
        if (!strcmp(argv[i], "--help")) {
            usage(argv[0]);
            return kNoError;
        }
        if (!strcmp(argv[i], "--listfilenames")) {
            listFilenames = true;
            continue;
        }
        if (!strcmp(argv[i], "--outputdir")) {
            if (argc == ++i) {
                SkDebugf("outputdir expects one argument.\n");
                continue;
            }
            outputDir.set(argv[i]);
            continue;
        }
        if (!strcmp(argv[i], "--threshold")) {
            colorThreshold = atoi(argv[++i]);
            continue;
        }
        if (!strcmp(argv[i], "-u")) {
            //we don't produce unified diffs, ignore parameter to work with svn diff
            continue;
        }
        if (!strcmp(argv[i], "-L")) {
            if (argc == ++i) {
                SkDebugf("label expects one argument.\n");
                continue;
            }
            switch (numLabelArguments++) {
                case 0:
                    baseLabel.set(argv[i]);
                    continue;
                case 1:
                    comparisonLabel.set(argv[i]);
                    continue;
                default:
                    SkDebugf("extra label argument <%s>\n", argv[i]);
                    usage(argv[0]);
                    return kGenericError;
            }
            continue;
        }
        if (argv[i][0] != '-') {
            switch (numUnflaggedArguments++) {
                case 0:
                    baseFile.set(argv[i]);
                    continue;
                case 1:
                    comparisonFile.set(argv[i]);
                    continue;
                default:
                    SkDebugf("extra unflagged argument <%s>\n", argv[i]);
                    usage(argv[0]);
                    return kGenericError;
            }
        }

        SkDebugf("Unrecognized argument <%s>\n", argv[i]);
        usage(argv[0]);
        return kGenericError;
    }

    if (numUnflaggedArguments != 2) {
        usage(argv[0]);
        return kGenericError;
    }

    if (listFilenames) {
        printf("Base file is [%s]\n", baseFile.c_str());
    }

    if (listFilenames) {
        printf("Comparison file is [%s]\n", comparisonFile.c_str());
    }

    if (outputDir.isEmpty()) {
        if (listFilenames) {
            printf("Not writing any diffs. No output dir specified.\n");
        }
    } else {
        if (!outputDir.endsWith(PATH_DIV_STR)) {
            outputDir.append(PATH_DIV_STR);
        }
        if (listFilenames) {
            printf("Writing diffs. Output dir is [%s]\n", outputDir.c_str());
        }
    }

    // Some obscure documentation about diff/patch labels:
    //
    // Posix says the format is: <filename><tab><date>
    //     It also states that if a filename contains <tab> or <newline>
    //     the result is implementation defined
    //
    // Svn diff --diff-cmd provides labels of the form: <filename><tab><revision>
    //
    // Git diff --ext-diff does not supply arguments compatible with diff.
    //     However, it does provide the filename directly.
    //     skimagediff_git.sh: skimagediff %2 %5 -L "%1\t(%3)" -L "%1\t(%6)"
    //
    // Git difftool sets $LOCAL, $REMOTE, $MERGED, and $BASE instead of command line parameters.
    //     difftool.<>.cmd: skimagediff $LOCAL $REMOTE -L "$MERGED\t(local)" -L "$MERGED\t(remote)"
    //
    // Diff will write any specified label verbatim. Without a specified label diff will write
    //     <filename><tab><date>
    //     However, diff will encode the filename as a cstring if the filename contains
    //         Any of <space> or <double quote>
    //         A char less than 32
    //         Any escapable character \\, \a, \b, \t, \n, \v, \f, \r
    //
    // Patch decodes:
    //     If first <non-white-space> is <double quote>, parse filename from cstring.
    //     If there is a <tab> after the first <non-white-space>, filename is
    //         [first <non-white-space>, the next run of <white-space> with an embedded <tab>).
    //     Otherwise the filename is [first <non-space>, the next <white-space>).
    //
    // The filename /dev/null means the file does not exist (used in adds and deletes).

    // Considering the above, skimagediff will consider the contents of a -L parameter as
    //     <filename>(\t<specifier>)?
    SkString outputFile;

    if (baseLabel.isEmpty()) {
        baseLabel.set(baseFile);
        outputFile = baseLabel;
    } else {
        const char* baseLabelCstr = baseLabel.c_str();
        const char* tab = strchr(baseLabelCstr, '\t');
        if (NULL == tab) {
            outputFile = baseLabel;
        } else {
            outputFile.set(baseLabelCstr, tab - baseLabelCstr);
        }
    }
    if (comparisonLabel.isEmpty()) {
        comparisonLabel.set(comparisonFile);
    }
    printf("Base:       %s\n", baseLabel.c_str());
    printf("Comparison: %s\n", comparisonLabel.c_str());

    DiffRecord dr;
    create_diff_images(diffProc, colorThreshold, baseFile, comparisonFile, outputDir, outputFile,
                       &dr);

    if (DiffResource::isStatusFailed(dr.fBase.fStatus)) {
        printf("Base %s.\n", DiffResource::getStatusDescription(dr.fBase.fStatus));
    }
    if (DiffResource::isStatusFailed(dr.fComparison.fStatus)) {
        printf("Comparison %s.\n", DiffResource::getStatusDescription(dr.fComparison.fStatus));
    }
    printf("Base and Comparison %s.\n", DiffRecord::getResultDescription(dr.fResult));

    if (DiffRecord::kDifferentPixels_Result == dr.fResult) {
        printf("%.4f%% of pixels differ", 100 * dr.fFractionDifference);
        printf(" (%.4f%%  weighted)", 100 * dr.fWeightedFraction);
        if (dr.fFractionDifference < 0.01) {
            printf(" %d pixels", static_cast<int>(dr.fFractionDifference *
                                                  dr.fBase.fBitmap.width() *
                                                  dr.fBase.fBitmap.height()));
        }

        printf("\nAverage color mismatch: ");
        printf("%d", static_cast<int>(MAX3(dr.fAverageMismatchR,
                                           dr.fAverageMismatchG,
                                           dr.fAverageMismatchB)));
        printf("\nMax color mismatch: ");
        printf("%d", MAX3(dr.fMaxMismatchR,
                          dr.fMaxMismatchG,
                          dr.fMaxMismatchB));
        printf("\n");
    }
    printf("\n");

    int num_failing_results = 0;
    if (failOnResultType[dr.fResult]) {
        ++num_failing_results;
    }
    if (failOnStatusType[dr.fBase.fStatus][dr.fComparison.fStatus]) {
        ++num_failing_results;
    }

    return num_failing_results;
}
Example #10
0
int main(int argc, char *argv[])
{

    int nBytes = 0;
    int address = 0;
    uint16_t data;

    if(argc<2)
    {
        usage(argv[0]);
        return -1;
    }

    handle = usbOpenDevice(0x16c0,"NeuTroN",0x7755,"93CXXProg");

    if(handle == NULL)
    {
        printf("\nError! Programmer Not found.\n");
        return 0;
    }

    //this checking here detects whether the chip requires soft_clk or not
    //and also determines if any chip exists or not
    if(check_type() == -1)
    {
        usb_close(handle);
        return 0;
    }

    if(stricmp(argv[1],"read")==0)
    {
        if(argc==3 && stricmp(argv[2],"all")==0)
        {
            uint8_t k;
            for(k=0;k<64;k++)
            {
                nBytes = read_word(&data,k);

                //blink led while transmission
                led(k%2);

                if(nBytes<0)
                    fprintf(stderr,"Error!\n");
                else
                    printf("%04x\t",data);
            }
        }

        else
        {
            address = atoi(argv[2]);

            nBytes = read_word(&data,address);

            if(nBytes < 0)
            {
                fprintf(stderr,"Error!");
                usb_close(handle);
                return -1;
            }
            printf("\n%04x is data\n",data);

        }

        //turn off led
        led(USB_LED_OFF);

    }

    else if (argc == 4 && stricmp(argv[1],"write")==0)
    {
        uint16_t address = atoi(argv[2]);
        uint16_t word = atoi(argv[3]);

        nBytes = write_word(word,address);

        if(nBytes<0)
            fprintf(stderr,"Error!\n");
        else
            fprintf(stdout,"\nData written successfully.\n");
    }

    else if(argc > 2 && stricmp(argv[1],"read2f")==0)
    {
        char c;
        printf("\nCaution! if file \"%s\" exists its contents will be overwritten.\
               \nTo Continue press 'y' any other key to abort: ",argv[2]);


            c = getchar();
            c = tolower(c); //convert if upper case to lower

            if(c!='y')
                    return 0;

            FILE *fp = fopen(argv[2],"wb");

            if(!fp)
            {
                fprintf(stderr,"\nCannot create file. Check filepath and name properly.\n");
                return -1;
            }

        uint16_t fdata;
        uint8_t pointer=0;

        for(pointer=0;pointer<64;pointer++)
        {

            nBytes = read_word(&fdata,pointer);

            //blink led while transmission
            led(pointer%2);

            fwrite(&fdata,2,1,fp);

           //printf("%04x",fdata);

            if(nBytes<0)
            {
                fprintf(stderr,"Error! Try Again\n");
                fclose(fp);
                return -1;
            }

        }

        fclose(fp);
        fprintf(stdout,"\nData written to file \"%s\" successfully\n",argv[2]);

        //turn off led
        led(USB_LED_OFF);

    }
Example #11
0
int main(int argc, char **argv)
{
	int opt;
	int do_list = 0;
	char *do_load = NULL;

	while ((opt = getopt(argc, argv, "h?b:lf:a:n:p:kR:B:")) != EOF) {
		switch (opt) {
		case 'b':
			dbname = optarg;
			break;
		case 'f':
			if (do_load) {
				fprintf(stderr, "Duplicate option -f\n");
				usage();
			}
			do_load = optarg;
			break;
		case 'l':
			do_list = 1;
			break;
		case 'a':
			active_probing = atoi(optarg);
			break;
		case 'n':
			negative_timeout = atoi(optarg);
			break;
		case 'k':
			no_kernel_broadcasts = 1;
			break;
		case 'p':
			if ((poll_timeout = 1000 * strtod(optarg, NULL)) < 100) {
				fprintf(stderr, "Invalid poll timeout\n");
				exit(-1);
			}
			break;
		case 'R':
			if ((broadcast_rate = atoi(optarg)) <= 0 ||
			    (broadcast_rate = 1000/broadcast_rate) <= 0) {
				fprintf(stderr, "Invalid ARP rate\n");
				exit(-1);
			}
			break;
		case 'B':
			if ((broadcast_burst = atoi(optarg)) <= 0 ||
			    (broadcast_burst = 1000*broadcast_burst) <= 0) {
				fprintf(stderr, "Invalid ARP burst\n");
				exit(-1);
			}
			break;
		case 'h':
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc > 0) {
		ifnum = argc;
		ifnames = argv;
		ifvec = malloc(argc*sizeof(int));
		if (!ifvec) {
			perror("malloc");
			exit(-1);
		}
	}

	if ((udp_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket");
		exit(-1);
	}

	if (ifnum) {
		int i;
		struct ifreq ifr = {};

		for (i = 0; i < ifnum; i++) {
			strncpy(ifr.ifr_name, ifnames[i], IFNAMSIZ);
			if (ioctl(udp_sock, SIOCGIFINDEX, &ifr)) {
				perror("ioctl(SIOCGIFINDEX)");
				exit(-1);
			}
			ifvec[i] = ifr.ifr_ifindex;
		}
	}

	dbase = dbopen(dbname, O_CREAT|O_RDWR, 0644, DB_HASH, NULL);
	if (dbase == NULL) {
		perror("db_open");
		exit(-1);
	}

	if (do_load) {
		char buf[128];
		FILE *fp;
		struct dbkey k;
		DBT dbkey, dbdat;

		dbkey.data = &k;
		dbkey.size = sizeof(k);

		if (strcmp(do_load, "-") == 0 || strcmp(do_load, "--") == 0) {
			fp = stdin;
		} else if ((fp = fopen(do_load, "r")) == NULL) {
			perror("fopen");
			goto do_abort;
		}

		buf[sizeof(buf)-1] = 0;
		while (fgets(buf, sizeof(buf), fp)) {
			__u8 b1[6];
			char ipbuf[128];
			char macbuf[128];

			if (buf[0] == '#')
				continue;

			if (sscanf(buf, "%u%s%s", &k.iface, ipbuf, macbuf) != 3) {
				fprintf(stderr, "Wrong format of input file \"%s\"\n", do_load);
				goto do_abort;
			}
			if (strncmp(macbuf, "FAILED:", 7) == 0)
				continue;
			if (!inet_aton(ipbuf, (struct in_addr *)&k.addr)) {
				fprintf(stderr, "Invalid IP address: \"%s\"\n", ipbuf);
				goto do_abort;
			}

			if (ll_addr_a2n((char *) b1, 6, macbuf) != 6)
				goto do_abort;
			dbdat.size = 6;

			if (dbase->put(dbase, &dbkey, &dbdat, 0)) {
				perror("hash->put");
				goto do_abort;
			}
		}
		dbase->sync(dbase, 0);
		if (fp != stdin)
			fclose(fp);
	}

	if (do_list) {
		DBT dbkey, dbdat;

		printf("%-8s %-15s %s\n", "#Ifindex", "IP", "MAC");
		while (dbase->seq(dbase, &dbkey, &dbdat, R_NEXT) == 0) {
			struct dbkey *key = dbkey.data;

			if (handle_if(key->iface)) {
				if (!IS_NEG(dbdat.data)) {
					char b1[18];

					printf("%-8d %-15s %s\n",
					       key->iface,
					       inet_ntoa(*(struct in_addr *)&key->addr),
					       ll_addr_n2a(dbdat.data, 6, ARPHRD_ETHER, b1, 18));
				} else {
					printf("%-8d %-15s FAILED: %dsec ago\n",
					       key->iface,
					       inet_ntoa(*(struct in_addr *)&key->addr),
					       NEG_AGE(dbdat.data));
				}
			}
		}
	}

	if (do_load || do_list)
		goto out;

	pset[0].fd = socket(PF_PACKET, SOCK_DGRAM, 0);
	if (pset[0].fd < 0) {
		perror("socket");
		exit(-1);
	}

	if (1) {
		struct sockaddr_ll sll = {
			.sll_family = AF_PACKET,
			.sll_protocol = htons(ETH_P_ARP),
			.sll_ifindex = (ifnum == 1 ? ifvec[0] : 0),
		};

		if (bind(pset[0].fd, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
			perror("bind");
			goto do_abort;
		}
	}

	if (rtnl_open(&rth, RTMGRP_NEIGH) < 0) {
		perror("rtnl_open");
		goto do_abort;
	}
	pset[1].fd = rth.fd;

	load_initial_table();

	if (daemon(0, 0)) {
		perror("arpd: daemon");
		goto do_abort;
	}

	openlog("arpd", LOG_PID | LOG_CONS, LOG_DAEMON);
	catch_signal(SIGINT, sig_exit);
	catch_signal(SIGTERM, sig_exit);
	catch_signal(SIGHUP, sig_sync);
	catch_signal(SIGUSR1, sig_stats);

#define EVENTS (POLLIN|POLLPRI|POLLERR|POLLHUP)
	pset[0].events = EVENTS;
	pset[0].revents = 0;
	pset[1].events = EVENTS;
	pset[1].revents = 0;

	sigsetjmp(env, 1);

	for (;;) {
		in_poll = 1;

		if (do_exit)
			break;
		if (do_sync) {
			in_poll = 0;
			dbase->sync(dbase, 0);
			do_sync = 0;
			in_poll = 1;
		}
		if (do_stats)
			send_stats();
		if (poll(pset, 2, poll_timeout) > 0) {
			in_poll = 0;
			if (pset[0].revents&EVENTS)
				get_arp_pkt();
			if (pset[1].revents&EVENTS)
				get_kern_msg();
		} else {
			do_sync = 1;
		}
	}

	undo_sysctl_adjustments();
out:
	dbase->close(dbase);
	exit(0);

do_abort:
	dbase->close(dbase);
	exit(-1);
}
Example #12
0
bool readSettingsFromCommandLine(int argc, char *argv[],
                  Settings& config)
{
    bool builtWithOpenGL = false;
    Settings::Options options;

#ifndef QT_NO_OPENGL
    builtWithOpenGL = true;
#endif
    for (int i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "-manual") == 0) {
            options |= Settings::ManualTest;
            argv[i] = 0;
            break;
        }
    }

    for (int i = 1; i < argc; ++i) {
        if (!argv[i])
            continue;
        if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0) {
            usage(argv[0]);
            return true;
        }
        if (strcmp(argv[i], "-opengl") == 0) {
            if (builtWithOpenGL) {
                options |= Settings::UseOpenGL;
                argv[i] = 0;
            } else {
                printf("-opengl parameter can be used only with building PRECONDITIONS: QT_NO_OPENGL is off.\n");
                usage(argv[0]);
                return false;
            }
        } else if (strcmp(argv[i], "-resolution") == 0) {
            if (i + 1 >= argc) {
                printf("-resolution needs an extra parameter specifying the application UI resolution\n");
                usage(argv[0]);
                return false;
            }
            else {
                QStringList res = QString(argv[i+1]).split(QLatin1Char('x'));
                if (res.count() != 2) {
                    printf("-resolution parameter UI resolution should be set in format WxH where width and height are positive values\n");
                    usage(argv[0]);
                    return false;
                }
                int width = res.at(0).toInt();
                int height = res.at(1).toInt();

                config.setSize(QSize(width, height));

                if (width <=0 || height <=0) {
                    printf("-resolution parameter UI resolution should be set in format WxH where width and height are positive values\n");
                    usage(argv[0]);
                    return false;
                }
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        }

        if (!argv[i])
            continue;

        if (!(options & Settings::ManualTest)) {
            if (argumentOnlyAvailableInManualMode(argv[i])) {
                printf("\nWrong option: '%s' is only available in manual mode\n\n", argv[i]);
                usage(argv[0]);
                return false;
            }
            continue;
        }

        if (strcmp(argv[i], "-rotation") == 0) {
            if (i + 1 >= argc) {
                printf("-rotation needs an extra parameter specifying the application UI rotation in degrees\n");
                usage(argv[0]);
                return false;
            }
            else {
                bool ok;
                int angle = QString(argv[i+1]).toInt(&ok);
                if (!ok) {
                    printf("-rotation parameter should specify rotation angle in degrees\n");
                    usage(argv[0]);
                    return false;
                }
                config.setAngle(angle);
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        } else if (strcmp(argv[i], "-subtree-cache") == 0) {
            options |= Settings::UseListItemCache;
            argv[i] = 0;
        } else if (strcmp(argv[i], "-fps") == 0) {
             options |= Settings::OutputFps;
             argv[i] = 0;
        } else if (strcmp(argv[i], "-items") == 0) {
            if (i + 1 >= argc) {
                printf("-items needs an extra parameter specifying amount of list items\n");
                usage(argv[0]);
                return false;
            }
            else {
                bool ok;
                int amount = QString(argv[i+1]).toInt(&ok);
                if (!ok) {
                    printf("-items needs an extra parameter specifying amount (integer) of list items\n");
                    usage(argv[0]);
                    return false;
                }
                config.setListItemCount(amount);
                argv[i] = 0;
                i++;
                argv[i] = 0;
            }
        }
    }

    config.setOptions(options);

    return true;
}
int main(int argument_count, char **arguments)
{
	DM7820_Board_Descriptor *board;
	DM7820_Error dm7820_status;
	int status;
	struct option options[] = {
		{"help", 0, 0, 1},
		{"minor", 1, 0, 2},
		{0, 0, 0, 0}
	};
	struct sigaction signal_action;
	uint8_t help_option = 0x00;
	uint8_t minor_option = 0x00;
	unsigned long int minor_number = 0;

	program_name = arguments[0];

	fprintf(stdout, "\n");
	fprintf(stdout,
		"\tDM7820 8254 Timer/Counter Interrupt Example Program\n");
	fprintf(stdout, "\n");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Process command line options
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	while (1) {

		/*
		 * Parse the next command line option and any arguments it may require
		 */

		status = getopt_long(argument_count,
				     arguments, "", options, NULL);

		/*
		 * If getopt_long() returned -1, then all options have been processed
		 */

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

		/*
		 * Figure out what getopt_long() found
		 */

		switch (status) {

			/*#################################################################
			   User entered '--help'
			   ################################################################# */

		case 1:

			/*
			 * Refuse to accept duplicate '--help' options
			 */

			if (help_option) {
				error(0, 0, "ERROR: Duplicate option '--help'");
				usage();
			}

			/*
			 * '--help' option has been seen
			 */

			help_option = 0xFF;
			break;

			/*#################################################################
			   User entered '--minor'
			   ################################################################# */

		case 2:{
				char *invalid_char_p;

				/*
				 * Refuse to accept duplicate '--minor' options
				 */

				if (minor_option) {
					error(0, 0,
					      "ERROR: Duplicate option '--minor'");
					usage();
				}

				/*
				 * Convert option argument string to unsigned long integer
				 */

				errno = 0;

				minor_number =
				    strtoul(optarg, &invalid_char_p, 10);

				/*
				 * Catch unsigned long int overflow
				 */

				if ((minor_number == ULONG_MAX)
				    && (errno == ERANGE)) {
					error(0, 0,
					      "ERROR: Device minor number caused numeric overflow");
					usage();
				}

				/*
				 * Catch argument strings with valid decimal prefixes, for
				 * example "1q", and argument strings which cannot be converted,
				 * for example "abc1"
				 */

				if ((*invalid_char_p != '\0')
				    || (invalid_char_p == optarg)) {
					error(0, 0,
					      "ERROR: Non-decimal device minor number");
					usage();
				}

				/*
				 * '--minor' option has been seen
				 */

				minor_option = 0xFF;
				break;
			}

			/*#################################################################
			   User entered unsupported option
			   ################################################################# */

		case '?':
			usage();
			break;

			/*#################################################################
			   getopt_long() returned unexpected value
			   ################################################################# */

		default:
			error(EXIT_FAILURE,
			      0,
			      "ERROR: getopt_long() returned unexpected value %#x",
			      status);
			break;
		}
	}

	/*
	 * Recognize '--help' option before any others
	 */

	if (help_option) {
		usage();
	}

	/*
	 * '--minor' option must be given
	 */

	if (minor_option == 0x00) {
		error(0, 0, "ERROR: Option '--minor' is required");
		usage();
	}

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Generic initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Set up a way for user to interrupt the program via Control-C
	 */

	fprintf(stdout, "Installing SIGINT signal handler ...\n");

	signal_action.sa_handler = sigint_handler;
	sigfillset(&(signal_action.sa_mask));
	signal_action.sa_flags = 0;

	if (sigaction(SIGINT, &signal_action, NULL) < 0) {
		error(EXIT_FAILURE, errno, "ERROR: sigaction() FAILED");
	}

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Device initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Open the device file
	 */

	fprintf(stdout, "Opening device with minor number %lu ...\n",
		minor_number);

	dm7820_status = DM7820_General_Open_Board(minor_number, &board);
	DM7820_Return_Status(dm7820_status, "DM7820_General_Open_Board()");

	/*
	 * Reset device
	 */

	fprintf(stdout, "Resetting device ...\n");

	dm7820_status = DM7820_General_Reset(board);
	DM7820_Return_Status(dm7820_status, "DM7820_General_Reset()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Interrupt generic initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Make sure timer/counter A1 interrupt is disabled to prevent stray
	 * interrupts
	 */

	fprintf(stdout, "Disabling timer/counter A1 interrupt ...\n");

	dm7820_status =
	    DM7820_General_Enable_Interrupt(board, DM7820_INTERRUPT_TMRCTR_A_1,
					    0x00);
	DM7820_Return_Status(dm7820_status,
			     "DM7820_General_Enable_Interrupt()");

	/*
	 * Install user-space ISR
	 */
	fprintf(stdout, "Installing user ISR ...\n");
	dm7820_status = DM7820_General_InstallISR(board, ISR);
	DM7820_Return_Status(dm7820_status, "DM7820_General_InstallISR()");

	fprintf(stdout, "Setting ISR priority ...\n");
	dm7820_status = DM7820_General_SetISRPriority(board, 99);
	DM7820_Return_Status(dm7820_status, "DM7820_General_SetISRPriority()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   8254 timer/counter generic initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Disable timer/counters A0 and A1 to get them into a known state
	 */

	fprintf(stdout, "Disabling timer/counters ...\n");

	fprintf(stdout, "    A0\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_0,
				      DM7820_TMRCTR_GATE_LOGIC_0);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	fprintf(stdout, "    A1\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_1,
				      DM7820_TMRCTR_GATE_LOGIC_0);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   8254 timer/counter A0 initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	fprintf(stdout, "Initializing 8254 timer/counter A0 ...\n");

	/*
	 * Set timer clock source to 5 MHz clock
	 */

	fprintf(stdout, "    Selecting clock source ...\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Clock(board, DM7820_TMRCTR_TIMER_A_0,
				       DM7820_TMRCTR_CLOCK_5_MHZ);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Clock()");

	/*
	 * Set up the timer by 1) setting waveform mode to square wave generator,
	 * 2) setting count mode to binary, and 3) loading divisor value to obtain
	 * 100 Hz frequency
	 */

	fprintf(stdout, "    Programming timer ...\n");

	dm7820_status = DM7820_TmrCtr_Program(board,
					      DM7820_TMRCTR_TIMER_A_0,
					      DM7820_TMRCTR_WAVEFORM_SQUARE_WAVE,
					      DM7820_TMRCTR_COUNT_MODE_BINARY,
					      50000);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Program()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   8254 timer/counter A1 initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	fprintf(stdout, "Initializing 8254 timer/counter A1 ...\n");

	/*
	 * Set timer clock source to 8254 timer/counter A0
	 */

	fprintf(stdout, "    Selecting clock source ...\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Clock(board, DM7820_TMRCTR_TIMER_A_1,
				       DM7820_TMRCTR_CLOCK_8254_A_0);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Clock()");

	/*
	 * Set up the timer by 1) setting waveform mode to square wave generator,
	 * 2) setting count mode to binary, and 3) loading divisor value to obtain
	 * .5 Hz frequency
	 */

	fprintf(stdout, "    Programming timer ...\n");

	dm7820_status = DM7820_TmrCtr_Program(board,
					      DM7820_TMRCTR_TIMER_A_1,
					      DM7820_TMRCTR_WAVEFORM_SQUARE_WAVE,
					      DM7820_TMRCTR_COUNT_MODE_BINARY,
					      200);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Program()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Timer/counter A1 interrupt initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	fprintf(stdout, "Enabling timer/counter A1 interrupt ...\n");

	dm7820_status =
	    DM7820_General_Enable_Interrupt(board, DM7820_INTERRUPT_TMRCTR_A_1,
					    0xFF);
	DM7820_Return_Status(dm7820_status,
			     "DM7820_General_Enable_Interrupt()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Secondary 8254 timer/counter A1 initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Set timer gate to high to enable counting
	 */

	fprintf(stdout, "Setting timer/counter A1 gate to logic high ...\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_1,
				      DM7820_TMRCTR_GATE_LOGIC_1);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Secondary 8254 timer/counter A0 initialization
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Set timer gate to high to enable counting
	 */

	fprintf(stdout, "Setting timer/counter A0 gate to logic high ...\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_0,
				      DM7820_TMRCTR_GATE_LOGIC_1);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Main processing
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	/*
	 * Loop until desired number of  have been seen
	 */
	int temp_interrupts = interrupts;
	while (temp_interrupts < 10 && !exit_program) {
		if (interrupts != temp_interrupts) {
			temp_interrupts = interrupts;
			fprintf(stdout, "    Interrupt number %u occurred.\n",
				interrupts);
			fflush(stdout);
		}
		usleep(0);
	}

	fprintf(stdout, "Interrupt count reached, exiting ...\n");

	/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	   Final processing before exit
	   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% */

	fprintf(stdout, "Disabling timer/counter A1 interrupt ...\n");

	dm7820_status =
	    DM7820_General_Enable_Interrupt(board, DM7820_INTERRUPT_TMRCTR_A_1,
					    0x00);
	DM7820_Return_Status(dm7820_status,
			     "DM7820_General_Enable_Interrupt()");

	fprintf(stdout, "Removing user ISR ...\n");

	dm7820_status = DM7820_General_RemoveISR(board);
	DM7820_Return_Status(dm7820_status, "DM7820_General_RemoveISR()");

	fprintf(stdout, "Disabling timer/counters ...\n");

	fprintf(stdout, "    A0\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_0,
				      DM7820_TMRCTR_GATE_LOGIC_0);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	fprintf(stdout, "    A1\n");

	dm7820_status =
	    DM7820_TmrCtr_Select_Gate(board, DM7820_TMRCTR_TIMER_A_1,
				      DM7820_TMRCTR_GATE_LOGIC_0);
	DM7820_Return_Status(dm7820_status, "DM7820_TmrCtr_Select_Gate()");

	fprintf(stdout, "Closing device ...\n");

	dm7820_status = DM7820_General_Close_Board(board);
	DM7820_Return_Status(dm7820_status, "DM7820_General_Close_Board()");

	fprintf(stdout, "\n");
	fprintf(stdout, "Successful end of example program.\n");

	exit(EXIT_SUCCESS);
}
Example #14
0
int
main(int argc, char *argv[])
{
	int arglen, ch, len, readstdin = 0;
	struct passwd *pw;
	char *p, *endp;
	pid_t forkpid;

#ifndef DEBUG
	if (geteuid())
		errx(1, "NOT super-user");
#endif
	while ((ch = getopt(argc, argv, "dfhknpr-")) != -1)
		switch (ch) {
		case '-':
			readstdin = 1;
			break;
		case 'd':
			dodump = 1;
			break;
		case 'f':
			dofast = 1;
			break;
		case 'h':
			dohalt = 1;
			break;
		case 'k':
			killflg = 1;
			break;
		case 'n':
			nosync = 1;
			break;
		case 'p':
			dopower = 1;
			break;
		case 'r':
			doreboot = 1;
			break;
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc < 1)
		usage();

	if (dofast && nosync) {
		(void)fprintf(stderr,
		    "shutdown: incompatible switches -f and -n.\n");
		usage();
	}
	if (doreboot && dohalt) {
		(void)fprintf(stderr,
		    "shutdown: incompatible switches -h and -r.\n");
		usage();
	}
	if (dopower && !dohalt) {
		(void)fprintf(stderr,
		    "shutdown: switch -p must be used with -h.\n");
		usage();
	}
	getoffset(*argv++);

	if (*argv) {
		for (p = mbuf, len = sizeof(mbuf); *argv; ++argv) {
			arglen = strlen(*argv);
			if ((len -= arglen) <= 2)
				break;
			if (p != mbuf)
				*p++ = ' ';
			memcpy(p, *argv, arglen);
			p += arglen;
		}
		*p = '\n';
		*++p = '\0';
	}

	if (readstdin) {
		p = mbuf;
		endp = mbuf + sizeof(mbuf) - 2;
		for (;;) {
			if (!fgets(p, endp - p + 1, stdin))
				break;
			for (; *p &&  p < endp; ++p)
				;
			if (p == endp) {
				*p = '\n';
				*++p = '\0';
				break;
			}
		}
	}
	mbuflen = strlen(mbuf);

	if (offset)
		(void)printf("Shutdown at %.24s.\n", ctime(&shuttime));
	else
		(void)printf("Shutdown NOW!\n");

	if (!(whom = getlogin()))
		whom = (pw = getpwuid(getuid())) ? pw->pw_name : "???";

#ifdef DEBUG
	(void)putc('\n', stdout);
#else
	(void)setpriority(PRIO_PROCESS, 0, PRIO_MIN);

	forkpid = fork();
	if (forkpid == -1)
		err(1, "fork");
	if (forkpid) {
		(void)printf("shutdown: [pid %ld]\n", (long)forkpid);
		exit(0);
	}
	setsid();
#endif
	openlog("shutdown", LOG_CONS, LOG_AUTH);
	loop();
	/* NOTREACHED */
}
Example #15
0
int main(int argc, char **argv)
{
	struct option long_options[] = {
		{"wordy", no_argument, NULL, 'w'},
		{"help", no_argument, NULL, 'h'},
	};
	struct epoll_event events[10];
	int epoll_fd = -1;
	struct itimerspec it;
	int ret;
	int status = EXIT_SUCCESS;

	if (argc > 0)
		progname = argv[0];

	for (;;) {
		int c;

		c = getopt_long(argc, argv, "wh", long_options, NULL);
		if (c == -1)
			break;

		switch (c) {
		case 'w':
			wordy = true;
			break;
		case 'h':
			usage(false);
		default:
			usage(true);
		}
	}
	if (optind != argc)
		usage(true);

	dpy = XOpenDisplay(NULL);
	if (!dpy) {
		fprintf(stderr, "unable to open display '%s'\n",
			XDisplayName(NULL));
		status = EXIT_FAILURE;
		goto out;
	}
	root = DefaultRootWindow(dpy);

	epoll_fd = epoll_create1(EPOLL_CLOEXEC);
	if (epoll_fd == -1) {
		perror("epoll_create1");
		status = EXIT_FAILURE;
		goto out;
	}

	ret = signal_fd_init(epoll_fd);
	if (ret == -1) {
		status = EXIT_FAILURE;
		goto out;
	}

	ret = timer_fd_init(epoll_fd);
	if (ret == -1) {
		status = EXIT_FAILURE;
		goto out;
	}

	ret = ctl_fd_init(epoll_fd);
	if (ret == -1) {
		status = EXIT_FAILURE;
		goto out;
	}

	if (init_plugins()) {
		status = EXIT_FAILURE;
		goto out;
	}
	if (init_sections(epoll_fd, config, sizeof(config) / sizeof(*config))) {
		status = EXIT_FAILURE;
		goto out;
	}
	if (update_timer_sections()) {
		status = EXIT_FAILURE;
		goto out;
	}

	it.it_interval.tv_sec = 1;
	it.it_interval.tv_nsec = 0;
	it.it_value.tv_sec = 1;
	it.it_value.tv_nsec = 0;
	ret = timerfd_settime(timer_cb.fd, 0, &it, NULL);
	if (ret == -1) {
		perror("timerfd_settime");
		status = EXIT_FAILURE;
		goto out;
	}

	while (!quit) {
		int i;

		update = false;

		ret = epoll_wait(epoll_fd, events,
				 sizeof(events) / sizeof(events[0]),
				 -1);
		if (ret == -1) {
			if (errno == EINTR)
				continue;
			perror("epoll_wait");
			status = EXIT_FAILURE;
			goto out;
		}

		for (i = 0; i < ret; i++) {
			struct epoll_callback *cb = events[i].data.ptr;

			ret = cb->callback(cb->fd, cb->data, events[i].events);
			if (ret) {
				status = EXIT_FAILURE;
				goto out;
			}
		}

		if (update) {
			ret = update_statusbar();
			if (ret) {
				status = EXIT_FAILURE;
				goto out;
			}
		}
	}

	status = EXIT_SUCCESS;
out:
	if (epoll_fd != -1)
		close(epoll_fd);
	free_sections();
	if (ctl_cb.fd != -1) {
		close(ctl_cb.fd);
		unlink(ctl_addr.sun_path);
	}
	if (timer_cb.fd != -1)
		close(timer_cb.fd);
	if (signal_cb.fd != -1)
		close(signal_cb.fd);
	str_free(&status_str);
	if (dpy) {
		XStoreName(dpy, root, "");
		XFlush(dpy);
		XCloseDisplay(dpy);
	}
	return status;
}
Example #16
0
int init_main(int argc, char* argv[])
{
    InitModuleObjects();

    Owned<IProperties> inputs = createProperties(true);

    bool interactive = false;

    for (int i = 1; i < argc; i++)
    {
        if (stricmp(argv[i], "-?")==0 || stricmp(argv[i], "-h")==0 || stricmp(argv[i], "-help")==0
             || stricmp(argv[i], "/?")==0 || stricmp(argv[i], "/h")==0)
             usage();
        else if(stricmp(argv[i], "interactive") == 0)
            interactive = true;
        else if (strchr(argv[i],'='))
        {
            inputs->loadProp(argv[i]);
        }
        else
        {
            fprintf(stderr, "Unknown option: %s", argv[i]);
            return 0;
        }
    }

    int result = -1;

#ifdef _WIN32 
    if (!interactive)
        ::SetErrorMode(SEM_NOGPFAULTERRORBOX|SEM_FAILCRITICALERRORS);
#endif

    SET_ESP_SIGNAL_HANDLER(SIGPIPE, brokenpipe_handler);

    bool SEHMappingEnabled = false;

    CEspAbortHandler abortHandler;

    Owned<IFile> sentinelFile = createSentinelTarget();
    removeSentinelFile(sentinelFile);

    Owned<CEspConfig> config;
    Owned<CEspServer> server;
    try
    {
        const char* cfgfile = NULL;
        const char* procname = NULL;
        if(inputs.get())
        {
            if(inputs->hasProp("config"))
                cfgfile = inputs->queryProp("config");
            if(inputs->hasProp("process"))
                procname = inputs->queryProp("process");
        }
        if(!cfgfile || !*cfgfile)
            cfgfile = "esp.xml";

        Owned<IPropertyTree> envpt= createPTreeFromXMLFile(cfgfile, ipt_caseInsensitive);
        Owned<IPropertyTree> procpt = NULL;
        if (envpt)
        {
            envpt->addProp("@config", cfgfile);
            StringBuffer xpath;
            if (procname==NULL || strcmp(procname, ".")==0)
                xpath.appendf("Software/EspProcess[1]");
            else
                xpath.appendf("Software/EspProcess[@name=\"%s\"]", procname);

            DBGLOG("Using ESP configuration section [%s]", xpath.str());
            procpt.set(envpt->queryPropTree(xpath.str()));
            if (!procpt)
                throw MakeStringException(-1, "Config section [%s] not found", xpath.str());
        }
        else
            throw MakeStringException(-1, "Failed to load config file %s", cfgfile);

        const char* build_ver = BUILD_TAG;
        setBuildVersion(build_ver);

        const char* build_level = BUILD_LEVEL;
        setBuildLevel(build_level);

        const char * processName = procpt->queryProp("@name");
        setStatisticsComponentName(SCTesp, processName, true);

        openEspLogFile(envpt.get(), procpt.get());

        DBGLOG("Esp starting %s", BUILD_TAG);

        StringBuffer componentfilesDir;
        if(procpt->hasProp("@componentfilesDir"))
            procpt->getProp("@componentfilesDir", componentfilesDir);
        if(componentfilesDir.length() > 0 && strcmp(componentfilesDir.str(), ".") != 0)
        {
            setCFD(componentfilesDir.str());
            DBGLOG("componentfiles are under %s", getCFD());
        }

        StringBuffer sehsetting;
        procpt->getProp("@enableSEHMapping", sehsetting);
        if(!interactive && sehsetting.length() > 0 && (stricmp(sehsetting.str(), "true") == 0 || stricmp(sehsetting.str(), "1") == 0))
            SEHMappingEnabled = true;
        if(SEHMappingEnabled)
            EnableSEHtoExceptionMapping();

        CEspConfig* cfg = new CEspConfig(inputs.getLink(), envpt.getLink(), procpt.getLink(), false);
        if(cfg && cfg->isValid())
        {
            config.setown(cfg);
            abortHandler.setConfig(cfg);
        }
    }
    catch(IException* e)
    {
        StringBuffer description;
        ERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
        e->Release();
        return -1;
    }
    catch (...)
    {
        ERRLOG("ESP Unhandled General Exception.");
        return -1;
    }

    if (config && config->isValid())
    {
        PROGLOG("Configuring Esp Platform...");

        try
        {
            CEspServer *srv = new CEspServer(config);
            if(SEHMappingEnabled)
                srv->setSavedSEHHandler(SEHMappingEnabled);
            server.setown(srv);
            abortHandler.setServer(srv);
            setEspContainer(server.get());

            config->loadAll();
            config->bindServer(*server.get(), *server.get()); 
            
        }
        catch(IException* e)
        {
            StringBuffer description;
            ERRLOG("ESP Unhandled IException (%d -- %s)", e->errorCode(), e->errorMessage(description).str());
            e->Release();
            return -1;
        }
        catch (...)
        {
            ERRLOG("ESP Unhandled General Exception.");
            return -1;
        }

        writeSentinelFile(sentinelFile);
        result = work_main(*config, *server.get());
    }
    else
    {
        ERRLOG("!!! Unable to load ESP configuration.");
    }
    
    return result;
}
Example #17
0
int ARCH_MAINDECL main(int argc, char *argv[])
{
	CBM_FILE fd;
	__int32  Status, FuncRes, RetVal = 0;

	printf("\ntapcontrol v1.00 - Commodore 1530/1531 tape control\n");
	printf("Copyright 2012 Arnd Menge\n\n");

	if ((RetVal = EvaluateCommandlineParams(argc, argv)) == -1)
	{
		usage();
		goto exit;
	}

	if (cbm_driver_open_ex(&fd, NULL) != 0)
	{
		printf("\nDriver error.\n");
		RetVal = -1;
		goto exit;
	}

	// Check tape firmware version compatibility.
	//   Status value:
	//   - tape firmware version
	//   - XUM1541_Error_NoTapeSupport
	//   - XUM1541_Error_NoDiskTapeMode
	//   - XUM1541_Error_TapeCmdInDiskMode
	FuncRes = cbm_tap_get_ver(fd, &Status);
	if (FuncRes != 1)
	{
		printf("\nReturned error [get_ver]: %d\n", FuncRes);
		RetVal = -1;
		goto exit2;
	}
	if (Status < 0)
	{
		printf("\nReturned error [get_ver]: ");
		if (OutputError(Status) < 0)
			if (OutputFuncError(Status) < 0)
				printf("%d\n", Status);
		RetVal = -1;
		goto exit2;
	}
	if (Status != TapeFirmwareVersion)
	{
		printf("\nError [get_ver]: ");
		OutputError(Tape_Status_ERROR_Wrong_Tape_Firmware);
		RetVal = -1;
		goto exit2;
	}

	if (MotorOn == 1)
	{
		//   Status values:
		//   - Tape_Status_OK_Motor_On
		//   - Tape_Status_ERROR_Device_Disconnected
		//   - XUM1541_Error_NoTapeSupport
		//   - XUM1541_Error_NoDiskTapeMode
		//   - XUM1541_Error_TapeCmdInDiskMode
		FuncRes = cbm_tap_motor_on(fd, &Status);
		if (FuncRes != 1)
		{
			printf("\nReturned error [motor_on]: %d\n", FuncRes);
			RetVal = -1;
		}
		if (Status != Tape_Status_OK_Motor_On)
		{
			printf("\nReturned error [motor_on]: ");
			if (OutputError(Status) < 0)
				if (OutputFuncError(Status) < 0)
					printf("%d\n", Status);
			RetVal = -1;
		}
	}

	if (MotorOff == 1)
	{
		//   Status values:
		//   - Tape_Status_OK_Motor_Off
		//   - Tape_Status_ERROR_Device_Disconnected
		//   - XUM1541_Error_NoTapeSupport
		//   - XUM1541_Error_NoDiskTapeMode
		//   - XUM1541_Error_TapeCmdInDiskMode
		FuncRes = cbm_tap_motor_off(fd, &Status);
		if (FuncRes != 1)
		{
			printf("\nReturned error [motor_off]: %d\n", FuncRes);
			RetVal = -1;
		}
		if (Status != Tape_Status_OK_Motor_Off)
		{
			printf("\nReturned error [motor_off]: ");
			if (OutputError(Status) < 0)
				if (OutputFuncError(Status) < 0)
					printf("%d\n", Status);
			RetVal = -1;
		}
	}

    exit2:
	cbm_driver_close(fd);

    exit:
   	printf("\n");
   	return RetVal;
}
Example #18
0
int
main(int argc, char **argv)
{
	int i, n, off;
	int c;
	char *addr;
	char *path;
	Spuser *user;
	Spcfsys *fs;
	Spcfid *fid;
	char buf[512];

	user = sp_unix_users->uid2user(sp_unix_users, geteuid());
	while ((c = getopt(argc, argv, "dp:")) != -1) {
		switch (c) {
		case 'd':
			spc_chatty = 1;
			break;

		case 'u':
			user = sp_unix_users->uname2user(sp_unix_users, optarg);
			break;

		default:
			usage();
		}
	}
	
	if (!user) {
		fprintf(stderr, "cannot retrieve user %d\n", geteuid());
		exit(1);
	}

	if (argc - optind < 2)
		usage();

	addr = argv[optind];
	path = argv[optind+1];

	fs = spc_netmount(addr, user, 564, NULL, NULL);
	fid = spc_open(fs, path, Owrite);
	if (!fid) {
		fid = spc_create(fs, path, 0666, Owrite);
		if (!fid) {
			fprintf(stderr, "error creating\n");
			exit(1);
		}
	}

	off = 0;
	while ((n = read(0, buf, sizeof(buf))) > 0) {
		i = spc_write(fid, (u8*) buf, n, off);
		if (i != n) {
			fprintf(stderr, "error writing\n");
			exit(1);
		}

		off += n;
	}
			
	spc_close(fid);
	spc_umount(fs);

	exit(0);
}
Example #19
0
int
main(int argc, char **argv)
{
	int	ch, aflag, lflag;
	char	*buf, *cp;
	long	l;

	effective_uid = geteuid();
	real_uid = getuid();
	effective_gid = getegid();
	real_gid = getgid();
	PRIV_END;	/* be safe */

	if (gethostname(host, sizeof(host)) != 0)
		err(1, "gethostname");
	openlog("lpq", 0, LOG_LPR);

	aflag = lflag = 0;
	while ((ch = getopt(argc, argv, "alP:w:")) != -1) {
		switch(ch) {
		case 'a':
			++aflag;
			break;
		case 'l':			/* long output */
			++lflag;
			break;
		case 'P':		/* printer name */
			printer = optarg;
			break;
		case 'w':
			l = strtol(optarg, &cp, 10);
			if (*cp != '\0' || l < 0 || l >= INT_MAX)
				errx(1, "wait time must be postive integer: %s",
				    optarg);
			wait_time = (u_int)l;
			if (wait_time < 30)
				warnx("warning: wait time less than 30 seconds");
			break;
		case '?':
		default:
			usage();
		}
	}

	if (!aflag && printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;

	for (argc -= optind, argv += optind; argc; --argc, ++argv)
		if (isdigit((unsigned char)argv[0][0])) {
			if (requests >= MAXREQUESTS)
				fatal("too many requests");
			requ[requests++] = atoi(*argv);
		}
		else {
			if (users >= MAXUSERS)
				fatal("too many users");
			user[users++] = *argv;
		}

	if (aflag) {
		while (cgetnext(&buf, printcapdb) > 0) {
			if (ckqueue(buf) <= 0) {
				free(buf);
				continue;	/* no jobs */
			}
			for (cp = buf; *cp; cp++)
				if (*cp == '|' || *cp == ':') {
					*cp = '\0';
					break;
				}
			printer = buf;
			printf("%s:\n", printer);
			displayq(lflag);
			free(buf);
			printf("\n");
		}
	} else
		displayq(lflag);
	exit(0);
}
Example #20
0
int main(int argc, char *argv[])
{
   FILE *fp;
   char *s, *infile = NULL, c;
   int size = SIZE, size2, k, nd = -1, out = ' ';
   double *x, *y;

   if ((cmnd = strrchr(argv[0], '/')) == NULL)
      cmnd = argv[0];
   else
      cmnd++;

   while (--argc) {
      if (*(s = *++argv) == '-') {
         c = *++s;
         switch (c) {
         case 'l':
            size = atoi(*++argv);
            argc--;
            break;
         case 'm':
            nd = atoi(*++argv) + 1;
            argc--;
            break;
         case 'i':
         case 'p':
         case 'r':
            c -= ('a' - 'A');
         case 'A':
         case 'I':
         case 'P':
         case 'R':
            out = c;
            break;
         case 'h':
            usage(0);
         default:
            fprintf(stderr, "%s : Invalid option '%c'!\n", cmnd, c);
            usage(1);
         }
      } else
         infile = s;
   }

   if (nd == -1)
      nd = size;
   if (nd > size) {
      fprintf(stderr,
              "%s : Order of sequence %d should be less than the FFT size %d!\n",
              cmnd, nd, size);
      return (1);
   }

   fp = stdin;

   if (infile) {
      fp = getfp(infile, "rb");
   }

   x = dgetmem(size2 = size + size);
   y = x + size;

   while (!feof(fp)) {
      fillz(x, size2, sizeof(double));
      if (freadf(x, sizeof(*x), nd, fp) == 0)
         break;
      if (freadf(y, sizeof(*y), nd, fp) == 0)
         break;
      fft(x, y, size);
      if (out == 'P')
         for (k = 0; k < size; k++)
            x[k] = x[k] * x[k] + y[k] * y[k];
      else if (out == 'A')
         for (k = 0; k < size; k++)
            x[k] = sqrt(x[k] * x[k] + y[k] * y[k]);
      if (out != 'I')
         fwritef(x, sizeof(*x), size, stdout);
      if (out == ' ' || out == 'I')
         fwritef(y, sizeof(*y), size, stdout);
   }

   if (infile) {
      fclose(fp);
   }

   return (0);
}
Example #21
0
/*
 * On success, leave *EXIT_CODE untouched and return SVN_NO_ERROR. On error,
 * either return an error to be displayed, or set *EXIT_CODE to non-zero and
 * return SVN_NO_ERROR.
 */
static svn_error_t *
sub_main(int *exit_code, int argc, const char *argv[], apr_pool_t *pool)
{
  enum run_mode run_mode = run_mode_unspecified;
  svn_boolean_t foreground = FALSE;
  apr_socket_t *sock;
  apr_sockaddr_t *sa;
  svn_error_t *err;
  apr_getopt_t *os;
  int opt;
  serve_params_t params;
  const char *arg;
  apr_status_t status;
#ifndef WIN32
  apr_proc_t proc;
#endif
  svn_boolean_t is_multi_threaded;
  enum connection_handling_mode handling_mode = CONNECTION_DEFAULT;
  svn_boolean_t cache_fulltexts = TRUE;
  svn_boolean_t cache_nodeprops = TRUE;
  svn_boolean_t cache_txdeltas = TRUE;
  svn_boolean_t cache_revprops = FALSE;
  svn_boolean_t use_block_read = FALSE;
  apr_uint16_t port = SVN_RA_SVN_PORT;
  const char *host = NULL;
  int family = APR_INET;
  apr_int32_t sockaddr_info_flags = 0;
#if APR_HAVE_IPV6
  svn_boolean_t prefer_v6 = FALSE;
#endif
  svn_boolean_t quiet = FALSE;
  svn_boolean_t is_version = FALSE;
  int mode_opt_count = 0;
  int handling_opt_count = 0;
  const char *config_filename = NULL;
  const char *pid_filename = NULL;
  const char *log_filename = NULL;
  svn_node_kind_t kind;
  apr_size_t min_thread_count = THREADPOOL_MIN_SIZE;
  apr_size_t max_thread_count = THREADPOOL_MAX_SIZE;
#ifdef SVN_HAVE_SASL
  SVN_ERR(cyrus_init(pool));
#endif

  /* Check library versions */
  SVN_ERR(check_lib_versions());

  /* Initialize the FS library. */
  SVN_ERR(svn_fs_initialize(pool));

  /* Initialize the efficient Authz support. */
  SVN_ERR(svn_repos_authz_initialize(pool));

  SVN_ERR(svn_cmdline__getopt_init(&os, argc, argv, pool));

  params.root = "/";
  params.tunnel = FALSE;
  params.tunnel_user = NULL;
  params.read_only = FALSE;
  params.base = NULL;
  params.cfg = NULL;
  params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_DEFAULT;
  params.logger = NULL;
  params.config_pool = NULL;
  params.fs_config = NULL;
  params.vhost = FALSE;
  params.username_case = CASE_ASIS;
  params.memory_cache_size = (apr_uint64_t)-1;
  params.zero_copy_limit = 0;
  params.error_check_interval = 4096;
  params.max_request_size = MAX_REQUEST_SIZE * 0x100000;
  params.max_response_size = 0;

  while (1)
    {
      status = apr_getopt_long(os, svnserve__options, &opt, &arg);
      if (APR_STATUS_IS_EOF(status))
        break;
      if (status != APR_SUCCESS)
        {
          usage(argv[0], pool);
          *exit_code = EXIT_FAILURE;
          return SVN_NO_ERROR;
        }
      switch (opt)
        {
        case '6':
#if APR_HAVE_IPV6
          prefer_v6 = TRUE;
#endif
          /* ### Maybe error here if we don't have IPV6 support? */
          break;

        case 'h':
          help(pool);
          return SVN_NO_ERROR;

        case 'q':
          quiet = TRUE;
          break;

        case SVNSERVE_OPT_VERSION:
          is_version = TRUE;
          break;

        case 'd':
          if (run_mode != run_mode_daemon)
            {
              run_mode = run_mode_daemon;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_FOREGROUND:
          foreground = TRUE;
          break;

        case SVNSERVE_OPT_SINGLE_CONN:
          handling_mode = connection_mode_single;
          handling_opt_count++;
          break;

        case 'i':
          if (run_mode != run_mode_inetd)
            {
              run_mode = run_mode_inetd;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_LISTEN_PORT:
          {
            apr_uint64_t val;

            err = svn_cstring_strtoui64(&val, arg, 0, APR_UINT16_MAX, 10);
            if (err)
              return svn_error_createf(SVN_ERR_CL_ARG_PARSING_ERROR, err,
                                       _("Invalid port '%s'"), arg);
            port = (apr_uint16_t)val;
          }
          break;

        case SVNSERVE_OPT_LISTEN_HOST:
          host = arg;
          break;

        case 't':
          if (run_mode != run_mode_tunnel)
            {
              run_mode = run_mode_tunnel;
              mode_opt_count++;
            }
          break;

        case SVNSERVE_OPT_TUNNEL_USER:
          params.tunnel_user = arg;
          break;

        case 'X':
          if (run_mode != run_mode_listen_once)
            {
              run_mode = run_mode_listen_once;
              mode_opt_count++;
            }
          break;

        case 'r':
          SVN_ERR(svn_utf_cstring_to_utf8(&params.root, arg, pool));

          SVN_ERR(svn_io_check_resolved_path(params.root, &kind, pool));
          if (kind != svn_node_dir)
            {
              return svn_error_createf(SVN_ERR_ILLEGAL_TARGET, NULL,
                       _("Root path '%s' does not exist "
                         "or is not a directory"), params.root);
            }

          params.root = svn_dirent_internal_style(params.root, pool);
          SVN_ERR(svn_dirent_get_absolute(&params.root, params.root, pool));
          break;

        case 'R':
          params.read_only = TRUE;
          break;

        case 'T':
          handling_mode = connection_mode_thread;
          handling_opt_count++;
          break;

        case 'c':
          params.compression_level = atoi(arg);
          if (params.compression_level < SVN_DELTA_COMPRESSION_LEVEL_NONE)
            params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_NONE;
          if (params.compression_level > SVN_DELTA_COMPRESSION_LEVEL_MAX)
            params.compression_level = SVN_DELTA_COMPRESSION_LEVEL_MAX;
          break;

        case 'M':
          {
            apr_uint64_t sz_val;
            SVN_ERR(svn_cstring_atoui64(&sz_val, arg));

            params.memory_cache_size = 0x100000 * sz_val;
          }
          break;

        case SVNSERVE_OPT_CACHE_TXDELTAS:
          cache_txdeltas = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CACHE_FULLTEXTS:
          cache_fulltexts = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CACHE_REVPROPS:
          cache_revprops = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CACHE_NODEPROPS:
          cache_nodeprops = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_BLOCK_READ:
          use_block_read = svn_tristate__from_word(arg) == svn_tristate_true;
          break;

        case SVNSERVE_OPT_CLIENT_SPEED:
          {
            apr_size_t bandwidth = (apr_size_t)apr_strtoi64(arg, NULL, 0);

            /* for slower clients, don't try anything fancy */
            if (bandwidth >= 1000)
              {
                /* block other clients for at most 1 ms (at full bandwidth).
                   Note that the send buffer is 16kB anyways. */
                params.zero_copy_limit = bandwidth * 120;

                /* check for aborted connections at the same rate */
                params.error_check_interval = bandwidth * 120;
              }
          }
          break;

        case SVNSERVE_OPT_MAX_REQUEST:
          params.max_request_size = 0x100000 * apr_strtoi64(arg, NULL, 0);
          break;

        case SVNSERVE_OPT_MAX_RESPONSE:
          params.max_response_size = 0x100000 * apr_strtoi64(arg, NULL, 0);
          break;

        case SVNSERVE_OPT_MIN_THREADS:
          min_thread_count = (apr_size_t)apr_strtoi64(arg, NULL, 0);
          break;

        case SVNSERVE_OPT_MAX_THREADS:
          max_thread_count = (apr_size_t)apr_strtoi64(arg, NULL, 0);
          break;

#ifdef WIN32
        case SVNSERVE_OPT_SERVICE:
          if (run_mode != run_mode_service)
            {
              run_mode = run_mode_service;
              mode_opt_count++;
            }
          break;
#endif

        case SVNSERVE_OPT_CONFIG_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&config_filename, arg, pool));
          config_filename = svn_dirent_internal_style(config_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&config_filename, config_filename,
                                          pool));
          break;

        case SVNSERVE_OPT_PID_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&pid_filename, arg, pool));
          pid_filename = svn_dirent_internal_style(pid_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&pid_filename, pid_filename, pool));
          break;

         case SVNSERVE_OPT_VIRTUAL_HOST:
           params.vhost = TRUE;
           break;

         case SVNSERVE_OPT_LOG_FILE:
          SVN_ERR(svn_utf_cstring_to_utf8(&log_filename, arg, pool));
          log_filename = svn_dirent_internal_style(log_filename, pool);
          SVN_ERR(svn_dirent_get_absolute(&log_filename, log_filename, pool));
          break;

        }
    }

  if (is_version)
    {
      SVN_ERR(version(quiet, pool));
      return SVN_NO_ERROR;
    }

  if (os->ind != argc)
    {
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  if (mode_opt_count != 1)
    {
      svn_error_clear(svn_cmdline_fputs(
#ifdef WIN32
                      _("You must specify exactly one of -d, -i, -t, "
                        "--service or -X.\n"),
#else
                      _("You must specify exactly one of -d, -i, -t or -X.\n"),
#endif
                       stderr, pool));
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  if (handling_opt_count > 1)
    {
      svn_error_clear(svn_cmdline_fputs(
                      _("You may only specify one of -T or --single-thread\n"),
                      stderr, pool));
      usage(argv[0], pool);
      *exit_code = EXIT_FAILURE;
      return SVN_NO_ERROR;
    }

  /* construct object pools */
  is_multi_threaded = handling_mode == connection_mode_thread;
  params.fs_config = apr_hash_make(pool);
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_DELTAS,
                cache_txdeltas ? "1" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_FULLTEXTS,
                cache_fulltexts ? "1" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_NODEPROPS,
                cache_nodeprops ? "1" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_CACHE_REVPROPS,
                cache_revprops ? "2" :"0");
  svn_hash_sets(params.fs_config, SVN_FS_CONFIG_FSFS_BLOCK_READ,
                use_block_read ? "1" :"0");

  SVN_ERR(svn_repos__config_pool_create(&params.config_pool,
                                        is_multi_threaded,
                                        pool));

  /* If a configuration file is specified, load it and any referenced
   * password and authorization files. */
  if (config_filename)
    {
      params.base = svn_dirent_dirname(config_filename, pool);

      SVN_ERR(svn_repos__config_pool_get(&params.cfg,
                                         params.config_pool,
                                         config_filename,
                                         TRUE, /* must_exist */
                                         NULL,
                                         pool));
    }

  if (log_filename)
    SVN_ERR(logger__create(&params.logger, log_filename, pool));
  else if (run_mode == run_mode_listen_once)
    SVN_ERR(logger__create_for_stderr(&params.logger, pool));

  if (params.tunnel_user && run_mode != run_mode_tunnel)
    {
      return svn_error_create(SVN_ERR_CL_ARG_PARSING_ERROR, NULL,
               _("Option --tunnel-user is only valid in tunnel mode"));
    }

  if (run_mode == run_mode_inetd || run_mode == run_mode_tunnel)
    {
      apr_pool_t *connection_pool;
      svn_ra_svn_conn_t *conn;
      svn_stream_t *stdin_stream;
      svn_stream_t *stdout_stream;

      params.tunnel = (run_mode == run_mode_tunnel);
      apr_pool_cleanup_register(pool, pool, apr_pool_cleanup_null,
                                redirect_stdout);

      /* We are an interactive server, i.e. can't use APR buffering on
       * stdin. */
      SVN_ERR(svn_stream_for_stdin2(&stdin_stream, FALSE, pool));
      SVN_ERR(svn_stream_for_stdout(&stdout_stream, pool));

      /* Use a subpool for the connection to ensure that if SASL is used
       * the pool cleanup handlers that call sasl_dispose() (connection_pool)
       * and sasl_done() (pool) are run in the right order. See issue #3664. */
      connection_pool = svn_pool_create(pool);
      conn = svn_ra_svn_create_conn5(NULL, stdin_stream, stdout_stream,
                                     params.compression_level,
                                     params.zero_copy_limit,
                                     params.error_check_interval,
                                     params.max_request_size,
                                     params.max_response_size,
                                     connection_pool);
      err = serve(conn, &params, connection_pool);
      svn_pool_destroy(connection_pool);

      return err;
    }

#ifdef WIN32
  /* If svnserve needs to run as a Win32 service, then we need to
     coordinate with the Service Control Manager (SCM) before
     continuing.  This function call registers the svnserve.exe
     process with the SCM, waits for the "start" command from the SCM
     (which will come very quickly), and confirms that those steps
     succeeded.

     After this call succeeds, the service is free to run.  At some
     point in the future, the SCM will send a message to the service,
     requesting that it stop.  This is translated into a call to
     winservice_notify_stop().  The service is then responsible for
     cleanly terminating.

     We need to do this before actually starting the service logic
     (opening files, sockets, etc.) because the SCM wants you to
     connect *first*, then do your service-specific logic.  If the
     service process takes too long to connect to the SCM, then the
     SCM will decide that the service is busted, and will give up on
     it.
     */
  if (run_mode == run_mode_service)
    {
      err = winservice_start();
      if (err)
        {
          svn_handle_error2(err, stderr, FALSE, "svnserve: ");

          /* This is the most common error.  It means the user started
             svnserve from a shell, and specified the --service
             argument.  svnserve cannot be started, as a service, in
             this way.  The --service argument is valid only valid if
             svnserve is started by the SCM. */
          if (err->apr_err ==
              APR_FROM_OS_ERROR(ERROR_FAILED_SERVICE_CONTROLLER_CONNECT))
            {
              svn_error_clear(svn_cmdline_fprintf(stderr, pool,
                  _("svnserve: The --service flag is only valid if the"
                    " process is started by the Service Control Manager.\n")));
            }

          svn_error_clear(err);
          *exit_code = EXIT_FAILURE;
          return SVN_NO_ERROR;
        }

      /* The service is now in the "starting" state.  Before the SCM will
         consider the service "started", this thread must call the
         winservice_running() function. */
    }
#endif /* WIN32 */

  /* Make sure we have IPV6 support first before giving apr_sockaddr_info_get
     APR_UNSPEC, because it may give us back an IPV6 address even if we can't
     create IPV6 sockets. */

#if APR_HAVE_IPV6
#ifdef MAX_SECS_TO_LINGER
  /* ### old APR interface */
  status = apr_socket_create(&sock, APR_INET6, SOCK_STREAM, pool);
#else
  status = apr_socket_create(&sock, APR_INET6, SOCK_STREAM, APR_PROTO_TCP,
                             pool);
#endif
  if (status == 0)
    {
      apr_socket_close(sock);
      family = APR_UNSPEC;

      if (prefer_v6)
        {
          if (host == NULL)
            host = "::";
          sockaddr_info_flags = APR_IPV6_ADDR_OK;
        }
      else
        {
          if (host == NULL)
            host = "0.0.0.0";
          sockaddr_info_flags = APR_IPV4_ADDR_OK;
        }
    }
#endif

  status = apr_sockaddr_info_get(&sa, host, family, port,
                                 sockaddr_info_flags, pool);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't get address info"));
    }


#ifdef MAX_SECS_TO_LINGER
  /* ### old APR interface */
  status = apr_socket_create(&sock, sa->family, SOCK_STREAM, pool);
#else
  status = apr_socket_create(&sock, sa->family, SOCK_STREAM, APR_PROTO_TCP,
                             pool);
#endif
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't create server socket"));
    }

  /* Prevents "socket in use" errors when server is killed and quickly
   * restarted. */
  status = apr_socket_opt_set(sock, APR_SO_REUSEADDR, 1);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't set options on server socket"));
    }

  status = apr_socket_bind(sock, sa);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't bind server socket"));
    }

  status = apr_socket_listen(sock, ACCEPT_BACKLOG);
  if (status)
    {
      return svn_error_wrap_apr(status, _("Can't listen on server socket"));
    }

#if APR_HAS_FORK
  if (run_mode != run_mode_listen_once && !foreground)
    /* ### ignoring errors... */
    apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);

  apr_signal(SIGCHLD, sigchld_handler);
#endif

#ifdef SIGPIPE
  /* Disable SIGPIPE generation for the platforms that have it. */
  apr_signal(SIGPIPE, SIG_IGN);
#endif

#ifdef SIGXFSZ
  /* Disable SIGXFSZ generation for the platforms that have it, otherwise
   * working with large files when compiled against an APR that doesn't have
   * large file support will crash the program, which is uncool. */
  apr_signal(SIGXFSZ, SIG_IGN);
#endif

  if (pid_filename)
    SVN_ERR(write_pid_file(pid_filename, pool));

#ifdef WIN32
  status = apr_os_sock_get(&winservice_svnserve_accept_socket, sock);
  if (status)
    winservice_svnserve_accept_socket = INVALID_SOCKET;

  /* At this point, the service is "running".  Notify the SCM. */
  if (run_mode == run_mode_service)
    winservice_running();
#endif

  /* Configure FS caches for maximum efficiency with svnserve.
   * For pre-forked (i.e. multi-processed) mode of operation,
   * keep the per-process caches smaller than the default.
   * Also, apply the respective command line parameters, if given. */
  {
    svn_cache_config_t settings = *svn_cache_config_get();

    if (params.memory_cache_size != -1)
      settings.cache_size = params.memory_cache_size;

    settings.single_threaded = TRUE;
    if (handling_mode == connection_mode_thread)
      {
#if APR_HAS_THREADS
        settings.single_threaded = FALSE;
#else
        /* No requests will be processed at all
         * (see "switch (handling_mode)" code further down).
         * But if they were, some other synchronization code
         * would need to take care of securing integrity of
         * APR-based structures. That would include our caches.
         */
#endif
      }

    svn_cache_config_set(&settings);
  }

#if APR_HAS_THREADS
  SVN_ERR(svn_root_pools__create(&connection_pools));

  if (handling_mode == connection_mode_thread)
    {
      /* create the thread pool with a valid range of threads */
      if (max_thread_count < 1)
        max_thread_count = 1;
      if (min_thread_count > max_thread_count)
        min_thread_count = max_thread_count;

      status = apr_thread_pool_create(&threads,
                                      min_thread_count,
                                      max_thread_count,
                                      pool);
      if (status)
        {
          return svn_error_wrap_apr(status, _("Can't create thread pool"));
        }

      /* let idle threads linger for a while in case more requests are
         coming in */
      apr_thread_pool_idle_wait_set(threads, THREADPOOL_THREAD_IDLE_LIMIT);

      /* don't queue requests unless we reached the worker thread limit */
      apr_thread_pool_threshold_set(threads, 0);
    }
  else
    {
      threads = NULL;
    }
#endif

  while (1)
    {
      connection_t *connection = NULL;
      SVN_ERR(accept_connection(&connection, sock, &params, handling_mode,
                                pool));
      if (run_mode == run_mode_listen_once)
        {
          err = serve_socket(connection, connection->pool);
          close_connection(connection);
          return err;
        }

      switch (handling_mode)
        {
        case connection_mode_fork:
#if APR_HAS_FORK
          status = apr_proc_fork(&proc, connection->pool);
          if (status == APR_INCHILD)
            {
              /* the child would't listen to the main server's socket */
              apr_socket_close(sock);

              /* serve_socket() logs any error it returns, so ignore it. */
              svn_error_clear(serve_socket(connection, connection->pool));
              close_connection(connection);
              return SVN_NO_ERROR;
            }
          else if (status != APR_INPARENT)
            {
              err = svn_error_wrap_apr(status, "apr_proc_fork");
              logger__log_error(params.logger, err, NULL, NULL);
              svn_error_clear(err);
            }
#endif
          break;

        case connection_mode_thread:
          /* Create a detached thread for each connection.  That's not a
             particularly sophisticated strategy for a threaded server, it's
             little different from forking one process per connection. */
#if APR_HAS_THREADS
          attach_connection(connection);

          status = apr_thread_pool_push(threads, serve_thread, connection,
                                        0, NULL);
          if (status)
            {
              return svn_error_wrap_apr(status, _("Can't push task"));
            }
#endif
          break;

        case connection_mode_single:
          /* Serve one connection at a time. */
          /* serve_socket() logs any error it returns, so ignore it. */
          svn_error_clear(serve_socket(connection, connection->pool));
        }

      close_connection(connection);
    }

  /* NOTREACHED */
}
Example #22
0
int main(int argc, char *argv[])
{
	char *conf_filename;
	int result;
	int wait_count;
	int sock;
	pthread_t schedule_tid;
	struct sigaction act;
	ScheduleEntry scheduleEntries[SCHEDULE_ENTRIES_COUNT];
	ScheduleArray scheduleArray;
	char pidFilename[MAX_PATH_SIZE];
	bool stop;

	if (argc < 2)
	{
		usage(argv[0]);
		return 1;
	}

	g_current_time = time(NULL);
	g_up_time = g_current_time;
	srand(g_up_time);

	log_init2();
	//通过指定的conf文件,获取base path
	conf_filename = argv[1];
	if ((result=get_base_path_from_conf_file(conf_filename,
		g_fdfs_base_path, sizeof(g_fdfs_base_path))) != 0)
	{
		log_destroy();
		return result;
	}
	//启动程序,或者通过文件中的pid来kill掉之前的进程
	snprintf(pidFilename, sizeof(pidFilename),
		"%s/data/fdfs_trackerd.pid", g_fdfs_base_path);
	if ((result=process_action(pidFilename, argv[2], &stop)) != 0)
	{
		if (result == EINVAL)
		{
			usage(argv[0]);
		}
		log_destroy();
		return result;
	}
	if (stop)
	{
		log_destroy();
		return 0;
	}

#if defined(DEBUG_FLAG) && defined(OS_LINUX)
	if (getExeAbsoluteFilename(argv[0], g_exe_name, \
		sizeof(g_exe_name)) == NULL)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return errno != 0 ? errno : ENOENT;
	}
#endif

	memset(bind_addr, 0, sizeof(bind_addr));
	if ((result=tracker_load_from_conf_file(conf_filename, \
			bind_addr, sizeof(bind_addr))) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}
	//g_tracker_last_status只记录了uptime和last check time作用未知
	if ((result=tracker_load_status_from_file(&g_tracker_last_status)) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	base64_init_ex(&g_base64_context, 0, '-', '_', '.');
	if ((result=set_rand_seed()) != 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"set_rand_seed fail, program exit!", __LINE__);
		return result;
	}
	//内存分配及历史group和storage载入
	if ((result=tracker_mem_init()) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	sock = socketServer(bind_addr, g_server_port, &result);
	if (sock < 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	if ((result=tcpsetserveropt(sock, g_fdfs_network_timeout)) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}
	//后台运行
	daemon_init(false);
	umask(0);
	//将pid记录到文件中
	if ((result=write_to_pid_file(pidFilename)) != 0)
	{
		log_destroy();
		return result;
	}
	//启动工作线程,这一块需要重点看
	if ((result=tracker_service_init()) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}
	//注册信号处理函数
	memset(&act, 0, sizeof(act));
	sigemptyset(&act.sa_mask);

	act.sa_handler = sigUsrHandler;
	if(sigaction(SIGUSR1, &act, NULL) < 0 || \
		sigaction(SIGUSR2, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}

	act.sa_handler = sigHupHandler;
	if(sigaction(SIGHUP, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}
	
	act.sa_handler = SIG_IGN;
	if(sigaction(SIGPIPE, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}

	act.sa_handler = sigQuitHandler;
	if(sigaction(SIGINT, &act, NULL) < 0 || \
		sigaction(SIGTERM, &act, NULL) < 0 || \
		sigaction(SIGQUIT, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}

#if defined(DEBUG_FLAG)
/*
#if defined(OS_LINUX)
	memset(&act, 0, sizeof(act));
	sigemptyset(&act.sa_mask);
        act.sa_sigaction = sigSegvHandler;
        act.sa_flags = SA_SIGINFO;
        if (sigaction(SIGSEGV, &act, NULL) < 0 || \
        	sigaction(SIGABRT, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}
#endif
*/

	memset(&act, 0, sizeof(act));
	sigemptyset(&act.sa_mask);
	act.sa_handler = sigDumpHandler;
	if(sigaction(SIGUSR1, &act, NULL) < 0 || \
		sigaction(SIGUSR2, &act, NULL) < 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"call sigaction fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		logCrit("exit abnormally!\n");
		return errno;
	}
#endif

#ifdef WITH_HTTPD
	if (!g_http_params.disabled)
	{
		if ((result=tracker_httpd_start(bind_addr)) != 0)
		{
			logCrit("file: "__FILE__", line: %d, " \
				"tracker_httpd_start fail, program exit!", \
				__LINE__);
			return result;
		}

	}

	if ((result=tracker_http_check_start()) != 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"tracker_http_check_start fail, " \
			"program exit!", __LINE__);
		return result;
	}
#endif

	if ((result=set_run_by(g_run_by_group, g_run_by_user)) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}
	//schedule 调度线程,主要作用待细看
	scheduleArray.entries = scheduleEntries;
	scheduleArray.count = 0;
	memset(scheduleEntries, 0, sizeof(scheduleEntries));
	//日志处理,日志是先存在cache中的,需要定时存储
	INIT_SCHEDULE_ENTRY(scheduleEntries[scheduleArray.count],
		scheduleArray.count + 1, TIME_NONE, TIME_NONE, TIME_NONE,
		g_sync_log_buff_interval, log_sync_func, &g_log_context);
	scheduleArray.count++;
	//用户检测trunk server服务器是否可用(trunk server是选定的一个storage)
	INIT_SCHEDULE_ENTRY(scheduleEntries[scheduleArray.count],
		scheduleArray.count + 1, TIME_NONE, TIME_NONE, TIME_NONE,
		g_check_active_interval, tracker_mem_check_alive, NULL);
	scheduleArray.count++;
	//每5分钟刷新一下status
	INIT_SCHEDULE_ENTRY(scheduleEntries[scheduleArray.count],
		scheduleArray.count + 1, 0, 0, 0,
		TRACKER_SYNC_STATUS_FILE_INTERVAL,
		tracker_write_status_to_file, NULL);
	scheduleArray.count++;

	if (g_rotate_error_log)
	{
		INIT_SCHEDULE_ENTRY_EX(scheduleEntries[scheduleArray.count],
			scheduleArray.count + 1, g_error_log_rotate_time,
			24 * 3600, log_notify_rotate, &g_log_context);
		scheduleArray.count++;

		if (g_log_file_keep_days > 0)
		{
			log_set_keep_days(&g_log_context, g_log_file_keep_days);

			INIT_SCHEDULE_ENTRY(scheduleEntries[scheduleArray.count],
				scheduleArray.count + 1, 1, 0, 0, 24 * 3600,
				log_delete_old_files, &g_log_context);
			scheduleArray.count++;
		}
	}

	if ((result=sched_start(&scheduleArray, &schedule_tid, \
		g_thread_stack_size, (bool * volatile)&g_continue_flag)) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}
	//选主机制,tracker默认不会把自己加入队列
	if ((result=tracker_relationship_init()) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	log_set_cache(true);

	bTerminateFlag = false;
	bAcceptEndFlag = false;
	//accept线程,工作线程和消息接收线程是分开的
	tracker_accept_loop(sock);
	bAcceptEndFlag = true;
	if (g_schedule_flag)
	{
		pthread_kill(schedule_tid, SIGINT);
	}
	tracker_terminate_threads();

#ifdef WITH_HTTPD
	if (g_http_check_flag)
	{
		tracker_http_check_stop();
	}

	while (g_http_check_flag)
	{
		usleep(50000);
	}
#endif

	wait_count = 0;
	//线程数和调度flag还在,则继续运行程序
	while ((g_tracker_thread_count != 0) || g_schedule_flag)
	{

/*
#if defined(DEBUG_FLAG) && defined(OS_LINUX)
		if (bSegmentFault)
		{
			sleep(5);
			break;
		}
#endif
*/

		usleep(10000);
		if (++wait_count > 3000)
		{
			logWarning("waiting timeout, exit!");
			break;
		}
	}
	
	tracker_mem_destroy();
	tracker_service_destroy();
	tracker_relationship_destroy();
	
	logInfo("exit normally.\n");
	log_destroy();
	
	delete_pid_file(pidFilename);
	return 0;
}
Example #23
0
parse_switches (j_compress_ptr cinfo, int argc, char **argv,
		int last_file_arg_seen, jboolean for_real)
/* Parse optional switches.
 * Returns argv[] index of first file-name argument (== argc if none).
 * Any file names with indexes <= last_file_arg_seen are ignored;
 * they have presumably been processed in a previous iteration.
 * (Pass 0 for last_file_arg_seen on the first or only iteration.)
 * for_real is FALSE on the first (dummy) pass; we may skip any expensive
 * processing.
 */
{
  int argn;
  char * arg;
  jboolean simple_progressive;
  char * scansarg = NULL;	/* saves -scans parm if any */

  /* Set up default JPEG parameters. */
  simple_progressive = FALSE;
  outfilename = NULL;
  copyoption = JCOPYOPT_DEFAULT;
  transformoption.transform = JXFORM_NONE;
  transformoption.trim = FALSE;
  transformoption.force_grayscale = FALSE;
  cinfo->err->trace_level = 0;

  /* Scan command line options, adjust parameters */

  for (argn = 1; argn < argc; argn++) {
    arg = argv[argn];
    if (*arg != '-') {
      /* Not a switch, must be a file name argument */
      if (argn <= last_file_arg_seen) {
	outfilename = NULL;	/* -outfile applies to just one input file */
	continue;		/* ignore this name if previously processed */
      }
      break;			/* else done parsing switches */
    }
    arg++;			/* advance past switch marker character */

    if (keymatch(arg, "arithmetic", 1)) {
      /* Use arithmetic coding. */
#ifdef C_ARITH_CODING_SUPPORTED
      cinfo->arith_code = TRUE;
#else
      fprintf(stderr, "%s: sorry, arithmetic coding not supported\n",
	      progname);
      exit(EXIT_FAILURE);
#endif

    } else if (keymatch(arg, "copy", 1)) {
      /* Select which extra markers to copy. */
      if (++argn >= argc)	/* advance to next argument */
	usage();
      if (keymatch(argv[argn], "none", 1)) {
	copyoption = JCOPYOPT_NONE;
      } else if (keymatch(argv[argn], "comments", 1)) {
	copyoption = JCOPYOPT_COMMENTS;
      } else if (keymatch(argv[argn], "all", 1)) {
	copyoption = JCOPYOPT_ALL;
      } else
	usage();

    } else if (keymatch(arg, "debug", 1) || keymatch(arg, "verbose", 1)) {
      /* Enable debug printouts. */
      /* On first -d, print version identification */
      static jboolean printed_version = FALSE;

      if (! printed_version) {
	fprintf(stderr, "Independent JPEG Group's JPEGTRAN, version %s\n%s\n",
		JVERSION, JCOPYRIGHT);
	printed_version = TRUE;
      }
      cinfo->err->trace_level++;

    } else if (keymatch(arg, "flip", 1)) {
      /* Mirror left-right or top-bottom. */
      if (++argn >= argc)	/* advance to next argument */
	usage();
      if (keymatch(argv[argn], "horizontal", 1))
	select_transform(JXFORM_FLIP_H);
      else if (keymatch(argv[argn], "vertical", 1))
	select_transform(JXFORM_FLIP_V);
      else
	usage();

    } else if (keymatch(arg, "grayscale", 1) || keymatch(arg, "greyscale",1)) {
      /* Force to grayscale. */
#if TRANSFORMS_SUPPORTED
      transformoption.force_grayscale = TRUE;
#else
      select_transform(JXFORM_NONE);	/* force an error */
#endif

    } else if (keymatch(arg, "maxmemory", 3)) {
      /* Maximum memory in Kb (or Mb with 'm'). */
      long lval;
      char ch = 'x';

      if (++argn >= argc)	/* advance to next argument */
	usage();
      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
	usage();
      if (ch == 'm' || ch == 'M')
	lval *= 1000L;
      cinfo->mem->max_memory_to_use = lval * 1000L;

    } else if (keymatch(arg, "optimize", 1) || keymatch(arg, "optimise", 1)) {
      /* Enable entropy parm optimization. */
#ifdef ENTROPY_OPT_SUPPORTED
      cinfo->optimize_coding = TRUE;
#else
      fprintf(stderr, "%s: sorry, entropy optimization was not compiled\n",
	      progname);
      exit(EXIT_FAILURE);
#endif

    } else if (keymatch(arg, "outfile", 4)) {
      /* Set output file name. */
      if (++argn >= argc)	/* advance to next argument */
	usage();
      outfilename = argv[argn];	/* save it away for later use */

    } else if (keymatch(arg, "progressive", 1)) {
      /* Select simple progressive mode. */
#ifdef C_PROGRESSIVE_SUPPORTED
      simple_progressive = TRUE;
      /* We must postpone execution until num_components is known. */
#else
      fprintf(stderr, "%s: sorry, progressive output was not compiled\n",
	      progname);
      exit(EXIT_FAILURE);
#endif

    } else if (keymatch(arg, "restart", 1)) {
      /* Restart interval in MCU rows (or in MCUs with 'b'). */
      long lval;
      char ch = 'x';

      if (++argn >= argc)	/* advance to next argument */
	usage();
      if (sscanf(argv[argn], "%ld%c", &lval, &ch) < 1)
	usage();
      if (lval < 0 || lval > 65535L)
	usage();
      if (ch == 'b' || ch == 'B') {
	cinfo->restart_interval = (unsigned int) lval;
	cinfo->restart_in_rows = 0; /* else prior '-restart n' overrides me */
      } else {
	cinfo->restart_in_rows = (int) lval;
	/* restart_interval will be computed during startup */
      }

    } else if (keymatch(arg, "rotate", 2)) {
      /* Rotate 90, 180, or 270 degrees (measured clockwise). */
      if (++argn >= argc)	/* advance to next argument */
	usage();
      if (keymatch(argv[argn], "90", 2))
	select_transform(JXFORM_ROT_90);
      else if (keymatch(argv[argn], "180", 3))
	select_transform(JXFORM_ROT_180);
      else if (keymatch(argv[argn], "270", 3))
	select_transform(JXFORM_ROT_270);
      else
	usage();

    } else if (keymatch(arg, "scans", 1)) {
      /* Set scan script. */
#ifdef C_MULTISCAN_FILES_SUPPORTED
      if (++argn >= argc)	/* advance to next argument */
	usage();
      scansarg = argv[argn];
      /* We must postpone reading the file in case -progressive appears. */
#else
      fprintf(stderr, "%s: sorry, multi-scan output was not compiled\n",
	      progname);
      exit(EXIT_FAILURE);
#endif

    } else if (keymatch(arg, "transpose", 1)) {
      /* Transpose (across UL-to-LR axis). */
      select_transform(JXFORM_TRANSPOSE);

    } else if (keymatch(arg, "transverse", 6)) {
      /* Transverse transpose (across UR-to-LL axis). */
      select_transform(JXFORM_TRANSVERSE);

    } else if (keymatch(arg, "trim", 3)) {
      /* Trim off any partial edge MCUs that the transform can't handle. */
      transformoption.trim = TRUE;

    } else {
      usage();			/* bogus switch */
    }
  }

  /* Post-switch-scanning cleanup */

  if (for_real) {

#ifdef C_PROGRESSIVE_SUPPORTED
    if (simple_progressive)	/* process -progressive; -scans can override */
      jpeg_simple_progression(cinfo);
#endif

#ifdef C_MULTISCAN_FILES_SUPPORTED
    if (scansarg != NULL)	/* process -scans if it was present */
      if (! read_scan_script(cinfo, scansarg))
	usage();
#endif
  }

  return argn;			/* return index of next arg (file name) */
}
Example #24
0
void main(int argc, char **argv)
{
    int row, col, row_size, col_size;
    char input_image[512], qimage[512];
    unsigned char **imgin;
    int *bound, *reco, input, label, output, numlev, numbits, c;
    int minvalue, maxvalue, range, level, stepsize, temp, end_flag;
    FILE *ofp;
  extern int  optind;
  extern char *optarg;

    fprintf(stderr,"\n\n\t\tUniform Quantization of Images - Encoder\n");

  ofp = stdout;
  strcpy(qimage,"standard out");
  numlev = -1;
  numbits = -1;
  minvalue = 0;
  maxvalue = 255;

  while((c=getopt(argc,argv,"i:o:l:b:m:t:h"))!=EOF)
  {
   switch (c){
   case 'i':
         strcpy(input_image,optarg);
         break;
   case 'o':
         strcpy(qimage,optarg);
         ofp = fopen(optarg,"wb");
         break;
   case 'l':
         sscanf(optarg,"%d", &numlev);
         break;
   case 'b':
         sscanf(optarg,"%d", &numbits);
         break;
   case 'm':
         sscanf(optarg,"%d", &maxvalue);
         break;
   case 't':
         sscanf(optarg,"%d", &minvalue);
         break;
   case 'x':
         sscanf(optarg,"%d", &row_size);
         break;
   case 'y':
         sscanf(optarg,"%d", &col_size);
         break;
   case 'h':
         usage();
         exit(1);
    }
   }

   if(numlev > 0 && numbits > 0)
   {
    temp = (int) pow((double) 2,(double) numbits);  
    if(temp != numlev)
    {
     fprintf(stderr,"\n You have entered values for the number of levels and\n");
     fprintf(stderr,"number of bits that are not compatible.  The number of\n");
     fprintf(stderr,"levels should be 2^(number of bits).  If you want to use\n");
     fprintf(stderr,"a number of levels which is not a power of 2 then only\n");
     fprintf(stderr,"enter a value for the number of levels.\n");
     exit(1);
    }
   }

   if(numlev < 0 && numbits < 0)
   {
    fprintf(stderr,"\n Enter number of bits per pixel: ");
    scanf("%d",&numbits);
    numlev = (int) pow((double) 2,(double) numbits);  
   }

   if (numbits <= 0 || numbits >= 8) {
    fprintf(stderr,"\n You have entered values for the number of bits that\n");
    fprintf(stderr,"are not compatible.  The number of bits should between\n");
    fprintf(stderr,"0 (zero) and 8 (eight).\n");
    exit(1);
   }

   if(numlev < 0 && numbits > 0)
    numlev = (int) pow((double) 2,(double) numbits);  
  
   if(numlev > 0 && numbits < 0)
     numbits = (int) (log((double)numlev)/log((double) 2.) + 0.99999);
 
/* Determine range, and stepsize for the quantizer
*/

   range = maxvalue - minvalue + 1;
   stepsize = range/(numlev);

/* Allocate space for the boundary values */

   bound = (int *) calloc((numlev+1),sizeof(int));

/* Construct the boundary tables   */

   bound[0] = minvalue;
   for(level=1; level<=numlev; level++)
     {
      bound[level] = bound[level-1] + stepsize;
     }

/* Find out how large the image is */

    image_size(input_image, &row_size, &col_size);   

/* Allocate space for input image  */

    imgin  = (unsigned char **) calloc(row_size,sizeof(char *));  
    for(row=0; row<row_size; row++)
     imgin[row] = (unsigned char *) calloc((col_size),sizeof(char));

/* Read the input image */

    readimage(input_image, imgin, row_size, col_size);  

/*  Store coding parameters in the output file */

   fwrite(&numlev,1,sizeof(int),ofp);
   fwrite(&numbits,1,sizeof(int),ofp);
   fwrite(&maxvalue,1,sizeof(int),ofp);
   fwrite(&minvalue,1,sizeof(int),ofp);
   fwrite(&row_size,1,sizeof(int),ofp);
   fwrite(&col_size,1,sizeof(int),ofp);

   struct Queue* code_write;
   code_write = (struct Queue*) malloc(sizeof(struct Queue));
   code_write->front = NULL;
   code_write->rear = NULL;
   code_write->size = 0;
	
//   Print(&(code_write)->front);

/* encode each pixel into an integer label and store  */
   end_flag = 0;
   for(row=0; row<row_size; row++)
      for(col=0; col<col_size; col++)
         {
          if(row == row_size-1 && col == col_size - 1)
            end_flag = 1;
          input = imgin[row][col];
          label = encuqi(input,bound,numlev);
//          printf("%d %d, ", input, label);
//          printf("%d ", &ofp);
//          stuffit(label,numbits,&ofp,end_flag);
          stuffit(label,numbits,&code_write,end_flag);
         }

//   Print(&code_write->front);
   while(code_write->size >= 8) {
     write_to_file(&ofp, &code_write);
   }
	
//   printf("%d", code_write->size);

   FILE *fp;
   fp = fopen(input_image, "rb");
   double ratio_com = get_ratio(&fp, &ofp);
   
   printf("\n Ratio compression := %lf %%\n", ratio_com);
   
   fclose(fp);
   fclose(ofp);

}
Example #25
0
int main( int argc, char* argv[] ){

  int i,j;
  ogg_packet op;
  SDL_Event event;
  int hasdatatobuffer = 1;
  int playbackdone = 0;
  double now, delay, last_frame_time = 0;

  int frameNum=0;
  int skipNum=0;

  /* takes first argument as file to play */
  /* this works better on Windows and is more convenient
     for drag and drop ogg files over the .exe */

  if( argc != 2 )
  {
    usage();
    exit(0);
  }

  infile  = fopen( argv[1], "rb" );

  /* start up Ogg stream synchronization layer */
  ogg_sync_init(&oy);

  /* init supporting Vorbis structures needed in header parsing */
  vorbis_info_init(&vi);
  vorbis_comment_init(&vc);

  /* init supporting Theora structures needed in header parsing */
  theora_comment_init(&tc);
  theora_info_init(&ti);

  parseHeaders();

  /* force audio off */
  /* vorbis_p = 0; */

  /* initialize decoders */
  if(theora_p){
    theora_decode_init(&td,&ti);
    printf("Ogg logical stream %x is Theora %dx%d %.02f fps video\n"
           "  Frame content is %dx%d with offset (%d,%d).\n",
	   to.serialno,ti.width,ti.height, (double)ti.fps_numerator/ti.fps_denominator,
	   ti.frame_width, ti.frame_height, ti.offset_x, ti.offset_y);
    report_colorspace(&ti);
    dump_comments(&tc);
  }else{
    /* tear down the partial theora setup */
    theora_info_clear(&ti);
    theora_comment_clear(&tc);
  }
  if(vorbis_p){
    vorbis_synthesis_init(&vd,&vi);
    vorbis_block_init(&vd,&vb);  
    printf("Ogg logical stream %x is Vorbis %d channel %d Hz audio.\n",
	   vo.serialno,vi.channels,vi.rate);
  }else{
    /* tear down the partial vorbis setup */
    vorbis_info_clear(&vi);
    vorbis_comment_clear(&vc);
  }
  /* open audio */
  if(vorbis_p)open_audio();
  /* open video */
  if(theora_p)open_video();
  
  /* our main loop */
  while(!playbackdone){

    /* break out on SDL quit event */
    if ( SDL_PollEvent ( &event ) )
    {
      if ( event.type == SDL_QUIT ) break ;
    }

    /* get some audio data */
    while(vorbis_p && !audiobuf_ready){
      int ret;
      float **pcm;
      int count = 0;
      int maxBytesToWrite;

      /* is there pending audio? does it fit our circular buffer without blocking? */
      ret=vorbis_synthesis_pcmout(&vd,&pcm);
      maxBytesToWrite = GetAudioStreamWriteable(aOutStream);

      if (maxBytesToWrite<=FRAMES_PER_BUFFER){
        /* break out until there is a significant amount of
           data to avoid a series of small write operations. */
        break;
      }
      /* if there's pending, decoded audio, grab it */
      if((ret>0)&&(maxBytesToWrite>0)){

	for(i=0;i<ret && i<(maxBytesToWrite/vi.channels);i++)
	  for(j=0;j<vi.channels;j++){
	    int val=(int)(pcm[j][i]*32767.f);
	    if(val>32767)val=32767;
	    if(val<-32768)val=-32768;
	    samples[count]=val;
	    count++;
	  }
	if(WriteAudioStream( aOutStream, samples, i )) {
	  if(count==maxBytesToWrite){
	    audiobuf_ready=1;
	  }
	}
        vorbis_synthesis_read(&vd,i);

	if(vd.granulepos>=0)
	  audiobuf_granulepos=vd.granulepos-ret+i;
	else
	  audiobuf_granulepos+=i;

      }else{
	
	/* no pending audio; is there a pending packet to decode? */
	if(ogg_stream_packetout(&vo,&op)>0){
	  if(vorbis_synthesis(&vb,&op)==0) /* test for success! */
	   vorbis_synthesis_blockin(&vd,&vb);
	}else	/* we need more data; break out to suck in another page */
	  break;
      }
    } /* end audio cycle */

    while(theora_p && !videobuf_ready){
      /* get one video packet... */
      if(ogg_stream_packetout(&to,&op)>0){
      
        theora_decode_packetin(&td,&op);

	  videobuf_granulepos=td.granulepos;
	  videobuf_time=theora_granule_time(&td,videobuf_granulepos);
	  /* update the frame counter */
	  frameNum++;

	  /* check if this frame time has not passed yet.
	     If the frame is late we need to decode additonal
	     ones and keep looping, since theora at this stage
	     needs to decode all frames */
	  now=get_time();
	  delay=videobuf_time-now;
	  if(delay>=0.0){
		/* got a good frame, not late, ready to break out */
		videobuf_ready=1;
	  }else if(now-last_frame_time>=1.0){
		/* display at least one frame per second, regardless */
		videobuf_ready=1;
	  }else{
		fprintf(stderr, "dropping frame %d (%.3fs behind)\n",
			frameNum, -delay);
	   }
      }else{
	/* need more data */
	break;
      }
    }

    if(!hasdatatobuffer && !videobuf_ready && !audiobuf_ready){
      isPlaying = 0;
      playbackdone = 1;
    }

    /* if we're set for the next frame, sleep */
    if((!theora_p || videobuf_ready) && 
       (!vorbis_p || audiobuf_ready)){
        int ticks = 1.0e3*(videobuf_time-get_time());
	if(ticks>0)
          SDL_Delay(ticks);
    }
 
    if(videobuf_ready){
      /* time to write our cached frame */
      video_write();
      videobuf_ready=0;
      last_frame_time=get_time();

      /* if audio has not started (first frame) then start it */
      if ((!isPlaying)&&(vorbis_p)){
        start_audio();
        isPlaying = 1;
      }
    }

    /* HACK: always look for more audio data */
    audiobuf_ready=0;

    /* buffer compressed data every loop */
    if(hasdatatobuffer){
      hasdatatobuffer=buffer_data(&oy);
      if(hasdatatobuffer==0){
        printf("Ogg buffering stopped, end of file reached.\n");
      }
    }
    
    if (ogg_sync_pageout(&oy,&og)>0){
      queue_page(&og);
    }

  } /* playbackdone */

  /* show number of video frames decoded */
  printf( "\n");
  printf( "Frames decoded: %d", frameNum );
  if(skipNum)
    printf( " (only %d shown)", frameNum-skipNum);
  printf( "\n" );

  /* tear it all down */
  fclose( infile );

  if(vorbis_p){
    audio_close();

    ogg_stream_clear(&vo);
    vorbis_block_clear(&vb);
    vorbis_dsp_clear(&vd);
    vorbis_comment_clear(&vc);
    vorbis_info_clear(&vi); 
  }
  if(theora_p){
    ogg_stream_clear(&to);
    theora_clear(&td);
    theora_comment_clear(&tc);
    theora_info_clear(&ti);
  }
  ogg_sync_clear(&oy);

  printf("\r                                                              "
	 "\nDone.\n");
	 
  SDL_Quit();

  return(0);

}
int main(int argc, char **argv)
{
	char *output_file = NULL;
	char *entry_table_file = NULL;
	FILE *output = stdout;
	FILE *export_file;
	struct brw_program_instruction *entry, *entry1, *tmp_entry;
	int err, inst_offset;
	char o;
	void *mem_ctx;

	while ((o = getopt_long(argc, argv, "e:l:o:g:abW", longopts, NULL)) != -1) {
		switch (o) {
		case 'o':
			if (strcmp(optarg, "-") != 0)
				output_file = optarg;

			break;

		case 'g': {
			char *dec_ptr, *end_ptr;
			unsigned long decimal;

			gen_level = strtol(optarg, &dec_ptr, 10) * 10;

			if (*dec_ptr == '.') {
				decimal = strtoul(++dec_ptr, &end_ptr, 10);
				if (end_ptr != dec_ptr && *end_ptr == '\0') {
					if (decimal > 10) {
						fprintf(stderr, "Invalid Gen X decimal version\n");
						exit(1);
					}
					gen_level += decimal;
				}
			}

			if (gen_level < 40 || gen_level > 90) {
				usage();
				exit(1);
			}

			break;
		}

		case 'a':
			advanced_flag = 1;
			break;
		case 'b':
			binary_like_output = 1;
			break;

		case 'e':
			need_export = 1;
			if (strcmp(optarg, "-") != 0)
				export_filename = optarg;
			break;

		case 'l':
			if (strcmp(optarg, "-") != 0)
				entry_table_file = optarg;
			break;

		case 'W':
			warning_flags |= WARN_ALL;
			break;

		default:
			usage();
			exit(1);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 1) {
		usage();
		exit(1);
	}

	if (strcmp(argv[0], "-") != 0) {
		input_filename = argv[0];
		yyin = fopen(input_filename, "r");
		if (yyin == NULL) {
			perror("Couldn't open input file");
			exit(1);
		}
	}

	brw_init_context(&genasm_brw_context, gen_level);
	mem_ctx = ralloc_context(NULL);
	brw_init_compile(&genasm_brw_context, &genasm_compile, mem_ctx);

	err = yyparse();

	if (strcmp(argv[0], "-"))
		fclose(yyin);

	yylex_destroy();

	if (err || errors)
		exit (1);

	if (output_file) {
		output = fopen(output_file, "w");
		if (output == NULL) {
			perror("Couldn't open output file");
			exit(1);
		}

	}

	if (read_entry_file(entry_table_file)) {
		fprintf(stderr, "Read entry file error\n");
		exit(1);
	}
	inst_offset = 0 ;
	for (entry = compiled_program.first;
		entry != NULL; entry = entry->next) {
	    entry->inst_offset = inst_offset;
	    entry1 = entry->next;
	    if (entry1 && is_label(entry1) && is_entry_point(entry1)) {
		// insert NOP instructions until (inst_offset+1) % 4 == 0
		while (((inst_offset+1) % 4) != 0) {
		    tmp_entry = calloc(sizeof(*tmp_entry), 1);
		    tmp_entry->insn.gen.header.opcode = BRW_OPCODE_NOP;
		    entry->next = tmp_entry;
		    tmp_entry->next = entry1;
		    entry = tmp_entry;
		    tmp_entry->inst_offset = ++inst_offset;
		}
	    }
	    if (!is_label(entry))
              inst_offset++;
	}

	for (entry = compiled_program.first; entry; entry = entry->next)
	    if (is_label(entry))
		add_label(entry);

	if (need_export) {
		if (export_filename) {
			export_file = fopen(export_filename, "w");
		} else {
			export_file = fopen("export.inc", "w");
		}
		for (entry = compiled_program.first;
			entry != NULL; entry = entry->next) {
		    if (is_label(entry))
			fprintf(export_file, "#define %s_IP %d\n",
				label_name(entry), (IS_GENx(5) ? 2 : 1)*(entry->inst_offset));
		}
		fclose(export_file);
	}

	for (entry = compiled_program.first; entry; entry = entry->next) {
	    struct relocation *reloc = &entry->reloc;

	    if (!is_relocatable(entry))
		continue;

	    if (reloc->first_reloc_target)
		reloc->first_reloc_offset = label_to_addr(reloc->first_reloc_target, entry->inst_offset) - entry->inst_offset;

	    if (reloc->second_reloc_target)
		reloc->second_reloc_offset = label_to_addr(reloc->second_reloc_target, entry->inst_offset) - entry->inst_offset;

	    if (reloc->second_reloc_offset) { // this is a branch instruction with two offset arguments
                set_branch_two_offsets(entry, reloc->first_reloc_offset, reloc->second_reloc_offset);
	    } else if (reloc->first_reloc_offset) {
                set_branch_one_offset(entry, reloc->first_reloc_offset);
	    }
	}

	if (binary_like_output)
		fprintf(output, "%s", binary_prepend);

	for (entry = compiled_program.first;
		entry != NULL;
		entry = entry1) {
	    entry1 = entry->next;
	    if (!is_label(entry))
		print_instruction(output, &entry->insn.gen);
	    else
		free(entry->insn.label.name);
	    free(entry);
	}
	if (binary_like_output)
		fprintf(output, "};");

	free_entry_point_table(entry_point_table);
	free_hash_table(declared_register_table);
	free_label_table(label_table);

	fflush (output);
	if (ferror (output)) {
	    perror ("Could not flush output file");
	    if (output_file)
		unlink (output_file);
	    err = 1;
	}
	return err;
}
Example #27
0
int
read_args(struct args *args, int argc, char **argv)
{
    int i;
    /* Count positions in collection arrays */
    int libs_count = 0, lib_dirs_count = 0, pkg_dirs_count = 0,
        llc_opts_count = 0, as_opts_count = 0, ld_opts_count = 0,
        sources_count = 0;

    init_args(args);

    for (i = 1; i < argc; ++i) {
        if (!strcmp (argv[i], "-h") ||
            !strcmp (argv[i], "-help") ||
            !strcmp (argv[i], "--help")) {
            usage (*argv);
            args->exit_code = 0;
            return 1;
        }

        else if (!strcmp (argv[i], "-version")) {
            version ();
            args->exit_code = 0;
            return 1;
        }

        else if (!strncmp (argv[i], "-o", 2)) {
            args->output = consume (argc, argv, &i, 2, 0);
        }

        else if (!strcmp (argv[i], "-v") || !strcmp (argv[i], "-verbose")) {
            args->verbose = 1;
        }

        else if (!strncmp (argv[i], "-path=", 6)) {
            /* Acceptable syntax:
             *  -path=help
             *  -path=key:value
             */
            /* Message is down here to fit it in... */
#define MSG "The -path argument can be used to give paths to files at compile" \
                " time.\nThe format is \"-path=key:value\", where the valid " \
                "keys are:\n  llc, llvm-as, as, ld, crt1-64, crti-64, " \
                "crtn-64, ldso-64,\n  crt1-32, crti-32, crtn-32, ldso-32, " \
                "runtime-64, runtime-32\n"
            if (!strcmp (argv[i], "-path=help")) {
                printf (MSG);
                args->exit_code = 0;
                return 1;
            }
#undef MSG

            // Separate key and value
            if (argv[i][6] == 0)
                error_message("-path option expects argument");
            char *key = argv[i] + 6;
            char *value = strchr (key, ':');
            if (key == value || !value) {
                // -path=:blah or -path=blah
                error_message("-path option must be given as -path=key:value");
            }
            // 'key' and 'value' don't quite point to key and value yet.
            // 'key' must be NUL-terminated, and 'value' must be advanced one.
            *value = 0; // NUL-terminate 'key'
            ++value;
            if (*value == 0)
                error_message("-path option must be given as -path=key:value");

            if (!strcmp (key, "llc"))
                args->llc = value;
            else if (!strcmp (key, "llvm-as"))
                args->llvm_as = value;
            else if (!strcmp (key, "as"))
                args->as = value;
            else if (!strcmp (key, "ld"))
                args->ld = value;
            else if (!strcmp (key, "crt1-64"))
                args->crt1_64 = value;
            else if (!strcmp (key, "crti-64"))
                args->crti_64 = value;
            else if (!strcmp (key, "crtn-64"))
                args->crtn_64 = value;
            else if (!strcmp (key, "ldso-64"))
                args->ldso_64 = value;
            else if (!strcmp (key, "crt1-32"))
                args->crt1_32 = value;
            else if (!strcmp (key, "crti-32"))
                args->crti_32 = value;
            else if (!strcmp (key, "crtn-32"))
                args->crtn_32 = value;
            else if (!strcmp (key, "ldso-32"))
                args->ldso_32 = value;
            else if (!strcmp (key, "runtime-64"))
                args->runtime_64 = value;
            else if (!strcmp (key, "runtime-32"))
                args->runtime_32 = value;
            else
                error_message ("invalid argument to -path");

        }

        else if (!strcmp (argv[i], "-path")) {
            // Check for and complain about:
            //  -path help
            //  -path key:value
            //  etc.
            error_message ("-path option must be given as -path=key:value"); 
        }

        else if (!strcmp (argv[i], "-list-paths")) {
            args->paths_only = 1;
        }

        else if (!strncmp (argv[i], "-llc", 4)) {
            if (llc_opts_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -llc");
            }
            args->llc_opts[llc_opts_count] = consume
                (argc, argv, &i, 4, 1);
            ++llc_opts_count;
        }

        else if (!strncmp (argv[i], "-as", 3)) {
            if (as_opts_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -as");
            }
            args->as_opts[as_opts_count] = consume
                (argc, argv, &i, 3, 1);
            ++as_opts_count;
        }

        else if (!strncmp (argv[i], "-ld", 3)) {
            if (ld_opts_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -ld");
            }
            args->ld_opts[ld_opts_count] = consume
                (argc, argv, &i, 3, 1);
            ++ld_opts_count;
        }

        else if (!strcmp (argv[i], "-g")) {
            args->debug = 1;
        }

        else if (!strncmp (argv[i], "-O", 2)) {
            if (argv[i][2] >= '0' && argv[i][2] <= '3')
                args->optlevel = argv[i][2] - '0';
            else
                error_message ("-O must be given as -O0, -O1, -O2, -O3");
        }

        /* This MUST stay before -m */
        else if (!strncmp (argv[i], "-malloc", 7)) {
            args->malloc = consume (argc, argv, &i, 7, 0);
        }

        /* This MUST stay after -malloc */
        else if (!strncmp (argv[i], "-m", 2)) {
            if (!strcmp (argv[i], "-m32"))
                args->machine = "32";
            else if (!strcmp (argv[i], "-m64"))
                args->machine = "64";
            else
                error_message ("-m must be given as -m32, -m64");
        }

        else if (!strcmp (argv[i], "-fPIC")) {
            args->fpic = 1;
        }

        else if (!strncmp (argv[i], "-l", 2)) {
            if (libs_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -l");
            }
            args->libs[libs_count] = consume
                (argc, argv, &i, 2, 0);
            ++libs_count;
        }

        else if (!strncmp (argv[i], "-L", 2)) {
            if (lib_dirs_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -L");
            }
            args->lib_dirs[lib_dirs_count] = consume
                (argc, argv, &i, 2, 0);
            ++lib_dirs_count;
        }

        else if (!strncmp (argv[i], "-P", 2)) {
            if (pkg_dirs_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many occurrences of -P");
            }
            args->pkg_dirs[pkg_dirs_count] = consume
                (argc, argv, &i, 2, 0);
            ++pkg_dirs_count;
        }

        else if (!strcmp (argv[i], "-emit-llvm")) {
            args->emit_llvm = 1;
        }

        else if (!strcmp (argv[i], "-S")) {
            args->assembly = 1;
        }

        else if (!strcmp (argv[i], "-c")) {
            args->objfile = 1;
        }

        else if (!strcmp (argv[i], "-nogc")) {
            args->nogc = 1;
        }

        else if (!strcmp (argv[i], "-nomemabort")) {
            args->nomemabort = 1;
        }

        else if (!strcmp (argv[i], "-noboundck")) {
            args->noboundck = 1;
        }

        else if (!strcmp (argv[i], "-sm")) {
            args->sm = 1;
        }

        else if (!strcmp (argv[i], "-free")) {
            args->free = consume (argc, argv, &i, 5, 0);
        }

        else if (!strcmp (argv[i], "-debug-mode")) {
            args->debug_mode = 1;
        }

        else if (!strcmp (argv[i], "-error-trace")) {
            args->error_trace = 1;
        }

        else if (!strcmp (argv[i], "-tokens")) {
            args->tokens_only = 1;
        }

        else if (!strcmp (argv[i], "-ast")) {
            args->ast_only = 1;
        }

        else if (!strcmp (argv[i], "-pre-ast")) {
            args->pre_ast_only = 1;
        }

        else if (!strcmp (argv[i], "-force-platform")) {
            args->force_platform = 1;
        }

        else if (!strcmp (argv[i], "-Wno-octalish")) {
            args->w_octalish = 0;
        }
        else if (!strcmp (argv[i], "-Woctalish")) {
            args->w_octalish = 1;
        }

        else if (*argv[i] != '-') {
            if (sources_count >= (LIST_ARG_MAX - 1)) {
                error_message ("too many source files");
            }
            args->sources[sources_count] = argv[i];
            ++sources_count;
        }

        else {
            error_message ("invalid option %s", argv[i]);
        }
    }

    return 0;
}
Example #28
0
/** program entry point */
int
main(int argc, char *argv[])
{
	int		 ch, fd;
	const char	*fmt = NULL;
	time_t		 f, t;
	struct timeb	 tb;
	extern int	 optind;
	extern char	*optarg;

	tzset();

	time(&curr_time);
	localtime_r(&curr_time, &curr_tm);

	memset(&tb, 0, sizeof(tb));
	tb.time = curr_time;
#if defined(__GLIBC__) || defined(__CYGWIN__)
	{
	struct timeval tv;
	struct timezone tz;

	gettimeofday(&tv, &tz);
	tb.timezone = tz.tz_minuteswest;
	}
#else
	/*
	 * as localtime_r(3) 
	 *	tm_gmtoff is the offset (in seconds) of the time represented
	 *	from UTC, with positive values indicating east of the Prime
	 *	Meridian.
	 * on the other hands tb.tb_timezone is minutes *west* of CUT.
	 */
	tb.timezone = -1 * (curr_tm.tm_gmtoff / 60);
#endif
	f = -1;
	t = curr_time;

	while ((ch = getopt(argc, argv, "iawhF:f:t:")) != -1)
		switch (ch) {
		case 'i':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = ISO_FMT;
			break;
		case 'a':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = ANSI_FMT;
			break;
		case 'w':
			if (fmt != NULL)
				goto fmt_redef;
			fmt = APACHE_FMT;
			break;
		case 't':
			if ((t = get_date(optarg, &tb)) < 0) {
				fprintf(stderr, "parse error: %s\n", optarg);
				exit(1);
			}
			break;
		case 'f':
			if ((f = get_date(optarg, &tb)) < 0) {
				fprintf(stderr, "parse error: %s\n", optarg);
				exit(1);
			}
			break;
		case 'F':
			if (fmt != NULL) {
		fmt_redef:
				fprintf(stderr,
				    "Format is already specified: %s\n", fmt);
				exit(1);
			}
			fmt = optarg;
			break;
		default:
		case 'h':
			usage();
			exit(1);
		}

	argc -= optind;
	if (f == -1) {
		usage();
		exit(1);
	}
	if (fmt == NULL)
		fmt = ANSI_FMT;
	argv += optind;

	if (argc <= 0) {
		usage();
		exit(1);
	}
	while (argc > 0) {
		if ((fd = open(argv[0], O_RDONLY)) < 0)
			err(1, "open(%s)", argv[0]);
		if (cut_file(fd, STDOUT_FILENO, fmt, f, t) != 0)
			err(1, "cut_file(%s)", argv[0]);
		
		close(fd);
		argv++;
		argc--;
	}

	exit(0);
}
Example #29
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    int res = 0;
    QString appIni;
    QHash<QString, QString> args = convertArgs(QCoreApplication::arguments());

    if (!args.value("-f").isEmpty()) {
        appIni = args.value("-f");
        devIni = QFileInfo(appIni).dir().path() + QDir::separator() + "development.ini";
    } else {
        QString dir = QLatin1String("..") + QDir::separator() + QLatin1String("..") + QDir::separator() + "config" +  QDir::separator();
        appIni = dir + "application.ini";
        devIni = dir + "development.ini";
    }

    if (!QFile::exists(appIni)) {
        usage();
        return 1;
    }

    QSettings appSetting(appIni, QSettings::IniFormat);
    QSettings devSetting(devIni, QSettings::IniFormat);

    // Default codec
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString codecName = appSetting.value("InternalEncoding").toString();
    if (!codecName.isEmpty()) {
        QTextCodec *c = QTextCodec::codecForName(codecName.toLatin1().constData());
        if (c) {
            codec = c;
        }
    }
    QTextCodec::setCodecForLocale(codec);

    defaultTrimMode = devSetting.value("Erb.DefaultTrimMode", "1").toInt();
    printf("Erb.DefaultTrimMode: %d\n", defaultTrimMode);

    QDir viewDir(".");
    if (!args.value("-v").isEmpty()) {
        viewDir.setPath(args.value("-v"));
    }
    if (!viewDir.exists()) {
        usage();
        return 1;
    }

    QDir outputDir(DEFAULT_OUTPUT_DIR);
    if (!args.value("-d").isEmpty()) {
        outputDir.setPath(args.value("-d"));
    }

    if (outputDir.exists()) {
        if (outputDir.path() != ".") {
            printf("  exists   %s\n", qPrintable(outputDir.path()));
        }
    } else {
        if (outputDir.mkpath(".")) {
            printf("  created  %s\n", qPrintable(outputDir.path()));
        } else {
            usage();
            return 1;
        }
    }

    bool createProFile = (args.contains("-p") || !args.contains("-P"));
    ViewConverter conv(viewDir, outputDir, createProFile);
    QString templateSystem = devSetting.value("TemplateSystem").toString();
    if (templateSystem.isEmpty()) {
        templateSystem = appSetting.value("TemplateSystem", "Erb").toString();
    }

    res = conv.convertView(templateSystem);
    return res;
}  
Example #30
0
int
main(int argc, char **argv)
{
    int port = 0;
    int optind = 0;
    int ret = 1;
    const char *host, *user, *filename = NULL;
    char *pobox = NULL;

    setprogname (argv[0]);

#ifdef KRB5
    {
	krb5_error_code ret;

	ret = krb5_init_context (&context);
	if (ret)
	    errx (1, "krb5_init_context failed: %d", ret);
    }
#endif

    if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
		&optind))
	usage (1);

    argc -= optind;
    argv += optind;

    if (do_help)
	usage (0);

    if (do_version) {
	print_version(NULL);
	return 0;
    }
	
    if (do_from && header_str == NULL)
	header_str = "From:";
    else if (header_str != NULL)
	do_from = 1;

    if (do_from) {
	if (argc == 0)
	    pobox = NULL;
	else if (argc == 1)
	    pobox = argv[0];
	else
	    usage (1);
    } else {
	if (argc == 1) {
	    filename = argv[0];
	    pobox    = NULL;
	} else if (argc == 2) {
	    filename = argv[1];
	    pobox    = argv[0];
	} else
	    usage (1);
    }

    if (port_str) {
	struct servent *s = roken_getservbyname (port_str, "tcp");

	if (s)
	    port = s->s_port;
	else {
	    char *ptr;

	    port = strtol (port_str, &ptr, 10);
	    if (port == 0 && ptr == port_str)
		errx (1, "Bad port `%s'", port_str);
	    port = htons(port);
	}
    }
    if (port == 0) {
#ifdef KRB5
	port = krb5_getportbyname (context, "kpop", "tcp", 1109);
#else
#error must define KRB5
#endif
    }

    parse_pobox (pobox, &host, &user);

#ifdef KRB5
    if (ret && use_v5) {
	ret = do_v5 (host, port, user, filename, header_str,
		     do_leave, verbose_level, do_fork);
    }
#endif
    return ret;
}