Ejemplo n.º 1
0
int main(int argc, char** argv){
    parse_args(argc, argv);

    // Create random data, either function can be used.
    //init_clustered_data();
    init_data();

    omp_set_num_threads(nThreads);

    // Iterate until no points are updated
    int updated = 1;
    while (updated) {
        updated = 0;

        #pragma omp parallel for
        for (int i = 0; i < nClusters; i++) {
            centroids[i].x = 0.0;
            centroids[i].y = 0.0;
            centroids[i].nPoints= 0;
        }

        // Compute new centroids positions
        for (int i = 0; i < nPoints; i++) {
            int c = points[i].cluster;
            centroids[c].x += points[i].x;
            centroids[c].y += points[i].y;
            centroids[c].nPoints++;
        }

        for (int i = 0; i < nClusters; i++) {
            // If a centroid lost all its points, we give it a random position
            // (to avoid dividing by 0)
            if (centroids[i].nPoints == 0) {
                centroids[i] = create_random_centroid();
            } else {
                centroids[i].x /= centroids[i].nPoints;
                centroids[i].y /= centroids[i].nPoints;
            }
        }


        double bestDistance = DBL_MAX;
        int bestCluster = -1;
        double d;
        //Reassign points to closest centroid
        #pragma omp parallel for \
        private(bestDistance, bestCluster, d)
        for (int i = 0; i < nPoints; i++) {
            bestDistance = DBL_MAX;
            bestCluster = -1;
            for (int j = 0; j < nClusters; j++) {
                d = distance(points[i], centroids[j]);
                if (d < bestDistance) {
                    bestDistance = d;
                    bestCluster = j;
                }
            }

            // If one point got reassigned to a new cluster, we have to do another iteration
            if (bestCluster != points[i].cluster) {
                updated = 1;
            }
            points[i].cluster = bestCluster;
        }
    }

    print_data();
}
Ejemplo n.º 2
0
gboolean
print_ip4_config (NMIPConfig *cfg4,
                  NmCli *nmc,
                  const char *group_prefix,
                  const char *one_field)
{
	GPtrArray *ptr_array;
	char **addr_arr = NULL;
	char **route_arr = NULL;
	char **dns_arr = NULL;
	char **domain_arr = NULL;
	char **wins_arr = NULL;
	int i = 0;
	NmcOutputField *tmpl, *arr;
	size_t tmpl_len;

	if (cfg4 == NULL)
		return FALSE;

	tmpl = nmc_fields_ip4_config;
	tmpl_len = sizeof (nmc_fields_ip4_config);
	nmc->print_fields.indices = parse_output_fields (one_field ? one_field : NMC_FIELDS_IP4_CONFIG_ALL,
	                                                 tmpl, FALSE, NULL, NULL);
	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_FIELD_NAMES);
	g_ptr_array_add (nmc->output_data, arr);

	/* addresses */
	ptr_array = nm_ip_config_get_addresses (cfg4);
	if (ptr_array) {
		addr_arr = g_new (char *, ptr_array->len + 1);
		for (i = 0; i < ptr_array->len; i++) {
			NMIPAddress *addr = (NMIPAddress *) g_ptr_array_index (ptr_array, i);

			addr_arr[i] = g_strdup_printf ("%s/%u",
			                               nm_ip_address_get_address (addr),
			                               nm_ip_address_get_prefix (addr));
		}
		addr_arr[i] = NULL;
	}

	/* routes */
	ptr_array = nm_ip_config_get_routes (cfg4);
	if (ptr_array) {
		route_arr = g_new (char *, ptr_array->len + 1);
		for (i = 0; i < ptr_array->len; i++) {
			NMIPRoute *route = (NMIPRoute *) g_ptr_array_index (ptr_array, i);
			const char *next_hop;

			next_hop = nm_ip_route_get_next_hop (route);
			if (!next_hop)
				next_hop = "0.0.0.0";

			route_arr[i] = g_strdup_printf ("dst = %s/%u, nh = %s%c mt = %u",
			                                nm_ip_route_get_dest (route),
			                                nm_ip_route_get_prefix (route),
			                                next_hop,
			                                nm_ip_route_get_metric (route) == -1 ? '\0' : ',',
			                                (guint32) nm_ip_route_get_metric (route));
		}
		route_arr[i] = NULL;
	}

	/* DNS */
	dns_arr = g_strdupv ((char **) nm_ip_config_get_nameservers (cfg4));

	/* domains */
	domain_arr = g_strdupv ((char **) nm_ip_config_get_domains (cfg4));

	/* WINS */
	wins_arr = g_strdupv ((char **) nm_ip_config_get_wins_servers (cfg4));

	arr = nmc_dup_fields_array (tmpl, tmpl_len, NMC_OF_FLAG_SECTION_PREFIX);
	set_val_strc (arr, 0, group_prefix);
	set_val_arr  (arr, 1, addr_arr);
	set_val_strc (arr, 2, nm_ip_config_get_gateway (cfg4));
	set_val_arr  (arr, 3, route_arr);
	set_val_arr  (arr, 4, dns_arr);
	set_val_arr  (arr, 5, domain_arr);
	set_val_arr  (arr, 6, wins_arr);
	g_ptr_array_add (nmc->output_data, arr);

	print_data (nmc); /* Print all data */

	/* Remove any previous data */
	nmc_empty_output_fields (nmc);

	return TRUE;
}
/*
 * Recursively print (a portion of) the fdt.  The depth parameter
 * determines how deeply nested the fdt is printed.
 */
static int fdt_print(const char *pathp, char *prop, int depth)
{
	static char tabs[MAX_LEVEL+1] =
		"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"
		"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
	const void *nodep;	/* property node pointer */
	int  nodeoffset;	/* node offset from libfdt */
	int  nextoffset;	/* next node offset from libfdt */
	uint32_t tag;		/* tag */
	int  len;		/* length of the property */
	int  level = 0;		/* keep track of nesting level */
	const struct fdt_property *fdt_prop;

	nodeoffset = fdt_path_offset (fdt, pathp);
	if (nodeoffset < 0) {
		/*
		 * Not found or something else bad happened.
		 */
		printf ("libfdt fdt_path_offset() returned %s\n",
			fdt_strerror(nodeoffset));
		return 1;
	}
	/*
	 * The user passed in a property as well as node path.
	 * Print only the given property and then return.
	 */
	if (prop) {
		nodep = fdt_getprop (fdt, nodeoffset, prop, &len);
		if (len == 0) {
			/* no property value */
			printf("%s %s\n", pathp, prop);
			return 0;
		} else if (len > 0) {
			printf("%s=", prop);
			print_data (nodep, len);
			printf("\n");
			return 0;
		} else {
			printf ("libfdt fdt_getprop(): %s\n",
				fdt_strerror(len));
			return 1;
		}
	}

	/*
	 * The user passed in a node path and no property,
	 * print the node and all subnodes.
	 */
	while(level >= 0) {
		tag = fdt_next_tag(fdt, nodeoffset, &nextoffset);
		switch(tag) {
		case FDT_BEGIN_NODE:
			pathp = fdt_get_name(fdt, nodeoffset, NULL);
			if (level <= depth) {
				if (pathp == NULL)
					pathp = "/* NULL pointer error */";
				if (*pathp == '\0')
					pathp = "/";	/* root is nameless */
				printf("%s%s {\n",
					&tabs[MAX_LEVEL - level], pathp);
			}
			level++;
			if (level >= MAX_LEVEL) {
				printf("Nested too deep, aborting.\n");
				return 1;
			}
			break;
		case FDT_END_NODE:
			level--;
			if (level <= depth)
				printf("%s};\n", &tabs[MAX_LEVEL - level]);
			if (level == 0) {
				level = -1;		/* exit the loop */
			}
			break;
		case FDT_PROP:
			fdt_prop = fdt_offset_ptr(fdt, nodeoffset,
					sizeof(*fdt_prop));
			pathp    = fdt_string(fdt,
					fdt32_to_cpu(fdt_prop->nameoff));
			len      = fdt32_to_cpu(fdt_prop->len);
			nodep    = fdt_prop->data;
			if (len < 0) {
				printf ("libfdt fdt_getprop(): %s\n",
					fdt_strerror(len));
				return 1;
			} else if (len == 0) {
				/* the property has no value */
				if (level <= depth)
					printf("%s%s;\n",
						&tabs[MAX_LEVEL - level],
						pathp);
			} else {
				if (level <= depth) {
					printf("%s%s=",
						&tabs[MAX_LEVEL - level],
						pathp);
					print_data (nodep, len);
					printf(";\n");
				}
			}
			break;
		case FDT_NOP:
			printf("/* NOP */\n", &tabs[MAX_LEVEL - level]);
			break;
		case FDT_END:
			return 1;
		default:
			if (level <= depth)
				printf("Unknown tag 0x%08X\n", tag);
			return 1;
		}
		nodeoffset = nextoffset;
	}
	return 0;
}
Ejemplo n.º 4
0
int handle_datagram(datagram *dptr, FILE *fp, uint32_t *skips)
{
    int status = STATUS_CONTINUE;

    // Get the length of the data portion in bytes (not including the header)
    uint8_t data_length = dptr->length - sizeof(datagram);
    
    // Get the datagram type
    uint8_t type = dptr->type;

    if (*skips > 0 || dptr->data.skip_bit) {
        // Handle skipping N datagrams and the skip bit
        if (*skips > 0) {
            --(*skips);
        }
        return skip_datagram(fp, data_length);
    }

    // Make sure the version is valid
    if (dptr->version < 1 || dptr->version > 3) {
        printf("Invalid version: %u\n", dptr->version);
        return status;
    }

    // Normally, we only run things once
    int run_count = 1;

    // When the dupe bit is set, run things twice
    if (dptr->version == 2 && dptr->data.version2.dupe_bit) {
        run_count = 2;
    }

    if (dptr->version == 2 || dptr->version == 3) {
        // Skip the datagram if the checksum is invalid (ignoring the length)
        if (!valid_checksum(dptr)) {
            while (run_count--) {
                printf("Checksum is invalid!!!\n");
            }
            return status;
        }
    }

    if (dptr->length < sizeof(datagram)) {
        // Make sure the length is valid
        while (run_count--) {
            printf("Length is invalid: %u\n", dptr->length);
        }
        status = STATUS_FAIL;
    }
    else if ((type >= 0 && type <= 3) || type == 7) {
        // Handle datagram containing data
        
        // Allocate memory to read the data
        void *data = malloc(data_length);

        // Read the data from the file into the buffer
        size_t bytes_read = fread(data, 1, data_length, fp);

        if (bytes_read == data_length) {
            // Print the data read as the correct type
            while (run_count--) {
                print_data(type, data, data_length);
            }
        }
        else {
            while (run_count--) {
                printf("Read %lu/%u bytes of the datagram.\n", bytes_read, data_length);
            }
            status = STATUS_FAIL;
        }

        // Free the memory allocated for the data
        free(data);
    }
    else if (type == CONTROL_SKIP) {
        // Handle datagram containing SKIP instruction
        // Read the number of datagrams to skip from the file (store this number in skips)
        size_t bytes_read = fread(skips, 1, sizeof(*skips), fp);

        // Modify the skip value according to the run count.
        // (This doubles the skips if the dupe bit is set.)
        (*skips) *= run_count;

        // If the number could not be read, then fail
        if (bytes_read != sizeof(*skips)) {
            status = STATUS_FAIL;
        }
    }
    else if (type == CONTROL_BURN) {
        // Handle datagram containing BURN instruction
        while (run_count--) {
            status = handle_burn();
        }
    }
    else if (type == CONTROL_STOP) {
        // Handle datagram containing STOP instruction
        // Stop reading the file
        status = STATUS_STOP;
    }
    else if (type == TYPE_JUNK) {
        // Handle datagram containing junk data
        // Skip junk data
        status = skip_datagram(fp, data_length);
    }
    else {
        // Handle datagram with unrecognized type value
        printf("Unknown datagram type: %u\n", type);
        status = STATUS_FAIL;
    }

    return status;
}
Ejemplo n.º 5
0
void print_128(uint8_t* data) {
    print_data(data, 16);
}
Ejemplo n.º 6
0
int gmx_traj(int argc,char *argv[])
{
  static char *desc[] = {
    "g_traj plots coordinates, velocities, forces and/or the box.",
    "With [TT]-com[tt] the coordinates, velocities and forces are",
    "calculated for the center of mass of each group.",
    "When [TT]-mol[tt] is set, the numbers in the index file are",
    "interpreted as molecule numbers and the same procedure as with",
    "[TT]-com[tt] is used for each molecule.[PAR]",
    "Option [TT]-ot[tt] plots the temperature of each group,",
    "provided velocities are present in the trajectory file.",
    "No corrections are made for constrained degrees of freedom!",
    "This implies [TT]-com[tt].[PAR]",
    "Options [TT]-ekt[tt] and [TT]-ekr[tt] plot the translational and",
    "rotational kinetic energy of each group,", 
    "provided velocities are present in the trajectory file.",
    "This implies [TT]-com[tt].[PAR]",
    "Options [TT]-cv[tt] and [TT]-cf[tt] write the average velocities",
    "and average forces as temperature factors to a pdb file with",
    "the average coordinates. The temperature factors are scaled such",
    "that the maximum is 10. The scaling can be changed with the option",
    "[TT]-scale[tt]. To get the velocities or forces of one",
    "frame set both [TT]-b[tt] and [TT]-e[tt] to the time of",
    "desired frame. When averaging over frames you might need to use",
    "the [TT]-nojump[tt] option to obtain the correct average coordinates.",
    "If you select either of these option the average force and velocity",
    "for each atom are written to an xvg file as well",
    "(specified with [TT]-av[tt] or [TT]-af[tt]).[PAR]",
    "Option [TT]-vd[tt] computes a velocity distribution, i.e. the",
    "norm of the vector is plotted. In addition in the same graph",
    "the kinetic energy distribution is given."
  };
  static bool bMol=FALSE,bCom=FALSE,bNoJump=FALSE;
  static bool bX=TRUE,bY=TRUE,bZ=TRUE,bNorm=FALSE;
  static int  ngroups=1;
  static real scale=0,binwidth=1;
  t_pargs pa[] = {
    { "-com", FALSE, etBOOL, {&bCom},
      "Plot data for the com of each group" },
    { "-mol", FALSE, etBOOL, {&bMol},
      "Index contains molecule numbers iso atom numbers" },
    { "-nojump", FALSE, etBOOL, {&bNoJump},
      "Remove jumps of atoms across the box" },
    { "-x", FALSE, etBOOL, {&bX},
      "Plot X-component" },
    { "-y", FALSE, etBOOL, {&bY},
      "Plot Y-component" },
    { "-z", FALSE, etBOOL, {&bZ},
      "Plot Z-component" },
    { "-ng",       FALSE, etINT, {&ngroups},
      "Number of groups to consider" },
    { "-len", FALSE, etBOOL, {&bNorm},
      "Plot vector length" },
    { "-bin", FALSE, etREAL, {&binwidth},
      "Binwidth for velocity histogram (nm/ps)" },
    { "-scale", FALSE, etREAL, {&scale},
      "Scale factor for pdb output, 0 is autoscale" }
    
  };
  FILE       *outx=NULL,*outv=NULL,*outf=NULL,*outb=NULL,*outt=NULL;
  FILE       *outekt=NULL,*outekr=NULL;
  t_topology top;
  int        ePBC;
  real       *mass,time;
  char       title[STRLEN],*indexfn;
  t_trxframe fr,frout;
  int        flags,nvhisto=0,*vhisto=NULL;
  rvec       *xtop,*xp=NULL;
  rvec       *sumxv=NULL,*sumv=NULL,*sumxf=NULL,*sumf=NULL;
  matrix     topbox;
  int        status,status_out=-1;
  int        i,j,n;
  int        nr_xfr,nr_vfr,nr_ffr;
  char       **grpname;
  int        *isize0,*isize;
  atom_id    **index0,**index;
  atom_id    *atndx;
  t_block    *mols;
  bool       bTop,bOX,bOXT,bOV,bOF,bOB,bOT,bEKT,bEKR,bCV,bCF;
  bool       bDim[4],bDum[4],bVD;
  char       *box_leg[6] = { "XX", "YY", "ZZ", "YX", "ZX", "ZY" };

  t_filenm fnm[] = {
    { efTRX, "-f", NULL, ffREAD },
    { efTPS, NULL, NULL, ffREAD },
    { efNDX, NULL, NULL, ffOPTRD },
    { efXVG, "-ox", "coord.xvg", ffOPTWR },
    { efTRX, "-oxt","coord.xtc", ffOPTWR },
    { efXVG, "-ov", "veloc.xvg", ffOPTWR },
    { efXVG, "-of", "force.xvg", ffOPTWR },
    { efXVG, "-ob", "box.xvg",   ffOPTWR },
    { efXVG, "-ot", "temp.xvg",  ffOPTWR },
    { efXVG, "-ekt","ektrans.xvg", ffOPTWR },
    { efXVG, "-ekr","ekrot.xvg", ffOPTWR },
    { efXVG, "-vd", "veldist.xvg", ffOPTWR },
    { efPDB, "-cv", "veloc.pdb", ffOPTWR },
    { efPDB, "-cf", "force.pdb", ffOPTWR },
    { efXVG, "-av", "all_veloc.xvg", ffOPTWR },
    { efXVG, "-af", "all_force.xvg", ffOPTWR }
  };
#define NFILE asize(fnm)

  CopyRight(stderr,argv[0]);
  parse_common_args(&argc,argv,
		    PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW | PCA_BE_NICE,
		    NFILE,fnm,asize(pa),pa,asize(desc),desc,0,NULL);

  if (bMol)
    fprintf(stderr,"Interpreting indexfile entries as molecules.\n"
	    "Using center of mass.\n");
  
  bOX  = opt2bSet("-ox",NFILE,fnm);
  bOXT = opt2bSet("-oxt",NFILE,fnm);
  bOV  = opt2bSet("-ov",NFILE,fnm);
  bOF  = opt2bSet("-of",NFILE,fnm);
  bOB  = opt2bSet("-ob",NFILE,fnm);
  bOT  = opt2bSet("-ot",NFILE,fnm);
  bEKT = opt2bSet("-ekt",NFILE,fnm);
  bEKR = opt2bSet("-ekr",NFILE,fnm);
  bCV  = opt2bSet("-cv",NFILE,fnm) || opt2bSet("-av",NFILE,fnm);
  bCF  = opt2bSet("-cf",NFILE,fnm) || opt2bSet("-af",NFILE,fnm);
  bVD  = opt2bSet("-vd",NFILE,fnm) || opt2parg_bSet("-bin",asize(pa),pa);
  if (bMol || bOT || bEKT || bEKR)
    bCom = TRUE;

  bDim[XX] = bX;
  bDim[YY] = bY;
  bDim[ZZ] = bZ;
  bDim[DIM] = bNorm;

  bTop = read_tps_conf(ftp2fn(efTPS,NFILE,fnm),title,&top,&ePBC,
		       &xtop,NULL,topbox,
		       bCom && (bOX || bOXT || bOV || bOT || bEKT || bEKR));
  sfree(xtop);
  if ((bMol || bCV || bCF) && !bTop)
    gmx_fatal(FARGS,"Need a run input file for option -mol, -cv or -cf");

  if (bMol)
    indexfn = ftp2fn(efNDX,NFILE,fnm);
  else
    indexfn = ftp2fn_null(efNDX,NFILE,fnm);

  if (!(bCom && !bMol))
    ngroups = 1;
  snew(grpname,ngroups);
  snew(isize0,ngroups);
  snew(index0,ngroups);
  get_index(&(top.atoms),indexfn,ngroups,isize0,index0,grpname);
  
  if (bMol) {
    mols=&(top.mols);
    atndx = mols->index;
    ngroups = isize0[0];
    snew(isize,ngroups);
    snew(index,ngroups);
    for (i=0; i<ngroups; i++) {
      if (index0[0][i] < 0 || index0[0][i] >= mols->nr)
	gmx_fatal(FARGS,"Molecule index (%d) is out of range (%d-%d)",
		  index0[0][i]+1,1,mols->nr);
      isize[i] = atndx[index0[0][i]+1] - atndx[index0[0][i]];
      snew(index[i],isize[i]);
      for(j=0; j<isize[i]; j++)
	index[i][j] = atndx[index0[0][i]] + j;
    }
  } else {
    isize = isize0;
    index = index0;
  }
  if (bCom) {
    snew(mass,top.atoms.nr);
    for(i=0; i<top.atoms.nr; i++)
      mass[i] = top.atoms.atom[i].m;
  } else
    mass = NULL;

  flags = 0;
  if (bOX) {
    flags = flags | TRX_READ_X;
    outx = xvgropen(opt2fn("-ox",NFILE,fnm),
		    bCom ? "Center of mass" : "Coordinate",
		    xvgr_tlabel(),"Coordinate (nm)");
    make_legend(outx,ngroups,isize0[0],index0[0],grpname,bCom,bMol,bDim);
  }
  if (bOXT) {
    flags = flags | TRX_READ_X;
    status_out = open_trx(opt2fn("-oxt",NFILE,fnm),"w");
  }
  if (bOV) {
    flags = flags | TRX_READ_V;
    outv = xvgropen(opt2fn("-ov",NFILE,fnm),
		    bCom ? "Center of mass velocity" : "Velocity",
		    xvgr_tlabel(),"Velocity (nm/ps)");
   make_legend(outv,ngroups,isize0[0],index0[0],grpname,bCom,bMol,bDim); 
  }
  if (bOF) {
    flags = flags | TRX_READ_F;
    outf = xvgropen(opt2fn("-of",NFILE,fnm),"Force",
		    xvgr_tlabel(),"Force (kJ mol\\S-1\\N nm\\S-1\\N)");
    make_legend(outf,ngroups,isize0[0],index0[0],grpname,bCom,bMol,bDim);
  }
  if (bOB) {
    outb = xvgropen(opt2fn("-ob",NFILE,fnm),"Box vector elements",
		    xvgr_tlabel(),"(nm)");
   
    xvgr_legend(outb,6,box_leg);
  }
  if (bOT) {
    bDum[XX] = FALSE;
    bDum[YY] = FALSE;
    bDum[ZZ] = FALSE;
    bDum[DIM] = TRUE;
    flags = flags | TRX_READ_V;
    outt = xvgropen(opt2fn("-ot",NFILE,fnm),"Temperature",xvgr_tlabel(),"(K)");
    make_legend(outt,ngroups,isize[0],index[0],grpname,bCom,bMol,bDum);
  }
  if (bEKT) {
    bDum[XX] = FALSE;
    bDum[YY] = FALSE;
    bDum[ZZ] = FALSE;
    bDum[DIM] = TRUE;
    flags = flags | TRX_READ_V;
    outekt = xvgropen(opt2fn("-ekt",NFILE,fnm),"Center of mass translation",
		      xvgr_tlabel(),"Energy (kJ mol\\S-1\\N)");
    make_legend(outekt,ngroups,isize[0],index[0],grpname,bCom,bMol,bDum);
  }
  if (bEKR) {
    bDum[XX] = FALSE;
    bDum[YY] = FALSE;
    bDum[ZZ] = FALSE;
    bDum[DIM] = TRUE;
    flags = flags | TRX_READ_X | TRX_READ_V;
    outekr = xvgropen(opt2fn("-ekr",NFILE,fnm),"Center of mass rotation",
		      xvgr_tlabel(),"Energy (kJ mol\\S-1\\N)");
    make_legend(outekr,ngroups,isize[0],index[0],grpname,bCom,bMol,bDum);
  }
  if (bVD)
    flags = flags | TRX_READ_V;
  if (bCV)
    flags = flags | TRX_READ_X | TRX_READ_V;
  if (bCF)
    flags = flags | TRX_READ_X | TRX_READ_F;
  if ((flags == 0) && !bOB) {
    fprintf(stderr,"Please select one or more output file options\n");
    exit(0);
  }

  read_first_frame(&status,ftp2fn(efTRX,NFILE,fnm),&fr,flags);

  if (bCV) {
    snew(sumxv,fr.natoms);
    snew(sumv,fr.natoms);
  }
  if (bCF) {
    snew(sumxf,fr.natoms);
    snew(sumf,fr.natoms);
  }
  nr_xfr = 0;
  nr_vfr = 0;
  nr_ffr = 0;
  
  do {
    time = convert_time(fr.time);

    if (fr.bX && bNoJump && fr.bBox) {
      if (xp)
	remove_jump(fr.box,fr.natoms,xp,fr.x);
      else 
	snew(xp,fr.natoms);
      for(i=0; i<fr.natoms; i++)
	copy_rvec(fr.x[i],xp[i]);
    }
    
    if (fr.bX && bCom)
      rm_pbc(&(top.idef),ePBC,fr.natoms,fr.box,fr.x,fr.x);

    if (bVD && fr.bV) 
      update_histo(isize[0],index[0],fr.v,&nvhisto,&vhisto,binwidth);
      
    if (bOX && fr.bX)
      print_data(outx,time,fr.x,mass,bCom,ngroups,isize,index,bDim);
    if (bOXT && fr.bX) {
      frout = fr;
      if (!frout.bAtoms) {
	frout.atoms  = &top.atoms;
	frout.bAtoms = TRUE;
      }
      write_trx_x(status_out,&frout,mass,bCom,ngroups,isize,index);
    }
    if (bOV && fr.bV)
      print_data(outv,time,fr.v,mass,bCom,ngroups,isize,index,bDim);
    if (bOF && fr.bF)
      print_data(outf,time,fr.f,NULL,bCom,ngroups,isize,index,bDim);
    if (bOB && fr.bBox)
      fprintf(outb,"\t%g\t%g\t%g\t%g\t%g\t%g\t%g\n",fr.time,
	      fr.box[XX][XX],fr.box[YY][YY],fr.box[ZZ][ZZ],
	      fr.box[YY][XX],fr.box[ZZ][XX],fr.box[ZZ][YY]);
    if (bOT && fr.bV) {
      fprintf(outt," %g",time);
      for(i=0; i<ngroups; i++)
	fprintf(outt,"\t%g",temp(fr.v,mass,isize[i],index[i]));
      fprintf(outt,"\n");
    }
    if (bEKT && fr.bV) {
      fprintf(outekt," %g",time);
      for(i=0; i<ngroups; i++)
	fprintf(outekt,"\t%g",ektrans(fr.v,mass,isize[i],index[i]));
      fprintf(outekt,"\n");
    }
    if (bEKR && fr.bX && fr.bV) {
      fprintf(outekr," %g",time);
      for(i=0; i<ngroups; i++)
	fprintf(outekr,"\t%g",ekrot(fr.x,fr.v,mass,isize[i],index[i]));
      fprintf(outekr,"\n");
    }
    if (bCV) {
      if (fr.bX) {
	for(i=0; i<fr.natoms; i++)
	  rvec_inc(sumxv[i],fr.x[i]);
	nr_xfr++;
      }
      if (fr.bV) {
	for(i=0; i<fr.natoms; i++)
	  rvec_inc(sumv[i],fr.v[i]);
	nr_vfr++;
      }
    }
    if (bCF) {
      if (fr.bX) {
	for(i=0; i<fr.natoms; i++)
	  rvec_inc(sumxf[i],fr.x[i]);
	nr_xfr++;
      }
      if (fr.bF) {
	for(i=0; i<fr.natoms; i++)
	  rvec_inc(sumf[i],fr.f[i]);
	nr_ffr++;
      }
    }
    
  } while(read_next_frame(status,&fr));
  

  /* clean up a bit */
  close_trj(status);
  
  if (bOX) fclose(outx);
  if (bOXT) close_trx(status_out);
  if (bOV) fclose(outv);
  if (bOF) fclose(outf);
  if (bOB) fclose(outb);
  if (bOT) fclose(outt);
  if (bEKT) fclose(outekt);
  if (bEKR) fclose(outekr);

  if (bVD)
    print_histo(opt2fn("-vd",NFILE,fnm),nvhisto,vhisto,binwidth);
    
  if ((bCV || bCF) && (nr_vfr>1 || nr_ffr>1) && !bNoJump)
    fprintf(stderr,"WARNING: More than one frame was used for option -cv or -cf\n"
	    "If atoms jump across the box you should use the -nojump option\n");

  if (bCV)
    write_pdb_bfac(opt2fn("-cv",NFILE,fnm),
		   opt2fn("-av",NFILE,fnm),"average velocity",&(top.atoms),
		   ePBC,topbox,isize[0],index[0],nr_xfr,sumxv,
		   nr_vfr,sumv,bDim,scale);
  if (bCF)
    write_pdb_bfac(opt2fn("-cf",NFILE,fnm),
		   opt2fn("-af",NFILE,fnm),"average force",&(top.atoms),
		   ePBC,topbox,isize[0],index[0],nr_xfr,sumxf,
		   nr_ffr,sumf,bDim,scale);

  /* view it */
  view_all(NFILE, fnm);
  
  thanx(stderr);
  
  return 0;
}
Ejemplo n.º 7
0
Archivo: print.c Proyecto: tomerkal/RAM
void print_mem()
{
    int i=0, j=0;
    char *ptr, name[4];

    printf("\t\t\t /* Memory printout *\\\n");
    printf("-------------------------------------------------------------------------\n");

    /*********** printing the RAM **************/

        printf("RAM:\n\n");

        for (ptr=RAM ; ptr<RAM+sizeofRam ; ptr++)
        {
            if (*ptr == '$')
                printf("$");
            else
            {
                if (*ptr == '*')
                    printf("*");
                else
                {
                    for (i=0 ; i<sizeofmapArray ; i++)
                    {
                        if (mapArray[i] != NULL)
                        {
                            if (mapArray[i]->addressInRam == ptr)
                                break;
                        }
                    }
                    ptr = print_data(i, ptr);
                }
            }
        }
        printf("\n\n");

    /************ printing the memory map *****************/

        printf("Memory map:\n\n");

        for (j=0 ; j<sizeofmapArray ; j++)
        {
            if (mapArray[j] == NULL)
                printf("*");
            else
                {
                    printf(" ");
                    for (i=0 ; i<4 ; i++)
                        printf("%c", mapArray[j]->name[i]);
                    printf(" ");
                }
        }
        printf("\n\n");

    /************************* printing the cache **************/

        printf("Cache:\n\n");

        for (ptr=cache ; ptr<cache+sizeofCache ; ptr++)
        {
            if (*ptr == '*')
                printf("*");
            else
            {
                /** print and save the name */
                for (i=0 ; i<4 ; i++)
                {
                    printf("%c", *(ptr));
                    name[i] = *(ptr);
                    ptr++;
                }

                printf("%d", *(int*)ptr); // print size
                ptr += 4;
                printf("%d", *ptr); // print dirty-bit
                ptr++;
                printf("%d", *(int*)ptr); // print LRU
                ptr += 4;

            /** search in map array for corresponding variable */
                for (i=0 ; i<sizeofmapArray ; i++)
                {
                    if (mapArray[i] != NULL)
                    {
                        if (is_name(mapArray[i]->name, name))
                            break;
                    }
                }
                ptr = print_data(i, ptr); // print data

            }
        }
        printf("\n\n");

    printf("-------------------------------------------------------------------------\n");
}
Ejemplo n.º 8
0
int main (int argc, char ** argv)
{
  volatile size_t _rts_active = 1;
  volatile size_t _ack_active = 1;


  pami_client_t client;
  pami_context_t context[2];

  char                  cl_string[] = "TEST";
  pami_result_t result = PAMI_ERROR;

  result = PAMI_Client_create (cl_string, &client, NULL, 0);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to create pami client. result = %d\n", result);
    return 1;
  }

#ifdef TEST_CROSSTALK
  size_t num = 2;
#else
  size_t num = 1;
#endif
  result = PAMI_Context_createv(client, NULL, 0, context, num);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to create pami context(s). result = %d\n", result);
    return 1;
  }

  pami_configuration_t configuration;

  configuration.name = PAMI_CLIENT_TASK_ID;
  result = PAMI_Client_query(client, &configuration, 1);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable query configuration (%d). result = %d\n", configuration.name, result);
    return 1;
  }
  pami_task_t task_id = configuration.value.intval;
  fprintf (stderr, "My task id = %d\n", task_id);

  configuration.name = PAMI_CLIENT_NUM_TASKS;
  result = PAMI_Client_query(client, &configuration, 1);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable query configuration (%d). result = %d\n", configuration.name, result);
    return 1;
  }
  size_t num_tasks = configuration.value.intval;
  fprintf (stderr, "Number of tasks = %zu\n", num_tasks);
  if (num_tasks != 2)
  {
    fprintf (stderr, "Error. This test requires 2 tasks. Number of tasks in this job: %zu\n", num_tasks);
    return 1;
  }

  pami_dispatch_hint_t options={};

#ifdef USE_SHMEM_OPTION
  options.use_shmem = PAMI_HINT_ENABLE;
  fprintf (stderr, "##########################################\n");
  fprintf (stderr, "shared memory optimizations forced ON\n");
  fprintf (stderr, "##########################################\n");
#elif defined(NO_SHMEM_OPTION)
  options.use_shmem = PAMI_HINT_DISABLE;
  fprintf (stderr, "##########################################\n");
  fprintf (stderr, "shared memory optimizations forced OFF\n");
  fprintf (stderr, "##########################################\n");
#endif

  size_t i = 0;
#ifdef TEST_CROSSTALK
  for (i=0; i<2; i++)
#endif
  {
    pami_dispatch_callback_function fn;

    fprintf (stderr, "Before PAMI_Dispatch_set(%d) .. &_rts_active = %p, _rts_active = %zu\n", DISPATCH_ID_RTS, &_rts_active, _rts_active);
    fn.p2p = dispatch_rts;
    result = PAMI_Dispatch_set (context[i],
                                DISPATCH_ID_RTS,
                                fn,
                                (void *)&_rts_active,
                                options);
    if (result != PAMI_SUCCESS)
    {
      fprintf (stderr, "Error. Unable register pami dispatch. result = %d\n", result);
      return 1;
    }

    fprintf (stderr, "Before PAMI_Dispatch_set(%d) .. &_ack_active = %p, _ack_active = %zu\n", DISPATCH_ID_ACK, &_ack_active, _ack_active);
    fn.p2p = dispatch_ack;
    result = PAMI_Dispatch_set (context[i],
                                DISPATCH_ID_ACK,
                                fn,
                                (void *)&_ack_active,
                                options);
    if (result != PAMI_SUCCESS)
    {
      fprintf (stderr, "Error. Unable register pami dispatch. result = %d\n", result);
      return 1;
    }
  }

  if (task_id == 0)
  {
    pami_send_immediate_t parameters;
#ifdef TEST_CROSSTALK
    fprintf (stdout, "PAMI_Get('simple') functional test [crosstalk]\n");
    fprintf (stdout, "\n");
    PAMI_Endpoint_create (client, 1, 1, &parameters.dest);
#else
    fprintf (stdout, "PAMI_Get('simple') functional test\n");
    fprintf (stdout, "\n");
    PAMI_Endpoint_create (client, 1, 0, &parameters.dest);
#endif


    /* Allocate some memory from the heap. */
    void * send_buffer = malloc (BUFFERSIZE);

    /* Initialize the memory for validation. */
    initialize_data ((uint32_t *)send_buffer, BUFFERSIZE, 0);
    print_data (send_buffer, BUFFERSIZE);

    /* Send an 'rts' message to the target task */
    rts_info_t rts_info;
    PAMI_Endpoint_create (client, 0, 0, &rts_info.origin);
    rts_info.bytes  = BUFFERSIZE;
    rts_info.source = send_buffer;

    parameters.dispatch        = DISPATCH_ID_RTS;
    parameters.header.iov_base = &rts_info;
    parameters.header.iov_len  = sizeof(rts_info_t);
    parameters.data.iov_base   = NULL;
    parameters.data.iov_len    = 0;
    parameters.hints           = null_send_hint;
fprintf (stderr, "Before PAMI_Send_immediate()\n");
    PAMI_Send_immediate (context[0], &parameters);

    /* wait for the 'ack' */
fprintf (stderr, "Wait for 'ack', _ack_active = %zu\n", _ack_active);
    while (_ack_active != 0)
      result = PAMI_Context_advance (context[0], 100);

    free (send_buffer);

    switch (_ack_status)
    {
      case 0:
        fprintf (stdout, "Test PASSED\n");
        break;
      case 1:
        fprintf (stdout, "Test FAILED (get error)\n");
        break;
      case 2:
        fprintf (stdout, "Test FAILED (data error)\n");
        break;
      default:
        fprintf (stdout, "Test FAILED (unknown error)\n");
        break;
    }

  }
  else if (task_id == 1)
  {
#ifdef TEST_CROSSTALK
      size_t contextid = 1;
#else
      size_t contextid = 0;
#endif

    /* wait for the 'rts' */
fprintf (stderr, "Wait for 'rts', _rts_active = %zu, contextid = %zu\n", _rts_active, contextid);
    while (_rts_active != 0)
      result = PAMI_Context_advance (context[contextid], 100);
  }
fprintf (stderr, "Test completed .. cleanup\n");

  result = PAMI_Context_destroyv(context, num);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to destroy pami context. result = %d\n", result);
    return 1;
  }

  result = PAMI_Client_destroy(&client);
  if (result != PAMI_SUCCESS)
  {
    fprintf (stderr, "Error. Unable to destroy pami client. result = %d\n", result);
    return 1;
  }

  /*fprintf (stdout, "Success (%d)\n", task_id); */

  return 0;
};
Ejemplo n.º 9
0
/*
 * Extract all the TS packets for a nominated PID to another file.
 *
 * Returns 0 if all went well, 1 if something went wrong.
 */
static int extract_pid_packets(TS_reader_p  tsreader,
                               FILE        *output,
                               uint32_t     pid_wanted,
                               int          max,
                               int          verbose,
                               int          quiet)
{
    int    err;
    int    count = 0;
    int    extracted = 0;
    int    pes_packet_len = 0;
    int    got_pes_packet_len = FALSE;
    // It doesn't make sense to start outputting data for our PID until we
    // get the start of a packet
    int    need_packet_start = TRUE;

    for (;;)
    {
        uint32_t pid;
        int      payload_unit_start_indicator;
        byte    *adapt, *payload;
        int      adapt_len, payload_len;

        if (max > 0 && count >= max)
        {
            if (!quiet) fprint_msg("Stopping after %d packets\n",max);
            break;
        }

        err = get_next_TS_packet(tsreader,&pid,
                                 &payload_unit_start_indicator,
                                 &adapt,&adapt_len,&payload,&payload_len);
        if (err == EOF)
            break;
        else if (err)
        {
            print_err("### Error reading TS packet\n");
            return 1;
        }

        count++;

        // If the packet is empty, all we can do is ignore it
        if (payload_len == 0)
            continue;

        if (pid == pid_wanted)
        {
            byte  *data;
            int    data_len;
            size_t written;

            if (verbose)
            {
                fprint_msg("%4d: TS Packet PID %04x",count,pid);
                if (payload_unit_start_indicator)
                    print_msg(" (start)");
                else if (need_packet_start)
                    print_msg(" <ignored>");
                print_msg("\n");
            }


            if (payload_unit_start_indicator)
            {
                // It's the start of a PES packet, so we need to drop the header
                int offset;

                if (need_packet_start)
                    need_packet_start = FALSE;

                pes_packet_len = (payload[4] << 8) | payload[5];
                if (verbose) fprint_msg("PES packet length %d\n",pes_packet_len);
                got_pes_packet_len = (pes_packet_len > 0);

                if (IS_H222_PES(payload))
                {
                    // It's H.222.0 - payload[8] is the PES_header_data_length,
                    // so our ES data starts that many bytes after that field
                    offset = payload[8] + 9;
                }
                else
                {
                    // We assume it's MPEG-1
                    offset = calc_mpeg1_pes_offset(payload,payload_len);
                }
                data = &payload[offset];
                data_len = payload_len-offset;
                if (verbose) print_data(TRUE,"data",data,data_len,1000);
            }
            else
            {
                // If we haven't *started* a packet, we can't use this,
                // since it will just look like random bytes when written out.
                if (need_packet_start)
                {
                    continue;
                }

                data = payload;
                data_len = payload_len;
                if (verbose) print_data(TRUE,"Data",payload,payload_len,1000);

                if (got_pes_packet_len)
                {
                    // Try not to write more data than the PES packet declares
                    if (data_len > pes_packet_len)
                    {
                        data_len = pes_packet_len;
                        if (verbose) print_data(TRUE,"Reduced data",data,data_len,1000);
                        pes_packet_len = 0;
                    }
                    else
                        pes_packet_len -= data_len;
                }
            }
            if (data_len > 0)
            {
                // Windows doesn't seem to like writing 0 bytes, so be careful...
                written = fwrite(data,data_len,1,output);
                if (written != 1)
                {
                    fprint_err("### Error writing TS packet - units written = %d\n",
                               (int)written);
                    return 1;
                }
            }
            extracted ++;
        }
    }

    if (!quiet)
        fprint_msg("Extracted %d of %d TS packet%s\n",
                   extracted,count,(count==1?"":"s"));

    // If the user has forgotten to say -pid XX, or -video/-audio,
    // and are piping the output to another program, it can be surprising
    // if there is no data!
    if (quiet && extracted == 0)
        fprint_err("### No data extracted for PID %#04x (%d)\n",
                   pid_wanted,pid_wanted);
    return 0;
}
Ejemplo n.º 10
0
/* the result array must have size SHA1_SIZE */
void sha1 (const char * data, int dsize, char * result)
{
  int i;
  if (dsize < 0) {
    printf ("error in sha1 computation; %d (%x) bytes requested\n",
            dsize, dsize);
    exit (1);
  }
  /* padding */
  unsigned int bits = dsize * 8;
  /* number of full input blocks */
  /* int input_blocks = ((dsize + SHA1_BLOCK_SIZE - 1) / SHA1_BLOCK_SIZE) - 1;*/
  int input_blocks = dsize / SHA1_BLOCK_SIZE;

  char last1 [SHA1_BLOCK_SIZE];  /* next-to-last block, has data from input */
  char last2 [SHA1_BLOCK_SIZE];  /* last block, may not be needed */
  memset (last1, 0, sizeof (last1));
  memset (last2, 0, sizeof (last2));
  /* number of bytes in last1 (< SHA1_BLOCK_SIZE), and also index of byte
   * of last1 into which to write the 0x80 which ends the data */
  int last_bytes = dsize % SHA1_BLOCK_SIZE;
  /* number of bytes left in last1 after writing any odd bytes into last1 */
  int padding = SHA1_BLOCK_SIZE - last_bytes;
  /* number of bytes processed in the main loop */
  int full_blocks_bytes = input_blocks * SHA1_BLOCK_SIZE;
  if (dsize > full_blocks_bytes)
    memcpy (last1, data + full_blocks_bytes, dsize - full_blocks_bytes);
  last1 [last_bytes] = 0x80;
  if (padding < 9)  /* we extend if padding < 9 */
    write_int (last2 + (SHA1_BLOCK_SIZE - 8), bits);
  else
    write_int (last1 + (SHA1_BLOCK_SIZE - 8), bits);
  uint160 hash;
  memcpy (hash.c, init_H1, sizeof (init_H1));
  for (i = 0; i < input_blocks; i++) {
    compute_sha1 (((uint32_t *) (data + SHA1_BLOCK_SIZE * i)), &hash, 0);
#ifdef DEBUG_PRINT
    printf ("sha1 is %08" PRIx32 " %08" PRIx32 " %08" PRIx32 " %08" PRIx32 " %08" PRIx32 "\n",
            hash.i [0], hash.i [1], hash.i [2], hash.i [3], hash.i [4]);
    print_data (hash.c, 20);
#endif /* DEBUG_PRINT */
  }
  compute_sha1 (((uint32_t *) last1), &hash, 0);
  if (padding < 9)
    compute_sha1 (((uint32_t *) last2), &hash, 0);
#ifdef DEBUG_PRINT
  printf ("final sha1 is %08" PRIx32 " %08" PRIx32 " %08" PRIx32 " %08" PRIx32 " %08" PRIx32 "\n",
          hash.i [0], hash.i [1], hash.i [2], hash.i [3], hash.i [4]);
  print_data (hash.c, 20);
#endif /* DEBUG_PRINT */

#if __BYTE_ORDER == __LITTLE_ENDIAN
  write_int32 (result     , hash.i [0]);
  write_int32 (result +  4, hash.i [1]);
  write_int32 (result +  8, hash.i [2]);
  write_int32 (result + 12, hash.i [3]);
  write_int32 (result + 16, hash.i [4]);
#else /* __BYTE_ORDER != __LITTLE_ENDIAN */
  memcpy (result, hash.c, SHA1_SIZE);
#endif /* __BYTE_ORDER == __LITTLE_ENDIAN */
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    enum {
        CAPTURE_TIMES = 1,
    };
    urg_t urg;
    urg_connection_type_t connection_type = URG_SERIAL;
    long *data = NULL;
    long time_stamp;
    int n;
    int i;

#if defined(URG_WINDOWS_OS)
    const char *device = "COM3";
#elif defined(URG_LINUX_OS)
    const char *device = "/dev/ttyACM0";
#else
#endif
    long baudrate_or_port = 115200;
    const char *ip_address = "192.168.0.10";

    // 接続タイプの切替え
    for (i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-e")) {
            connection_type = URG_ETHERNET;
            baudrate_or_port = 10940;
            device = ip_address;
        }
    }
    for (i = 1; i < argc; ++i) {
        if (!strcmp(argv[i], "-e")) {
            connection_type = URG_ETHERNET;
        }
    }

    // \~japanese 接続
    if (urg_open(&urg, connection_type, device, baudrate_or_port) < 0) {
        printf("urg_open: %s\n", urg_error(&urg));
        return 1;
    }
    data = (long *)malloc(urg_max_data_size(&urg) * 3 * sizeof(data[0]));
    if (!data) {
        perror("urg_max_index()");
        return 1;
    }

    // \~japanese データ取得
    urg_start_measurement(&urg, URG_MULTIECHO, CAPTURE_TIMES, 0);
    for (i = 0; i < CAPTURE_TIMES; ++i) {
        n = urg_get_distance(&urg, data, &time_stamp);
        if (n <= 0) {
            printf("urg_distance: %s\n", urg_error(&urg));
            free(data);
            urg_close(&urg);
            return 1;
        }
        print_data(&urg, data, n, time_stamp);
    }

    // \~japanese 切断
    free(data);
    urg_close(&urg);

#if defined(URG_MSC)
    getchar();
#endif
    return 0;
}
Ejemplo n.º 12
0
/* #define SHA512_SIZE	64 */
void sha512 (const char * input, int bytes, char * result)
{
  int i;
  if (bytes < 0) {
    printf ("error in sha computation; %d (%x) bytes requested\n",
            bytes, bytes);
    exit (1);
  }
  /* padding */
  unsigned int bits = bytes * 8;
  int input_blocks = ((bytes + 127) / 128) - 1;

  char last1 [SHA512_BLOCK_SIZE];  /* next-to-last block, has data from input */
  char last2 [SHA512_BLOCK_SIZE];  /* last block, may not be needed */
  memset (last1, 0, SHA512_BLOCK_SIZE);
  memset (last2, 0, SHA512_BLOCK_SIZE);
  int last_bytes = bytes % SHA512_BLOCK_SIZE;
  int padding = SHA512_BLOCK_SIZE - last_bytes;
  if (last_bytes > 0)
    memcpy (last1, input + (bytes - last_bytes), last_bytes);
  if (padding > 0)
    last1 [last_bytes] = 0x80;
  else
    last2 [0] = 0x80;
  /* sha512 has 16B for 2^128 bytes, my ints are 64 bits/8B long */
  if (padding < 17)  /* so we extend if padding < 17, but only write 8 bytes */
    write_int (last2 + (SHA512_BLOCK_SIZE - 8), bits);
  else
    write_int (last1 + (SHA512_BLOCK_SIZE - 8), bits);
  uint512 hash;
  memcpy (hash.c, init_H512, sizeof (init_H512));
  for (i = 0; i < input_blocks; i++) {
    compute_sha512 (((uint64_t *) (input + 128 * i)), &hash, 0);
#ifdef DEBUG_PRINT
    printf ("hash is %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 "\n",
            hash.i [0], hash.i [1], hash.i [2], hash.i [3],
            hash.i [4], hash.i [5], hash.i [6], hash.i [7]);
    print_data (hash.c, 64);
#endif /* DEBUG_PRINT */
  }
  compute_sha512 (((uint64_t *) last1), &hash, 0);
  if (padding < 17)
    compute_sha512 (((uint64_t *) last2), &hash, 0);
#ifdef DEBUG_PRINT
  printf ("final hash is %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 " %016" PRIx64 "\n",
          hash.i [0], hash.i [1], hash.i [2], hash.i [3],
          hash.i [4], hash.i [5], hash.i [6], hash.i [7]);
  print_data (hash.c, 64);
#endif /* DEBUG_PRINT */

#if __BYTE_ORDER == __LITTLE_ENDIAN
  write_int (result     , hash.i [0]);
  write_int (result +  8, hash.i [1]);
  write_int (result + 16, hash.i [2]);
  write_int (result + 24, hash.i [3]);
  write_int (result + 32, hash.i [4]);
  write_int (result + 40, hash.i [5]);
  write_int (result + 48, hash.i [6]);
  write_int (result + 56, hash.i [7]);
#else /* __BYTE_ORDER != __LITTLE_ENDIAN */
  memcpy (result, hash.c, SHA512_SIZE);
#endif /* __BYTE_ORDER == __LITTLE_ENDIAN */
}
Ejemplo n.º 13
0
/* The input strings cannot contain any \0 bytes, according to the
   spec, but our API is such that they may not be \0 terminated
   either.  Thus we keep on treating them as krb5_data objects instead
   of C strings.  */
static krb5_error_code
foreach_realm (krb5_error_code (*fn)(krb5_data *comp,void *data), void *data,
               const krb5_data *crealm, const krb5_data *srealm,
               const krb5_data *transit)
{
    char buf[MAXLEN], last[MAXLEN];
    char *p, *bufp;
    int next_lit, intermediates, l;
    krb5_data this_component;
    krb5_error_code r;
    krb5_data last_component;

    /* Invariants:
       - last_component points to last[]
       - this_component points to buf[]
       - last_component has length of last
       - this_component has length of buf when calling out
       Keep these consistent, and we should be okay.  */

    next_lit = 0;
    intermediates = 0;
    memset (buf, 0, sizeof (buf));

    this_component.data = buf;
    last_component.data = last;
    last_component.length = 0;

#define print_data(fmt,d) Tprintf((fmt,(int)(d)->length,(d)->data))
    print_data ("client realm: %.*s\n", crealm);
    print_data ("server realm: %.*s\n", srealm);
    print_data ("transit enc.: %.*s\n", transit);

    if (transit->length == 0) {
        Tprintf (("no other realms transited\n"));
        return 0;
    }

    bufp = buf;
    for (p = transit->data, l = transit->length; l; p++, l--) {
        if (next_lit) {
            *bufp++ = *p;
            if (bufp == buf+sizeof(buf))
                return KRB5KRB_AP_ERR_ILL_CR_TKT;
            next_lit = 0;
        } else if (*p == '\\') {
            next_lit = 1;
        } else if (*p == ',') {
            if (bufp != buf) {
                this_component.length = bufp - buf;
                r = maybe_join (&last_component, &this_component, sizeof(buf));
                if (r)
                    return r;
                r = (*fn) (&this_component, data);
                if (r)
                    return r;
                if (intermediates) {
                    if (p == transit->data)
                        r = process_intermediates (fn, data,
                                                   &this_component, crealm);
                    else {
                        r = process_intermediates (fn, data, &this_component,
                                                   &last_component);
                    }
                    if (r)
                        return r;
                }
                intermediates = 0;
                memcpy (last, buf, sizeof (buf));
                last_component.length = this_component.length;
                memset (buf, 0, sizeof (buf));
                bufp = buf;
            } else {
                intermediates = 1;
                if (p == transit->data) {
                    if (crealm->length >= MAXLEN)
                        return KRB5KRB_AP_ERR_ILL_CR_TKT;
                    memcpy (last, crealm->data, crealm->length);
                    last[crealm->length] = '\0';
                    last_component.length = crealm->length;
                }
            }
        } else if (*p == ' ' && bufp == buf) {
            /* This next component stands alone, even if it has a
               trailing dot or leading slash.  */
            memset (last, 0, sizeof (last));
            last_component.length = 0;
        } else {
            /* Not a special character; literal.  */
            *bufp++ = *p;
            if (bufp == buf+sizeof(buf))
                return KRB5KRB_AP_ERR_ILL_CR_TKT;
        }
    }
    /* At end.  Must be normal state.  */
    if (next_lit)
        Tprintf (("ending in next-char-literal state\n"));
    /* Process trailing element or comma.  */
    if (bufp == buf) {
        /* Trailing comma.  */
        r = process_intermediates (fn, data, &last_component, srealm);
    } else {
        /* Trailing component.  */
        this_component.length = bufp - buf;
        r = maybe_join (&last_component, &this_component, sizeof(buf));
        if (r)
            return r;
        r = (*fn) (&this_component, data);
        if (r)
            return r;
        if (intermediates)
            r = process_intermediates (fn, data, &this_component,
                                       &last_component);
    }
    if (r != 0)
        return r;
    return 0;
}
Ejemplo n.º 14
0
int 
main (int argc, char **argv)
{
  int last_argc = -1;
  gpgme_error_t err;
  gpgme_ctx_t ctx;
  gpgme_key_t key;
  gpgme_keylist_result_t result;
  gpgme_key_t keyarray[100];
  int keyidx = 0;
  gpgme_data_t out;
  gpgme_export_mode_t mode = 0;

  if (argc)
    { argc--; argv++; }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        show_usage (0);
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--extern"))
        {
          mode |= GPGME_KEYLIST_MODE_EXTERN;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        show_usage (1);
      
    }          
 
  if (!argc)
    show_usage (1);

  init_gpgme (GPGME_PROTOCOL_OpenPGP);

  err = gpgme_new (&ctx);
  fail_if_err (err);
  gpgme_set_protocol (ctx, GPGME_PROTOCOL_OpenPGP);

  /* Lookup the keys.  */
  err = gpgme_op_keylist_ext_start (ctx, (const char**)argv, 0, 0);
  fail_if_err (err);
    
  while (!(err = gpgme_op_keylist_next (ctx, &key)))
    {
      printf ("keyid: %s  (fpr: %s)\n",
              key->subkeys?nonnull (key->subkeys->keyid):"?",
              key->subkeys?nonnull (key->subkeys->fpr):"?");

      if (keyidx < DIM (keyarray)-1)
        keyarray[keyidx++] = key;
      else
        {
          fprintf (stderr, PGM": too many keys"
                   "- skipping this key\n");
          gpgme_key_unref (key);
        }
    }
  if (gpg_err_code (err) != GPG_ERR_EOF)
    fail_if_err (err);
  err = gpgme_op_keylist_end (ctx);
  fail_if_err (err);
  keyarray[keyidx] = NULL;

  result = gpgme_op_keylist_result (ctx);
  if (result->truncated)
    {
      fprintf (stderr, PGM ": key listing unexpectedly truncated\n");
      exit (1);
    }

  /* Now for the actual export.  */
  if ((mode & GPGME_KEYLIST_MODE_EXTERN))
    printf ("sending keys to keyserver\n");

  err = gpgme_data_new (&out);
  fail_if_err (err);

  gpgme_set_armor (ctx, 1);
  err = gpgme_op_export_keys (ctx, keyarray, mode, 
                              (mode & GPGME_KEYLIST_MODE_EXTERN)? NULL:out);
  fail_if_err (err);

  fflush (NULL);
  if (!(mode & GPGME_KEYLIST_MODE_EXTERN))
    {
      fputs ("Begin Result:\n", stdout);
      print_data (out);
      fputs ("End Result.\n", stdout);
    }

  /* Cleanup.  */
  gpgme_data_release (out);

  for (keyidx=0; keyarray[keyidx]; keyidx++)
    gpgme_key_unref (keyarray[keyidx]);

  gpgme_release (ctx);
  return 0;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    int i, numprocs, rank, size, align_size, disp;
    int skip;
    double latency = 0.0, t_start = 0.0, t_stop = 0.0;
    double timer=0.0;
    double avg_time = 0.0, max_time = 0.0, min_time = 0.0; 
    char *sendbuf, *recvbuf, *s_buf1, *r_buf1;
    int *rdispls=NULL, *recvcounts=NULL;
    int max_msg_size = 1048576, full = 0;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

    if (process_args(argc, argv, rank, &max_msg_size, &full)) {
        MPI_Finalize();
        return EXIT_SUCCESS;
    }

    if(numprocs < 2) {
        if(rank == 0) {
            fprintf(stderr, "This test requires at least two processes\n");
        }

        MPI_Finalize();

        return EXIT_FAILURE;
    }

    print_header(rank, full);

    recvcounts=rdispls=NULL;
    recvcounts = (int *) malloc (numprocs*sizeof(int));
    if(NULL == recvcounts) {
        fprintf(stderr, "malloc failed.\n");
        exit(1);
    }
    
    rdispls = (int *) malloc (numprocs*sizeof(int));
    if(NULL == rdispls) {
        fprintf(stderr, "malloc failed.\n");
        exit(1);
    }

    s_buf1 = r_buf1 = NULL;

    s_buf1 = (char *) malloc(sizeof(char)*max_msg_size + MAX_ALIGNMENT);
    if(NULL == s_buf1) {
        fprintf(stderr, "malloc failed.\n");
        exit(1);
    }
    
    r_buf1 = (char *) malloc(sizeof(char)*max_msg_size * numprocs + MAX_ALIGNMENT);
    if(NULL == r_buf1) {
        fprintf(stderr, "malloc failed.\n");
        exit(1);
    }


    align_size = getpagesize();

    sendbuf = (char *)(((unsigned long) s_buf1 + (align_size - 1)) / align_size
                    * align_size);
    recvbuf = (char *)(((unsigned long) r_buf1 + (align_size - 1)) / align_size
                    * align_size);

    memset(sendbuf, 1, max_msg_size);
    memset(recvbuf, 0, max_msg_size * numprocs);

    for(size=1; size <= max_msg_size; size *= 2) {

        if(size > LARGE_MESSAGE_SIZE) {
            skip = SKIP_LARGE;
            iterations = iterations_large;
        } else {
            skip = SKIP;
            
        }

        MPI_Barrier(MPI_COMM_WORLD);

        disp =0;
        for ( i = 0; i < numprocs; i++) {
            recvcounts[i] = size;
            rdispls[i] = disp;
            disp += size;
        }

        MPI_Barrier(MPI_COMM_WORLD);       
        timer=0.0;
        for(i=0; i < iterations + skip ; i++) {

            t_start = MPI_Wtime();

            MPI_Allgatherv(sendbuf, size, MPI_CHAR, recvbuf, recvcounts, rdispls, MPI_CHAR, MPI_COMM_WORLD);
        
            t_stop = MPI_Wtime();

            if(i >= skip) {
                timer+= t_stop-t_start;
            }
            MPI_Barrier(MPI_COMM_WORLD);
 
        }
        
        MPI_Barrier(MPI_COMM_WORLD);

        latency = (double)(timer * 1e6) / iterations;

        MPI_Reduce(&latency, &min_time, 1, MPI_DOUBLE, MPI_MIN, 0, 
                MPI_COMM_WORLD); 
        MPI_Reduce(&latency, &max_time, 1, MPI_DOUBLE, MPI_MAX, 0, 
                MPI_COMM_WORLD); 
        MPI_Reduce(&latency, &avg_time, 1, MPI_DOUBLE, MPI_SUM, 0, 
                MPI_COMM_WORLD); 
        avg_time = avg_time/numprocs; 

        print_data(rank, full, size, avg_time, min_time, max_time, iterations);
        MPI_Barrier(MPI_COMM_WORLD);
    }
    
    free(s_buf1);
    free(r_buf1);

    free(recvcounts);
    free(rdispls);

    MPI_Finalize();

    return EXIT_SUCCESS;
}
Ejemplo n.º 16
0
static void log_record_print(const struct mail_transaction_header *hdr,
			     const void *data, uint64_t *modseq)
{
	unsigned int size = hdr->size - sizeof(*hdr);

	switch (hdr->type & MAIL_TRANSACTION_TYPE_MASK) {
	case MAIL_TRANSACTION_EXPUNGE|MAIL_TRANSACTION_EXPUNGE_PROT: {
		const struct mail_transaction_expunge *exp = data;

		printf(" - uids=");
		for (; size > 0; size -= sizeof(*exp), exp++) {
			printf("%u-%u,", exp->uid1, exp->uid2);
		}
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_EXPUNGE_GUID|MAIL_TRANSACTION_EXPUNGE_PROT: {
		const struct mail_transaction_expunge_guid *exp = data;

		for (; size > 0; size -= sizeof(*exp), exp++) {
			printf(" - uid=%u (guid ", exp->uid);
			print_data(exp->guid_128, sizeof(exp->guid_128));
			printf(")\n");
		}
		break;
	}
	case MAIL_TRANSACTION_APPEND: {
		const struct mail_index_record *rec = data;

		printf(" - uids=");
		for (; size > 0; size -= sizeof(*rec), rec++) {
			printf("%u", rec->uid);
			if (rec->flags != 0)
				printf(" (flags=%x)", rec->flags);
			printf(",");
		}
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_FLAG_UPDATE: {
		const struct mail_transaction_flag_update *u = data;

		for (; size > 0; size -= sizeof(*u), u++) {
			printf(" - uids=%u-%u (flags +%x-%x)\n",
			       u->uid1, u->uid2, u->add_flags, u->remove_flags);
		}
		break;
	}
	case MAIL_TRANSACTION_HEADER_UPDATE: {
		const struct mail_transaction_header_update *u = data;

		log_header_update(u);
		break;
	}
	case MAIL_TRANSACTION_EXT_INTRO: {
		const struct mail_transaction_ext_intro *intro = data;

		prev_intro = *intro;
		printf(" - ext_id = %u\n", intro->ext_id);
		printf(" - reset_id = %u\n", intro->reset_id);
		printf(" - hdr_size = %u\n", intro->hdr_size);
		printf(" - record_size = %u\n", intro->record_size);
		printf(" - record_align = %u\n", intro->record_align);
		printf(" - flags = %u\n", intro->flags);
		printf(" - name_size = %u\n", intro->name_size);
		if (intro->name_size > 0) {
			const char *name = (const char *)(intro+1);

			printf(" - name = '%.*s'\n", intro->name_size, name);
			if (*modseq == 0 && intro->name_size == 6 &&
			    memcmp(name, "modseq", 6) == 0)
				*modseq = 1;
		}
		break;
	}
	case MAIL_TRANSACTION_EXT_RESET: {
		const struct mail_transaction_ext_reset *reset = data;

		printf(" - new_reset_id = %u\n", reset->new_reset_id);
		printf(" - preserve_data = %u\n", reset->preserve_data);
		break;
	}
	case MAIL_TRANSACTION_EXT_HDR_UPDATE: {
		const struct mail_transaction_ext_hdr_update *u = data;

		printf(" - offset = %u, size = %u: ", u->offset, u->size);
		print_data(u + 1, u->size);
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_EXT_HDR_UPDATE32: {
		const struct mail_transaction_ext_hdr_update32 *u = data;

		printf(" - offset = %u, size = %u: ", u->offset, u->size);
		print_data(u + 1, u->size);
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_EXT_REC_UPDATE: {
		const struct mail_transaction_ext_rec_update *rec = data, *end;
		size_t record_size;

		end = CONST_PTR_OFFSET(data, size);
		record_size = (sizeof(*rec) + prev_intro.record_size + 3) & ~3;
		while (rec < end) {
			printf(" - uid=%u: ", rec->uid);
			print_data(rec + 1, prev_intro.record_size);
			printf("\n");
			rec = CONST_PTR_OFFSET(rec, record_size);
		}
		break;
	}
	case MAIL_TRANSACTION_EXT_ATOMIC_INC: {
		const struct mail_transaction_ext_atomic_inc *rec = data, *end;

		end = CONST_PTR_OFFSET(data, size);
		for (; rec < end; rec++) {
			printf(" - uid=%u: ", rec->uid);
			if (rec->diff > 0)
				printf("+%d\n", rec->diff);
			else
				printf("%d\n", rec->diff);
		}
		break;
	}
	case MAIL_TRANSACTION_KEYWORD_UPDATE: {
		const struct mail_transaction_keyword_update *u = data;
		const uint32_t *uid;
		unsigned int uid_offset;

		printf(" - modify=%d, name=%.*s, uids=",
		       u->modify_type, u->name_size, (const char *)(u+1));

		uid_offset = sizeof(*u) + u->name_size +
			((u->name_size % 4) == 0 ? 0 : 4 - (u->name_size%4));
		uid = (const uint32_t *)((const char *)u + uid_offset);
		size -= uid_offset;

		for (; size > 0; size -= sizeof(*uid)*2, uid += 2) {
			printf("%u-%u,", uid[0], uid[1]);
		}
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_KEYWORD_RESET: {
		const struct mail_transaction_keyword_reset *u = data;

		printf(" - uids=");
		for (; size > 0; size -= sizeof(*u), u++) {
			printf("%u-%u, ", u->uid1, u->uid2);
		}
		printf("\n");
		break;
	}
	case MAIL_TRANSACTION_MODSEQ_UPDATE: {
		const struct mail_transaction_modseq_update *rec, *end;

		end = CONST_PTR_OFFSET(data, size);
		for (rec = data; rec < end; rec++) {
			printf(" - uid=%u modseq=%llu\n", rec->uid,
			       ((unsigned long long)rec->modseq_high32 << 32) |
			       rec->modseq_low32);
		}
		break;
	}
	case MAIL_TRANSACTION_INDEX_DELETED:
	case MAIL_TRANSACTION_INDEX_UNDELETED:
		break;
	case MAIL_TRANSACTION_BOUNDARY: {
		const struct mail_transaction_boundary *rec = data;

		printf(" - size=%u\n", rec->size);
		break;
	}
	default:
		break;
	}
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
long i;
double window_sum;
LALStatus status={level:0, statusPtr: NULL};
PassBandParamStruc filterpar;
REAL4TimeSeries chan; /* must zero the f0 field */

fprintf(stderr,"make_sft_op version %s\n", MAKE_SFT_VERSION);
fprintf(stderr,"Using frame library %s\n", FrLibVersionF());
fprintf(stderr,"Using LAL version %s\n", LAL_VERSION);


yylex();

if(freq_start<0)freq_start=0;
if(freq_stop<0)freq_stop=total_samples;

/* post_init various subsystems */

post_init_response_files();
post_init_alpha_beta();

/* print settings */
print_settings(stderr);

/* start processing data */
print_data_stats();
print_data(file_debug1, "debug 1");

verify_loaded_data();

generate_fake_data();

linear_interpolate_gaps();
print_data(file_debug2, "debug 2");

/* this is a hack, but it significantly reduces memory footprint */
td_data=do_alloc(1,sizeof(*td_data));
td_data->length=total_samples;
td_data->data=data;

/* setup structure to hold input for Butterworth filter */
chan.data=NULL;
strncpy(chan.name,channel,LALNameLength);
chan.f0=0;
chan.name[LALNameLength-1]=0; /* make sure it is null-terminated */
chan.deltaT=1.0/samples_per_second;
chan.epoch.gpsSeconds=gps_start; /* no need */
chan.epoch.gpsNanoSeconds=0;

if(trace_power){
	fprintf(stderr, "Input data total power=%.*g\n",
		precision, sum_r4_squares(data, total_samples)/samples_per_second);
	}

if(!bypass_highpass_filter && (highpass_filter_f>0) && (highpass_filter_a>0)){
	fprintf(stderr,"Applying high pass filter, f=%g a=%g order=%d\n",
		highpass_filter_f, highpass_filter_a, highpass_filter_order);
	/* Setup Butterworth filter */
	filterpar.name="Butterworth High Pass";
	filterpar.nMax=highpass_filter_order;
	filterpar.f2=highpass_filter_f;
	filterpar.a2=highpass_filter_a;
	/* values that are 'not given' = out of range */
	filterpar.f1=-1.0;
	filterpar.a1=-1.0;
	
	/* REAL4Sequence is the same as REAL4Vector - according to lal/Datatypes.h */
	chan.data=(REAL4Sequence *)td_data;
	LALDButterworthREAL4TimeSeries(&status, &chan, &filterpar);
	TESTSTATUS(&status);

	if(trace_power){
		fprintf(stderr, "After highpass filter total power=%.*g\n",
			precision, sum_r4_squares(data, total_samples)/samples_per_second);
		}
	}
	
if(!bypass_lowpass_filter && (lowpass_filter_f>0) && (lowpass_filter_a > 0)){
	fprintf(stderr,"Applying low pass filter, f=%g a=%g order=%d\n",
		lowpass_filter_f, lowpass_filter_a, lowpass_filter_order);
	/* Setup Butterworth filter */
	filterpar.name="Butterworth Low Pass";
	filterpar.nMax=lowpass_filter_order;
	filterpar.f1=lowpass_filter_f;
	filterpar.a1=lowpass_filter_a;
	/* values that are 'not given' = out of range */
	/* why 2*nsamples ? LAL used to have a bug in it where
	   the pairs were sorted before deciding whether the filter 
	   is lowpass or highpass. Therefore, we need to specify a 
	   large, out of range, frequency f so that we get a low-pass filter.
	   The maximum frequency is Nyquist, hence 2*nsamples is definitely out of range */
	filterpar.f2=2*total_samples;
	filterpar.a2=-1.0;
		/* REAL4Sequence is the same as REAL4Vector - according to lal/Datatypes.h */
	chan.data=(REAL4Sequence *)td_data;
	LALDButterworthREAL4TimeSeries(&status, &chan, &filterpar);
	TESTSTATUS(&status);

	if(trace_power){
		fprintf(stderr, "After lowpass filter total power=%.*g\n",
			precision, sum_r4_squares(data, total_samples)/samples_per_second);
		}
	}

if(!bypass_first_window){
	fprintf(stderr,"Applying Hann window to input data\n");
	for(i=0;i<total_samples;i++)data[i]*=0.5*(1.0-cos((2.0*M_PI*i)/total_samples));
	window_sum=0.5;
	} else {
	window_sum=1.0;
	}

if(trace_power){
	fprintf(stderr, "After windowing total power=%.*g\n",
		precision, sum_r4_squares(data, total_samples)/samples_per_second);
	}

for(i=0;i<3;i++){
	fprintf(stderr,"Allocating phi[%ld]\n", i);
	LALCCreateVector(&status, &(phi[i]), freq_stop-freq_start);
	TESTSTATUS(&status);
	}

compute_test_fft(td_data, phi, 3, freq_start, freq_stop);

/* now free td_data to conserve space */
free(td_data->data);
data=NULL;
free(td_data);
td_data=NULL;

LALCCreateVector(&status, &pgram, freq_stop-freq_start);
TESTSTATUS(&status);

compute_calibrated_periodogram3(phi, freq_start, freq_stop, pgram, window_sum);

print_COMPLEX8Vector(pgram, output_sft, "CALIBRATED FREQUENCY DOMAIN DATA", output_mode, 0, freq_stop-freq_start);

if(output_power!=NULL){
	/* we need more space */
	for(i=0;i<3;i++){
		LALCDestroyVector(&status, &(phi[i]));
		TESTSTATUS(&status);
		}
	LALSCreateVector(&status, &power, freq_stop-freq_start);
	TESTSTATUS(&status);
	for(i=0;i<freq_stop-freq_start;i++)
		power->data[i]=(pgram->data[i].re*pgram->data[i].re+pgram->data[i].im*pgram->data[i].im);
	print_REAL4Vector(power, output_power, "CALIBRATED POWER", output_mode, 0, freq_stop-freq_start);
	}

/* we do not destroy large vectors when we are done unless we need
  to allocate a lot of space again. This reduces run time 
  of the program */
return 0;
}
Ejemplo n.º 18
0
int main(int argc, char ** argv)
{
    int i;
    int ret;
    int hw_threads;
    int sw_threads;
    int running_threads;
    int simulation_steps;
    single_pendulum_simple_state_t *data, *expected;
    int success;
    int iteration;

    timing_t t_start, t_stop;
    ms_t t_generate;
    ms_t t_calculate;
    ms_t t_check;

    // parse options
    while (1)
    {
        int c;

        static struct option long_options[] =
        {
            { "help",            no_argument, &only_print_help, 1 },
            { "without-reconos", no_argument, &without_reconos, 1 },
            { "without-memory",  no_argument, &without_memory,  1 },
            { "dont-flush",      no_argument, &dont_flush,      1 },
            { "iterations",      required_argument, 0, 'n' },
            { "iterations-in-thread", required_argument, 0, 'm' },
            {0, 0, 0, 0}
        };

        int option_index = 0;
        c = getopt_long (argc, argv, "n:m:h?", long_options, &option_index);

        if (c == -1)
            // end of options
            break;

        switch (c) {
        case 0:
            // flags are handled by getopt - nothing else to do
            break;
        case 'n':
            iterations = atoi(optarg);
            break;
        case 'm':
            iterations_in_thread = atoi(optarg);
            break;
        case 'h':
        case '?':
            only_print_help = 1;
            break;
        }
    }

#   ifdef WITHOUT_RECONOS
    without_reconos = 1;
#   endif

    verbose_progress = (iterations < 10);

    if (only_print_help || argc - optind > 2)
    {
        print_help();
        exit(-1);
    }

    hw_threads = optind < argc ? atoi(argv[optind++]) : 1;
    sw_threads = optind < argc ? atoi(argv[optind++]) : 0;

    if (iterations < 1)
    {
        fprintf(stderr, "The number of iterations must be at least 1.\n");
        exit(-1);
    }

    if (without_reconos && hw_threads > 0)
    {
        fprintf(stderr, "We cannot use hardware threads without reconOS!\n");
        exit(-1);
    }

    if (without_memory && sw_threads > 0)
    {
        fprintf(stderr, "'--without-memory' only works with hardware threads!\n");
        exit(-1);
    }

    if (sizeof(void*) > sizeof(uint32_t) && sw_threads + hw_threads > 1)
    {
        fprintf(stderr, "mboxes work with 4-byte values, so we have some trouble passing a "
            "pointer through them. We have to pass it in parts, but with more than one thread, "
            "the threads might get parts from different pointers. Therefore, you cannot use "
            "more than one thread on this platform.\n");
        exit(-1);
    }

    if (iterations_in_thread > 1) {
        if (hw_threads > 0 && hw_threads + sw_threads > 1)
        {
            fprintf(stderr, "'--iterations-in-thread' can only be used with software threads "
                "or one hardware thread.\n");
            exit(-1);
        }
    }


    running_threads = hw_threads + sw_threads;

    // We calculate one step per thread.
    simulation_steps = running_threads;

    //int gettimeofday(struct timeval *tv, struct timezone *tz);

    // init mailboxes
    mbox_init(&mb_start, simulation_steps);
    mbox_init(&mb_stop,  simulation_steps);

    // init reconos and communication resources
    if (!without_reconos)
        reconos_init();

    res[0].type = RECONOS_TYPE_MBOX;
    res[0].ptr  = &mb_start;
    res[1].type = RECONOS_TYPE_MBOX;
    res[1].ptr  = &mb_stop;

    printf("Creating %i hw-threads: ", hw_threads);
    fflush(stdout);
    for (i = 0; i < hw_threads; i++)
    {
      printf(" %i",i);fflush(stdout);
      reconos_hwt_setresources(&(hwt[i]),res,2);
      reconos_hwt_create(&(hwt[i]),i,NULL);
    }
    printf("\n");

    // init software threads
    printf("Creating %i sw-threads: ",sw_threads);
    fflush(stdout);
    for (i = 0; i < sw_threads; i++)
    {
      printf(" %i",i);fflush(stdout);
      pthread_attr_init(&swt_attr[i]);
      pthread_create(&swt[i], &swt_attr[i], software_thread, (void*)res);
    }
    printf("\n");


    //print_mmu_stats();

    // create pages and generate data
    if (!without_memory) {
        t_start = gettime();

        printf("malloc of %zu bytes...\n", BLOCK_SIZE * simulation_steps);
        data     = malloc(BLOCK_SIZE * simulation_steps);
        expected = malloc(BLOCK_SIZE * simulation_steps);
        printf("generate data ...\n");
        generate_data(data, expected, simulation_steps);

        t_stop = gettime();
        t_generate = calc_timediff_ms(t_start, t_stop);

        printf("Printing of generated data skipped. \n");
        //print_data(data, simulation_steps * sizeof(single_pendulum_simple_state_t) / sizeof(real_t));
    }


    // Start sort threads
    t_start = gettime();

    if (!verbose_progress) {
        printf("Calculating... ");
        fflush(stdout);
    }

    for (iteration=0; iteration<iterations; iteration++) {
        if (verbose_progress) {
            printf("Putting %i blocks into job queue: ", simulation_steps);
            fflush(stdout);
        }

        if (!without_reconos && !dont_flush)
            reconos_cache_flush();

        for (i=0; i<simulation_steps; i++)
        {
            if (verbose_progress) { printf(" %i",i); fflush(stdout); }

            if (iterations_in_thread > 1 && hw_threads > 0) {
                // set iterations_in_thread for hw thread
                mbox_put(&mb_start, SET_ITERATIONS);
                mbox_put(&mb_start, iterations_in_thread);
            }

            mbox_put_pointer(&mb_start, (without_memory ? WITHOUT_MEMORY : &data[i]));
        }
        if (verbose_progress) printf("\n");

        // Wait for results
        if (verbose_progress) {
            printf("Waiting for %i acknowledgements: ", simulation_steps);
            fflush(stdout);
        }
        for (i=0; i<simulation_steps; i++)
        {
            if (verbose_progress) { printf(" %i",i); fflush(stdout); }
            (void)mbox_get_pointer(&mb_stop);
        }  
        if (verbose_progress) printf("\n");
    }

    if (!verbose_progress) {
        printf("done\n");
        fflush(stdout);
    }

    t_stop = gettime();
    t_calculate = calc_timediff_ms(t_start,t_stop);

    if (!without_reconos)
        reconos_cache_flush();

    // check data
    //data[0] = 6666; // manual fault
    if (!without_memory) {
        t_start = gettime();

        printf("Checking data: ... ");
        fflush(stdout);
        ret = check_data(data, expected, simulation_steps);
        if (ret >= 0)
        {
            int job;
            printf("failure at word index %i\n", ret);
            printf("expected %5.3f    found %5.3f\n", ((real_t*)expected)[ret], ((real_t*)data)[ret]);
            job = ret / BLOCK_SIZE;
            printf("dumping job %d:\n", job);
            printf("  expected:\t"); print_data (expected[job].all, REALS_PER_BLOCK);
            printf("  actual:  \t"); print_data (data    [job].all, REALS_PER_BLOCK);
            printf("  expected:\t"); print_reals(expected[job].all, REALS_PER_BLOCK);
            printf("  actual:  \t"); print_reals(data    [job].all, REALS_PER_BLOCK);

            success = 0;
        }
        else
        {
            printf("success\n");
            //print_data(data, TO_WORDS(buffer_size));

            success = 1;
        }

        t_stop = gettime();
        t_check = calc_timediff_ms(t_start,t_stop);
    }

    // terminate all threads
    printf("Sending terminate message to %i threads:", running_threads);
    fflush(stdout);
    for (i=0; i<running_threads; i++)
    {
      printf(" %i",i);fflush(stdout);
      mbox_put_pointer(&mb_start, THREAD_EXIT);
    }
    printf("\n");

    printf("Waiting for termination...\n");
    for (i=0; i<hw_threads; i++)
    {
      pthread_join(hwt[i].delegate,NULL);
    }
    for (i=0; i<sw_threads; i++)
    {
      pthread_join(swt[i],NULL);
    }

    printf("\n");
    if (!without_reconos)
        print_mmu_stats();
    if (!without_memory) {
        printf( "Running times (size: %d jobs, %d hw-threads, %d sw-threads):\n"
            "\tGenerate data: %lu ms\n"
            "\tCalculation  : %lu ms\n"
            "\tCheck data   : %lu ms\n",
                simulation_steps, hw_threads, sw_threads,
                t_generate, t_calculate, t_check);
    } else {
        printf( "Running times (size: %d jobs, %d hw-threads, %d sw-threads):\n"
            "\tCalculation  : %lu ms\n",
                simulation_steps, hw_threads, sw_threads,
                t_calculate);
    }

    free(data);
    free(expected);

    if (!without_reconos)
        reconos_cleanup();

    if (success)
        return 0;
    else
        return 1;
}
Ejemplo n.º 19
0
R_API int r_print_format(RPrint *p, ut64 seek, const ut8* b, const int len,
		const char *fmt, int elem, const char *setval) {
	int nargs, i, j, invalid, nexti, idx, times, otimes, endian, isptr = 0;
	int (*oldprintf)(const char *str, ...);
	const char *argend = fmt+strlen (fmt);
	ut64 addr = 0, addr64 = 0, seeki = 0;;
	char *args = NULL, *bracket, tmp, last = 0;
	const char *arg = fmt;
	int viewflags = 0, flag = (elem==SEEFLAG)?1:0;
	char namefmt[8];
	static int slide=0;
	ut8 *buf;

	nexti = nargs = i = j = 0;

	if (len < 1)
		return 0;
	buf = malloc (len);
	if (!buf)
		return 0;
	memcpy (buf, b, len);
	endian = p->big_endian;

	oldprintf = NULL;
	realprintf = p->printf;

	while (*arg && iswhitechar (*arg)) arg++;

	/* get times */
	otimes = times = atoi (arg);
	if (times > 0)
		while ((*arg>='0'&&*arg<='9')) arg++;

	bracket = strchr (arg,'{');
	if (bracket) {
		char *end = strchr (arg, '}');
		if (end == NULL) {
			eprintf ("No end bracket. Try pm {ecx}b @ esi\n");
			goto beach;
		}
		*end='\0';
		times = r_num_math (NULL, bracket+1);
		arg = end + 1;
	}

	if (*arg=='\0' || *arg=='?') {
		print_format_help (p);
		goto beach;
	}

	/* get args */
	args = strchr (arg, ' ');
	if (args) {
		int l=0, maxl = 0;
		argend = args;
		args = strdup (args+1);
		nargs = r_str_word_set0 (args);
		if (nargs == 0)
			R_FREE (args);
		for (i=0; i<nargs; i++) {
			const int len = strlen (r_str_word_get0 (args, i));
			if (len > maxl)
				maxl = len;
		}
		l++;
		snprintf (namefmt, sizeof (namefmt), "%%%ds : ", maxl+6*slide%STRUCTPTR);
	}

	/* go format */
	i = 0;
	if (!times)
		otimes = times = 1;
	for (; times; times--) { // repeat N times
		const char * orig = arg;
		if (otimes>1)
			p->printf ("0x%08"PFMT64x" [%d] {\n", seek+i, otimes-times);
		arg = orig;
		for (idx=0; i<len && arg<argend && *arg; arg++) {
			int size;
			char *name = NULL;
			seeki = seek+i;
			addr = 0LL;
			invalid = 0;
			if (arg[0] == '[') {
				char *end = strchr (arg,']');
				if (end == NULL) {
					eprintf ("No end bracket.\n");
					goto beach;
				}
				*end = '\0';
				size = r_num_math (NULL, arg+1);
				arg = end + 1;
				*end = ']';
			} else {
				size = -1;
			}
			updateAddr (buf, i, endian, &addr, &addr64);

			tmp = *arg;

			if (otimes>1)
				p->printf ("   ");
#define MUSTSET (setval && elem == idx)
#define MUSTSEE (elem == -1 || elem == idx)
			if (MUSTSEE && !flag) {
				if (!(MUSTSET)) {
					if (oldprintf)
						p->printf = oldprintf;
					if (idx<nargs && tmp != 'e' && isptr == 0) {
						p->printf (namefmt, r_str_word_get0 (args, idx));
						idx++;
					}
				}
			} else {
				if (!oldprintf)
					oldprintf = p->printf;
				p->printf = nullprintf;
			}

		feed_me_again:
			switch (isptr) {
			case 1:
				{
				nexti = i + (p->bits/8);
				i = 0;
				if(tmp == '?' )seeki = addr;
				memset (buf, '\0', len);
				p->printf ("(*0x%"PFMT64x") ", addr);
				if (addr == 0) isptr = NULLPTR;
				else isptr = PTRBACK;
				if (/*addr<(b+len) && addr>=b && */p->iob.read_at) { /* The test was here to avoid segfault in the next line, 
						but len make it doesnt work... */
					p->iob.read_at (p->iob.io, (ut64)addr, buf, len-4);
					updateAddr (buf, i, endian, &addr, &addr64);
				} else {
					eprintf ("(SEGFAULT: cannot read memory at 0x%08"PFMT64x", Block: %s, blocksize: 0x%x)\n",
							addr, b, len);
					p->printf("\n");
					goto beach;
				}
				}
				break;
			case 2:
				// restore state after pointer seek
				i = nexti;
				seeki = seek+i;
				memcpy (buf, b, len);
				isptr = NOPTR;
				arg--;
				continue;
			}
			if (tmp == 0 && last != '*')
				break;

			/* skip chars */
			switch (tmp) {
			case '*': // next char is a pointer
				isptr = PTRSEEK;
				arg++;
				tmp = *arg; //last;
				goto feed_me_again;
			case '+': // toggle view flags
				viewflags = !viewflags;
				continue;
			case 'e': // tmp swap endian
				endian ^= 1;
				continue;
			case ':': // skip 4 bytes
				if (size == -1) i+=4;
				else
					while (size--) i+=4;
				continue;
			case '.': // skip 1 byte
				if (size == -1) i++;
				else
					while (size--) i++;
				continue;
			case 'p': // pointer reference
				tmp = (p->bits == 64)? 'q': 'x';
				//tmp = (sizeof (void*)==8)? 'q': 'x';
				break;
			}
			if (flag && isptr != NULLPTR) {
				if (tmp == '?') {
					char *n = strdup (r_str_word_get0 (args, idx)+1);
					char *par = strchr (n, ')');
					if (par == NULL) {
						eprintf ("No end parenthesis for struct name");
						free (n);
						goto beach;
					} else {
						*par = '.';
					}
					realprintf ("f %s_", n);
					free(n);
				} else if (slide>0 && idx==0) {
					realprintf ("%s=0x%08"PFMT64x"\n",
						r_str_word_get0 (args, idx), seeki);
				} else realprintf ("f %s=0x%08"PFMT64x"\n",
					r_str_word_get0 (args, idx) , seeki);
				idx++;
			}

			if (isptr == NULLPTR) {
				p->printf ("NULL");
				isptr = PTRBACK;
			} else
			/* cmt chars */
			switch (tmp) {
#if 0
			case 't':
				/* unix timestamp */
				D cons_printf("0x%08x = ", config.seek+i);
				{
				/* dirty hack */
				int oldfmt = last_print_format;
				ut64 old = config.seek;
				radare_seek(config.seek+i, SEEK_SET);
				radare_read(0);
				print_data(config.seek+i, "8", buf+i, 4, FMT_TIME_UNIX);
				last_print_format=oldfmt;
				radare_seek(old, SEEK_SET);
				}
				break;
#endif
			case 'e': //WTF is this? 'e' is supposed to swap endians?!
				if (size > 0)
					p->printf ("Size not yet implemented\n");
				if (MUSTSET) {
					realprintf ("?e pf e not yet supported\n");
				} else {
					double doub;
					memcpy (&doub, buf+i, sizeof (double));
					p->printf ("0x%08"PFMT64x" = (double) ", seeki);
					p->printf ("%e", doub);
					i += 8;
				}
				break;
			case 'q':
				r_print_format_quadword(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i += (size==-1) ? 8 : 8*size;
				break;
			case 'b':
				r_print_format_byte(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i+= (size==-1) ? 1 : size;
				break;
			case 'c':
				r_print_format_char (p, endian, MUSTSET,
					setval, seeki, buf, i, size);
				i+= (size==-1) ? 1 : size;
				break;
			case 'X':
				size = r_print_format_hexpairs (p, endian, MUSTSET,
					setval, seeki, buf, size);
				i += size;
				break;
			case 'T':
				if(r_print_format_10bytes(p, MUSTSET,
					setval, seeki, addr, buf) == 0)
					i += (size==-1) ? 4 : 4*size;
				break;
			case 'f':
				r_print_format_float(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i += (size==-1) ? 4 : 4*size;
				break;
			case 'i':
			case 'd':
				r_print_format_hex(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i+= (size==-1) ? 4 : 4*size;
				break;
			case 'D':
				if (size>0) p->printf ("Size not yet implemented\n");
				if (p->disasm && p->user)
					i += p->disasm (p->user, seeki);
				break;
			case 'o':
				r_print_format_octal (p, endian, MUSTSET, setval, seeki, buf, i, size);
				i+= (size==-1) ? 4 : 4*size;
				break;
			case 'x':
				r_print_format_hexflag(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i+= (size==-1) ? 4 : 4*size;
				break;
			case 'w':
			case '1': // word (16 bits)
				r_print_format_word(p, endian, MUSTSET, setval, seeki, buf, i, size);
				i+= (size==-1) ? 2 : 2*size;
				break;
			case 'z': // zero terminated string
				if (MUSTSET) {
					int buflen = strlen ((const char *)buf);
					if (buflen>seeki) {
						buflen = strlen ((const char *)buf+seeki);
					}
					if (strlen (setval) > buflen) {
						eprintf ("Warning: new string is longer than previous one \n");
					}
					realprintf ("w %s @ 0x%08"PFMT64x"\n", setval, seeki);
				} else {
					p->printf ("0x%08"PFMT64x" = ", seeki);
					for (; ((size || size==-1) && buf[i]) && i<len; i++) {
						if (IS_PRINTABLE (buf[i]))
							p->printf ("%c", buf[i]);
						else p->printf (".");
						size -= (size==-1) ? 0 : 1;
					}
				}
				if (size == -1)
					i++;
				else
					while (size--) i++;
				break;
			case 'Z': // zero terminated wide string
				if (MUSTSET) {
					if ((size = strlen(setval)) > r_wstr_clen((char*)(buf+seeki)))
						eprintf ("Warning: new string is longer than previous one\n");
					realprintf ("ww %s @ 0x%08"PFMT64x"\n", setval, seeki);
				} else {
					p->printf ("0x%08"PFMT64x" = ", seeki);
					for (; ((size || size==-1) && buf[i]) && i<len; i+=2) {
						if (IS_PRINTABLE (buf[i]))
							p->printf ("%c", buf[i]);
						else p->printf (".");
						size -= (size==-1) ? 0 : 1;
					}
				}
				if (size == -1)
					i+=2;
				else
					while (size--) i+=2;
				break;
			case 's':
				if (r_print_format_ptrstring (p, seeki, addr64, addr, 0) == 0)
					i += (size==-1) ? 4 : 4*size;
				break;
			case 'S':
				if (r_print_format_ptrstring (p, seeki, addr64, addr, 1) == 0)
					i += (size==-1) ? 8 : 8*size;
				break;
			case 'B': // resolve bitfield
				{
				char *structname, *osn;
				char *bitfield = NULL;
				structname = osn = strdup (r_str_word_get0 (args, idx-1));
				switch (size) {
				case 1: addr &= UT8_MAX; break;
				case 2: addr &= UT16_MAX; break;
				case 4: addr &= UT32_MAX; break;
				}
				if (*structname == '(') {
					name = strchr (structname, ')');
				} else {
					eprintf ("Bitfield name missing (%s)\n", structname);
					free (structname);
					goto beach;
				}
				structname++;
				if (name) *(name++) = '\0';
				else eprintf ("No ')'\n");

				if (p->get_bitfield) 
					bitfield = p->get_bitfield (p->user, structname, addr);
				if (bitfield && *bitfield) {
					p->printf (" %s (bitfield) = %s\n", name, bitfield);
				} else {
					p->printf (" %s (bitfield) = `tb %s 0x%x`\n",
						name, structname, addr);
				}
				i+= 4; //(isptr) ? 4 : s;
				free (osn);
				free (bitfield);
				}
				break;
			case 'E': // resolve enum
				{
				char *enumname, *osn;
				char *enumvalue = NULL;
				enumname = osn = strdup (r_str_word_get0 (args, idx-1));
				switch (size) {
				case 1: addr &= UT8_MAX; break;
				case 2: addr &= UT16_MAX; break;
				case 4: addr &= UT32_MAX; break;
				}
				if (*enumname == '(') {
					name = strchr (enumname, ')');
				} else {
					eprintf ("Enum name missing (%s)\n", enumname);
					free (enumname);
					goto beach;
				}
				enumname++;
				if (name) *(name++) = '\0';
				else eprintf ("No ')'\n");
				if (p->get_enumname) 
					enumvalue = p->get_enumname (p->user, enumname, addr);
				if (enumvalue && *enumvalue) {
					p->printf (" %s (enum) = 0x%"PFMT64x" ; %s\n",
						name, addr, enumvalue);
				} else {
					p->printf (" %s (enum) = `te %s 0x%x`\n",
						name, enumname, addr);
				}
				i+= (size==-1) ? 1 : size;
				free (osn);
				free (enumvalue);
				}
				break;
			case '?':
				{
				int s;
				char *structname, *osn;
				structname = osn = strdup (r_str_word_get0 (args, idx-1));
				if (*structname == '(') {
					name = strchr (structname, ')');
				} else {
					eprintf ("Struct name missing (%s)\n", structname);
					free (structname);
					goto beach;
				}
				structname++;
				if (name) *(name++) = '\0';
				else eprintf ("No ')'\n");
				p->printf ("<struct>\n");
				if (flag) slide+=STRUCTFLAG;
				slide += (isptr) ? STRUCTPTR : NESTEDSTRUCT;
				s = r_print_format_struct (p, seeki,
					buf+i, len, structname--, slide);
				i+= (isptr) ? 4 : s;
				slide -= (isptr) ? STRUCTPTR : NESTEDSTRUCT;
				if (flag) slide-=STRUCTFLAG;
				free (osn);
				break;
				}
			default:
				/* ignore unknown chars */
				invalid = 1;
				break;
			}
			if (!flag && (!MUSTSEE || MUSTSET))
				idx++;
			if (viewflags && p->offname) {
				const char *s = p->offname (p->user, seeki);
				if (s)
					p->printf ("@(%s)", s);
				s = p->offname (p->user, addr);
				if (s)
					p->printf ("*(%s)", s);
			}
			if (tmp != 'D' && !invalid && name==NULL)
				p->printf ("\n");
			last = tmp;
		}
		if (otimes>1)
			p->printf ("}\n");
		arg = orig;
	}
	if (oldprintf)
		p->printf = oldprintf;
beach:
	free (buf);
	if (args)
		free (args);
	return i;
}
Ejemplo n.º 20
0
static int cmd_socket(int argc, char *argv[])
{
    if (cmd_parameter_index(argc, argv, "new") == 1) {
        return cmd_socket_new(argc, argv);
    } else if (cmd_parameter_index(argc, argv, "print-mode") > 0) {
        if (cmd_parameter_index(argc, argv, "--string") > 0) {
            printing_mode = PRINT_STRING;
        } else if (cmd_parameter_index(argc, argv, "--hex") > 0) {
            printing_mode = PRINT_HEX;
        } else if (cmd_parameter_index(argc, argv, "--disabled") > 0) {
            printing_mode = PRINT_DISABLED;
        }
        int32_t parsed_col_width = 0;
        if (cmd_parameter_int(argc, argv, "--col-width", &parsed_col_width)) {
            if (parsed_col_width <= 0) {
                cmd_printf("Printing column width must be > 0");
                return CMDLINE_RETCODE_FAIL;
            }
            if (printing_mode == PRINT_HEX && parsed_col_width > 42) {
                cmd_printf("Maximum column width for hex data is 42 bytes");
                return CMDLINE_RETCODE_FAIL;
            }
            printing_col_width = (int)parsed_col_width;
        }
        // Allow print-mode to be used as a parameter to other commands
        if (cmd_parameter_index(argc, argv, "print-mode") == 1) {
            return CMDLINE_RETCODE_SUCCESS;
        }
    }

    // Rest of the commands require Socket
    SInfo *info = get_sinfo(strtol(argv[1], NULL, 10));
    if (!info) {
        cmd_printf("Invalid socket id %s\r\n", argv[1]);
        return CMDLINE_RETCODE_FAIL;
    }

    bool enable_pattern_check;
    if (cmd_parameter_bool(argc, argv, "set_RFC_864_pattern_check", &enable_pattern_check)) {
        info->set_pattern_check(enable_pattern_check);
        return CMDLINE_RETCODE_SUCCESS;
    }

    // Helper macro for checking the which command was given
#define COMMAND_IS(cmd) (cmd_parameter_index(argc, argv, cmd) == 2)

    /*
     * Generic Socket commands:
     * delete, open, close, bind, set_blocking, set_timeout
     */

    if (COMMAND_IS("delete")) {
        return del_sinfo(info);

    } else if (COMMAND_IS("open")) {
        NetworkInterface *interface;

        interface = get_interface(); // get default interface

        if (!interface) {
            cmd_printf("Invalid interface\r\n");
            return CMDLINE_RETCODE_FAIL;
        }

        switch (info->type()) {
            case SInfo::IP:
                return handle_nsapi_error("Socket::open()", info->internetsocket()->open(interface));
            case SInfo::TCP_SERVER:
                return handle_nsapi_error("TCPServer::open()", info->tcp_server()->open(interface));
#if defined(MBEDTLS_SSL_CLI_C)
            case SInfo::TLS:
                return handle_nsapi_error("Socket::open()", info->tls_socket()->open(interface));
#endif
            default:
                cmd_printf("Not a IP socket\r\n");
                return CMDLINE_RETCODE_FAIL;
        }
    } else if (COMMAND_IS("close")) {
        return handle_nsapi_error("Socket::close()", info->socket().close());

    } else if (COMMAND_IS("bind")) {
        int32_t port = 0;
        char *addr;

        if (!cmd_parameter_int(argc, argv, "port", &port) && !cmd_parameter_int(argc, argv, "bind", &port) && port <= 0 && port > 65535) {
            printf("Missing or invalid port number\n");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }

        if (cmd_parameter_val(argc, argv, "addr", &addr)) {
            // Replace NULL-strings with NULL
            addr = strcmp(addr, "NULL") ? addr : NULL;
            cmd_printf("Socket::bind(%s, %" PRId32 ")\r\n", addr, port);
            SocketAddress tmp(addr, port);
            return handle_nsapi_error("Socket::bind(addr, port)", info->socket().bind(tmp));
        } else {
            cmd_printf("Socket::bind(%" PRId32 ")\r\n", port);
            SocketAddress tmp(NULL, port);
            return handle_nsapi_error("Socket::bind(port)", info->socket().bind(tmp));
        }

    } else if (COMMAND_IS("set_blocking")) {
        bool val;
        if (!cmd_parameter_bool(argc, argv, "set_blocking", &val)) {
            cmd_printf("Need boolean value");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }
        info->set_blocking(val);
        return CMDLINE_RETCODE_SUCCESS;

    } else if (COMMAND_IS("set_timeout")) {
        int32_t ms;
        if (!cmd_parameter_int(argc, argv, "set_timeout", &ms)) {
            cmd_printf("Need timeout value");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }
        if (ms == -1) {
            info->set_blocking(true);
        } else {
            info->set_blocking(false);
        }

        info->socket().set_timeout(ms);
        return CMDLINE_RETCODE_SUCCESS;

    } else if (COMMAND_IS("register_sigio_cb")) {
        info->socket().sigio(callback(sigio_handler, info));
        return CMDLINE_RETCODE_SUCCESS;
    }


    /*
     * Commands related to UDPSocket:
     * sendto, recvfrom
     */
    if (COMMAND_IS("sendto")) {
        return udp_sendto_command_handler(info, argc, argv);
    } else if (COMMAND_IS("recvfrom")) {
        return udp_recvfrom_command_handler(info, argc, argv);
    } else if (COMMAND_IS("start_udp_receiver_thread")) {
        return start_udp_receiver_thread(info, argc, argv);
    } else if (COMMAND_IS("last_data_received")) {
        print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount());
        if (info->getPacketSizeArray()) {
            int *packetSizes = info->getPacketSizeArray();
            cmd_printf("packet_sizes: ");
            for (int i = 0; i < PACKET_SIZE_ARRAY_LEN; i++) {
                cmd_printf("%d ", packetSizes[i]);
            }
            cmd_printf("\r\n");
        }
        if (info->getReceiverThread()) {
            info->getReceiverThread()->terminate();
        }
        thread_clean_up(info);

        return handle_nsapi_error("Socket::last_data_received()", NSAPI_ERROR_OK);
    }

    /*
     * Commands related to TCPSocket, TLSSocket
     * connect, send, recv
     */
    if (COMMAND_IS("connect")) {
        char *host;
        int32_t port;

        if (!cmd_parameter_val(argc, argv, "connect", &host)) {
            cmd_printf("Need host name\r\n");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }
        if (!cmd_parameter_int(argc, argv, host, &port)) {
            cmd_printf("Need port number\r\n");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }
        if (strcmp(host, "NULL") == 0) {
            host = NULL;
        }

        cmd_printf("Host name: %s port: %" PRId32 "\r\n", host, port);
        if (info->type() == SInfo::IP) {
            SocketAddress addr(NULL, port);
            nsapi_error_t ret = get_interface()->gethostbyname(host, &addr);
            if (ret) {
                return handle_nsapi_error("NetworkInterface::gethostbyname()", ret);
            }
            return handle_nsapi_error("Socket::connect()", info->socket().connect(addr));
#if defined(MBEDTLS_SSL_CLI_C)
        } else if (info->type() == SInfo::TLS) {
            return handle_nsapi_error("TLSSocket::connect()", static_cast<TLSSocket &>(info->socket()).connect(host, port));
#endif
        }

    } else if (COMMAND_IS("send")) {
        return tcp_send_command_handler(info, argc, argv);

    } else if (COMMAND_IS("recv")) {
        return tcp_recv_command_handler(info, argc, argv);

    } else if (COMMAND_IS("start_tcp_receiver_thread")) {
        return start_tcp_receiver_thread(info, argc, argv);

    } else if (COMMAND_IS("join_tcp_receiver_thread")) {
        info->getReceiverThread()->join();
        print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount());
        cmd_printf("received: %d bytes\r\n", info->getRecvTotal());

        thread_clean_up(info);

        return CMDLINE_RETCODE_SUCCESS;

    } else if (COMMAND_IS("start_bg_traffic_thread")) {
        return start_bg_traffic_thread(info, argc, argv);

    } else if (COMMAND_IS("join_bg_traffic_thread")) {
        int bg_thread_success = CMDLINE_RETCODE_SUCCESS;

        if (!info->available()) { // Tells that background thread stumbled to an issue and stopped prematurely
            bg_thread_success = CMDLINE_RETCODE_FAIL;
        }

        info->setUnavailable();
        info->getReceiverThread()->join();
        thread_clean_up(info);

        return bg_thread_success;
    } else if (COMMAND_IS("setsockopt_keepalive")) {
        int32_t seconds;
        nsapi_error_t ret;
        if (!cmd_parameter_int(argc, argv, "setsockopt_keepalive", &seconds)) {
            cmd_printf("Need keep-alive value(0-7200seconds)");
            return CMDLINE_RETCODE_INVALID_PARAMETERS;
        }

        ret = info->socket().setsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &seconds, sizeof(seconds));

        return handle_nsapi_error("Socket::setsockopt()", ret);
    }  else if (COMMAND_IS("getsockopt_keepalive")) {
        int32_t optval;
        unsigned optlen = sizeof(optval);
        nsapi_error_t ret;

        ret = info->socket().getsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &optval, &optlen);

        if (optlen != sizeof(int)) {
            return CMDLINE_RETCODE_FAIL;
        }
        if (ret < 0) {
            return handle_nsapi_error("Socket::getsockopt()", ret);
        }
        return handle_nsapi_size_or_error("Socket::getsockopt()", optval);
    }

    /*
     * Commands for TCPServer
     * listen, accept
     */
    if (COMMAND_IS("listen")) {
        int32_t backlog;
        if (cmd_parameter_int(argc, argv, "listen", &backlog)) {
            return handle_nsapi_error("TCPServer::listen()", info->socket().listen(backlog));
        } else {
            return handle_nsapi_error("TCPServer::listen()", info->socket().listen());
        }

    } else if (COMMAND_IS("accept")) {
        nsapi_error_t ret;

        if (info->type() != SInfo::TCP_SERVER) {
            Socket *new_sock = info->socket().accept(&ret);
            if (ret == NSAPI_ERROR_OK) {
                SInfo *new_info = new SInfo(new_sock, false);
                m_sockets.push_back(new_info);
                cmd_printf("Socket::accept() new socket sid: %d\r\n", new_info->id());
            }
            return handle_nsapi_error("Socket::accept()", ret);
        } else { // Old TCPServer API
            int32_t id;
            SocketAddress addr;

            if (!cmd_parameter_int(argc, argv, "accept", &id)) {
                cmd_printf("Need new socket id\r\n");
                return CMDLINE_RETCODE_INVALID_PARAMETERS;
            }
            SInfo *new_info = get_sinfo(id);
            if (!new_info) {
                cmd_printf("Invalid socket id\r\n");
                return CMDLINE_RETCODE_FAIL;
            }
            TCPSocket *new_sock = static_cast<TCPSocket *>(&new_info->socket());
            nsapi_error_t ret = static_cast<TCPServer &>(info->socket()).accept(new_sock, &addr);
            if (ret == NSAPI_ERROR_OK) {
                cmd_printf("TCPServer::accept() new socket sid: %d connection from %s port %d\r\n",
                           new_info->id(), addr.get_ip_address(), addr.get_port());
            }
            return handle_nsapi_error("TCPServer::accept()", ret);
        }
    }


    /*
     * Commands for TLSSocket
     * set_root_ca_cert
     */
#if defined(MBEDTLS_SSL_CLI_C)
    if (COMMAND_IS("set_root_ca_cert")) {
        if (info->type() != SInfo::TLS) {
            cmd_printf("Not a TLS socket.\r\n");
            return CMDLINE_RETCODE_FAIL;
        }
        return handle_nsapi_error("TLSSocket::tls_set_cert", tls_set_cert(argc, argv, info));
    }
#endif

    return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
Ejemplo n.º 21
0
Archivo: list.c Proyecto: e7/analysis
int main(int argc, char *argv[])
{
#if 0
    intptr_t list = 0;
    data_t data[8];
    int i = 0;
    intptr_t iter = 0;

    for (i = 0; i < ARRAY_COUNT(data); ++i) {
        data[i].__x__ = i;
        list_add(&list, &data[i].__node__);
    }

    assert(0 == list_rm(&list, 0));
    assert(0 == list_rm(&list, 7));

    iter = list;
    while (0 != iter) {
        data_t *data = CONTAINER_OF((intptr_t *)iter, data_t, __node__);

        (void)fprintf(stderr, "%d\n", data->__x__);
        iter = *(intptr_t *)iter;
    }

    return 0;
#endif

#if 0
    intptr_t head = 0;
    intptr_t node = 0;

    (void)fprintf(stderr, "&head: %p, &node: %p\n", &head, &node);
    list_add(&head, &node);
    (void)fprintf(stderr, "head: %x, node: %x\n", head, node);
    list_remove(&head);
    (void)fprintf(stderr, "head: %x, node: %x\n", head, node);

    return 0;
#endif

#if 0
    intptr_t i = 0;
    data_t data[8];

    print_data((data_t){9, 0, {0, 0}});
    memset(data, 0, SIZE_OF(data));
    arraylist_add(&data[0].__node__, &data[2].__node__, 2);
    arraylist_add(&data[2].__node__, &data[3].__node__, 3);
    arraylist_add(&data[3].__node__, &data[7].__node__, 7);
    arraylist_del(&data[0].__node__, &data[2].__node__);
    for (i = 0; i < (intptr_t)ARRAY_COUNT(data); ++i) {
        (void)fprintf(stderr, "data[%d] : %d\n", i, data[i].__node__);
    }

    memset(data, 0, SIZE_OF(data));
    arraydlist_add(&data[0].__dnode__,
                   &data[0].__dnode__,
                   &data[0].__dnode__,
                   0);
    arraydlist_add(&data[0].__dnode__,
                   &data[0].__dnode__,
                   &data[2].__dnode__,
                   2);
    arraydlist_add(&data[0].__dnode__,
                   &data[2].__dnode__,
                   &data[3].__dnode__,
                   3);
    arraydlist_add(&data[3].__dnode__,
                   &data[2].__dnode__,
                   &data[7].__dnode__,
                   7);
    /* that's NOT right, broke the dlist
    arraydlist_add(&data[2].__dnode__,
                   &data[3].__dnode__,
                   &data[7].__dnode__,
                   7);*/

    /*arraydlist_del(&data[3].__dnode__,
                   &data[2].__dnode__,
                   &data[7].__dnode__);*/

    for (i = 0; i < (intptr_t)ARRAY_COUNT(data); ++i) {
        (void)fprintf(stderr,
                      "data[%d] : (%d, %d)\n",
                      i,
                      data[i].__dnode__.__prev__,
                      data[i].__dnode__.__next__);
    }

    return 0;
#endif

#if 1
    typedef struct {
        intptr_t a;
        intptr_t b;
    } mydata_t;

    dlist_t dlist;
    mydata_t x1 = {1, 2};
    mydata_t x2 = {3, 4};
    mydata_t x3 = {5, 6};

    (void)init_dlist(&dlist, SIZE_OF(mydata_t));
    dlist_insert(&dlist, &x2);
    dlist_insert(&dlist, &x3);
    dlist_insert(&dlist, &x1);
    for (intptr_t iter = dlist.__head__->__next__;
         iter != 0;
         iter = dlist_next(&dlist, iter))
    {
        // mydata_t *d = CONTAINER_OF(iter, mydata_t, __dnode__);
        intptr_t shell_size = dlist.__obj_size__ + SIZE_OF(arraydlist_t);

        mydata_t *d = (mydata_t *)(dlist.__cache__ + shell_size * iter);

        fprintf(stderr, "%d, %d\n", d->a, d->b);
    }
    exit_dlist(&dlist);

    return 0;
#endif
}
Ejemplo n.º 22
0
void run_blastee(char* port, unsigned long int echo)
{
    struct addrinfo hints, *res;//, *p;
    int status;
    char ipstr[INET_ADDRSTRLEN] = "0.0.0.0";
    int socketfd;
    char *buffer;
    int flag = 0;
    int sz = BUFFER_SIZE;
    struct timeval tv;
    struct sockaddr src_addr;
    socklen_t addrlen;
    int do_break = 0;
    unsigned int numpkts_rx = 0, numbytes_rx = 0;
    struct timeval tv1, tv_first, tv_end;
    char preamble[50];
    struct sockaddr_in myaddr;

    myaddr.sin_addr.s_addr=INADDR_ANY;
    myaddr.sin_family=AF_INET;
    myaddr.sin_port=htons(atoi(port));

    buffer = (char *)malloc(sizeof(char) * BUFFER_SIZE);
    if (buffer == NULL) {
        printf("Memory allocation failed\n");
        exit(1);
    }

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;

    if ((status = getaddrinfo(NULL, port, &hints, &res)) != 0) {
        printf("getaddrinfo: %s\n", gai_strerror(status));
        exit(1);
    }

    socketfd = socket(PF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0) {
        perror("Socket open failed: ");
    }

    //SPEC: exit if no packet for 5 secs
    tv.tv_sec = BLASTEE_RX_TIMEOUT;
    tv.tv_usec = 0;
    if (setsockopt(socketfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
        perror("Error");
    }

    if (setsockopt(socketfd, SOL_SOCKET, SO_SNDBUF, &sz, sizeof(sz)) < 0) {
        perror("Error");
    }

    if (bind(socketfd,(struct sockaddr *) &myaddr, sizeof(myaddr)) != 0) {
        perror("Socket binding failed");
        return;
    }

    // in case test ends without receiving any packet
    // we should print positive test runtime while
    // printing the summary stats
    gettimeofday(&tv_first, NULL);

    while(1) {
        int pktlen;
        struct sockaddr_in *sin;
        char *ipver;
        void *addr;
        struct packet_header *hdr;
        char *data;
        struct tm *tm;

        pktlen = recvfrom(socketfd, buffer, BUFFER_SIZE, flag, &src_addr, &addrlen);

        if (pktlen != -1) {
            gettimeofday(&tv1, NULL);

            numpkts_rx++;
            numbytes_rx += pktlen;

            if (numpkts_rx == 1) {
                tv_first = tv1;
            }

            sin = (struct sockaddr_in *)&src_addr;

		
            struct sockaddr_in *ipv4 = (struct sockaddr_in *) &src_addr;
            addr = &(ipv4->sin_addr);
            ipver = "IPv4";
		
            inet_ntop(sin->sin_family, addr, ipstr, sizeof(ipstr));
		
            hdr = (struct packet_header *)buffer;
            data = buffer + sizeof(struct packet_header);
            tm = localtime(&tv1.tv_sec);

            snprintf(preamble, sizeof(preamble),
                    "%s %s %d %u %d:%02d:%02d.%06ld: ",
                    ipstr, port, pktlen, ntohl(hdr->sequence), tm->tm_hour,
                    tm->tm_min, tm->tm_sec, (long int)tv1.tv_usec);
            print_data(preamble, data, ntohl(hdr->length) < 4 ?
                    ntohl(hdr->length) : 4);

            if (hdr->type == 'E'){
                numpkts_rx--;	                
                numbytes_rx -= pktlen;
                do_break = 1;
            }	
            hdr->type = 'C';
        }

        if (echo == 1 && pktlen != -1) {
            addrlen = sizeof(src_addr);
            if (sendto(socketfd, buffer, pktlen, flag, &src_addr, addrlen) == -1) {
                perror("Send Error:");
            }
        }

        //SPEC: exit if no packet for 5 secs
        if ((pktlen == -1 && errno == EAGAIN) || do_break == 1) {

            gettimeofday(&tv_end, NULL);

            print_summarystats(&tv_first, &tv_end, numpkts_rx, numbytes_rx);

            break;
        }
    }

    freeaddrinfo(res);
    free(buffer);
}
Ejemplo n.º 23
0
int gmx_traj(int argc, char *argv[])
{
    const char       *desc[] = {
        "[THISMODULE] plots coordinates, velocities, forces and/or the box.",
        "With [TT]-com[tt] the coordinates, velocities and forces are",
        "calculated for the center of mass of each group.",
        "When [TT]-mol[tt] is set, the numbers in the index file are",
        "interpreted as molecule numbers and the same procedure as with",
        "[TT]-com[tt] is used for each molecule.[PAR]",
        "Option [TT]-ot[tt] plots the temperature of each group,",
        "provided velocities are present in the trajectory file.",
        "No corrections are made for constrained degrees of freedom!",
        "This implies [TT]-com[tt].[PAR]",
        "Options [TT]-ekt[tt] and [TT]-ekr[tt] plot the translational and",
        "rotational kinetic energy of each group,",
        "provided velocities are present in the trajectory file.",
        "This implies [TT]-com[tt].[PAR]",
        "Options [TT]-cv[tt] and [TT]-cf[tt] write the average velocities",
        "and average forces as temperature factors to a [REF].pdb[ref] file with",
        "the average coordinates or the coordinates at [TT]-ctime[tt].",
        "The temperature factors are scaled such that the maximum is 10.",
        "The scaling can be changed with the option [TT]-scale[tt].",
        "To get the velocities or forces of one",
        "frame set both [TT]-b[tt] and [TT]-e[tt] to the time of",
        "desired frame. When averaging over frames you might need to use",
        "the [TT]-nojump[tt] option to obtain the correct average coordinates.",
        "If you select either of these option the average force and velocity",
        "for each atom are written to an [REF].xvg[ref] file as well",
        "(specified with [TT]-av[tt] or [TT]-af[tt]).[PAR]",
        "Option [TT]-vd[tt] computes a velocity distribution, i.e. the",
        "norm of the vector is plotted. In addition in the same graph",
        "the kinetic energy distribution is given."
    };
    static gmx_bool   bMol    = FALSE, bCom = FALSE, bPBC = TRUE, bNoJump = FALSE;
    static gmx_bool   bX      = TRUE, bY = TRUE, bZ = TRUE, bNorm = FALSE, bFP = FALSE;
    static int        ngroups = 1;
    static real       ctime   = -1, scale = 0, binwidth = 1;
    t_pargs           pa[]    = {
        { "-com", FALSE, etBOOL, {&bCom},
          "Plot data for the com of each group" },
        { "-pbc", FALSE, etBOOL, {&bPBC},
          "Make molecules whole for COM" },
        { "-mol", FALSE, etBOOL, {&bMol},
          "Index contains molecule numbers iso atom numbers" },
        { "-nojump", FALSE, etBOOL, {&bNoJump},
          "Remove jumps of atoms across the box" },
        { "-x", FALSE, etBOOL, {&bX},
          "Plot X-component" },
        { "-y", FALSE, etBOOL, {&bY},
          "Plot Y-component" },
        { "-z", FALSE, etBOOL, {&bZ},
          "Plot Z-component" },
        { "-ng",       FALSE, etINT, {&ngroups},
          "Number of groups to consider" },
        { "-len", FALSE, etBOOL, {&bNorm},
          "Plot vector length" },
        { "-fp", FALSE, etBOOL, {&bFP},
          "Full precision output" },
        { "-bin", FALSE, etREAL, {&binwidth},
          "Binwidth for velocity histogram (nm/ps)" },
        { "-ctime", FALSE, etREAL, {&ctime},
          "Use frame at this time for x in [TT]-cv[tt] and [TT]-cf[tt] instead of the average x" },
        { "-scale", FALSE, etREAL, {&scale},
          "Scale factor for [REF].pdb[ref] output, 0 is autoscale" }
    };
    FILE             *outx   = NULL, *outv = NULL, *outf = NULL, *outb = NULL, *outt = NULL;
    FILE             *outekt = NULL, *outekr = NULL;
    t_topology        top;
    int               ePBC;
    real             *mass, time;
    const char       *indexfn;
    t_trxframe        fr;
    int               flags, nvhisto = 0, *vhisto = NULL;
    rvec             *xtop, *xp = NULL;
    rvec             *sumx = NULL, *sumv = NULL, *sumf = NULL;
    matrix            topbox;
    t_trxstatus      *status;
    t_trxstatus      *status_out = NULL;
    gmx_rmpbc_t       gpbc       = NULL;
    int               i, j;
    int               nr_xfr, nr_vfr, nr_ffr;
    char            **grpname;
    int              *isize0, *isize;
    int             **index0, **index;
    int              *atndx;
    t_block          *mols;
    gmx_bool          bTop, bOX, bOXT, bOV, bOF, bOB, bOT, bEKT, bEKR, bCV, bCF;
    gmx_bool          bDim[4], bDum[4], bVD;
    char              sffmt[STRLEN], sffmt6[STRLEN];
    const char       *box_leg[6] = { "XX", "YY", "ZZ", "YX", "ZX", "ZY" };
    gmx_output_env_t *oenv;

    t_filenm          fnm[] = {
        { efTRX, "-f", NULL, ffREAD },
        { efTPS, NULL, NULL, ffREAD },
        { efNDX, NULL, NULL, ffOPTRD },
        { efXVG, "-ox",  "coord",     ffOPTWR },
        { efTRX, "-oxt", "coord",     ffOPTWR },
        { efXVG, "-ov",  "veloc",     ffOPTWR },
        { efXVG, "-of",  "force",     ffOPTWR },
        { efXVG, "-ob",  "box",       ffOPTWR },
        { efXVG, "-ot",  "temp",      ffOPTWR },
        { efXVG, "-ekt", "ektrans",   ffOPTWR },
        { efXVG, "-ekr", "ekrot",     ffOPTWR },
        { efXVG, "-vd",  "veldist",   ffOPTWR },
        { efPDB, "-cv",  "veloc",     ffOPTWR },
        { efPDB, "-cf",  "force",     ffOPTWR },
        { efXVG, "-av",  "all_veloc", ffOPTWR },
        { efXVG, "-af",  "all_force", ffOPTWR }
    };
#define NFILE asize(fnm)

    if (!parse_common_args(&argc, argv,
                           PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW,
                           NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }

    if (bMol)
    {
        fprintf(stderr, "Interpreting indexfile entries as molecules.\n"
                "Using center of mass.\n");
    }

    bOX  = opt2bSet("-ox", NFILE, fnm);
    bOXT = opt2bSet("-oxt", NFILE, fnm);
    bOV  = opt2bSet("-ov", NFILE, fnm);
    bOF  = opt2bSet("-of", NFILE, fnm);
    bOB  = opt2bSet("-ob", NFILE, fnm);
    bOT  = opt2bSet("-ot", NFILE, fnm);
    bEKT = opt2bSet("-ekt", NFILE, fnm);
    bEKR = opt2bSet("-ekr", NFILE, fnm);
    bCV  = opt2bSet("-cv", NFILE, fnm) || opt2bSet("-av", NFILE, fnm);
    bCF  = opt2bSet("-cf", NFILE, fnm) || opt2bSet("-af", NFILE, fnm);
    bVD  = opt2bSet("-vd", NFILE, fnm) || opt2parg_bSet("-bin", asize(pa), pa);
    if (bMol || bOT || bEKT || bEKR)
    {
        bCom = TRUE;
    }

    bDim[XX]  = bX;
    bDim[YY]  = bY;
    bDim[ZZ]  = bZ;
    bDim[DIM] = bNorm;

    if (bFP)
    {
        sprintf(sffmt, "\t%s", gmx_real_fullprecision_pfmt);
    }
    else
    {
        sprintf(sffmt, "\t%%g");
    }
    sprintf(sffmt6, "%s%s%s%s%s%s", sffmt, sffmt, sffmt, sffmt, sffmt, sffmt);

    bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm), &top, &ePBC,
                         &xtop, NULL, topbox,
                         bCom && (bOX || bOXT || bOV || bOT || bEKT || bEKR));
    sfree(xtop);
    if ((bMol || bCV || bCF) && !bTop)
    {
        gmx_fatal(FARGS, "Need a run input file for option -mol, -cv or -cf");
    }

    if (bMol)
    {
        indexfn = ftp2fn(efNDX, NFILE, fnm);
    }
    else
    {
        indexfn = ftp2fn_null(efNDX, NFILE, fnm);
    }

    if (!(bCom && !bMol))
    {
        ngroups = 1;
    }
    snew(grpname, ngroups);
    snew(isize0, ngroups);
    snew(index0, ngroups);
    get_index(&(top.atoms), indexfn, ngroups, isize0, index0, grpname);

    if (bMol)
    {
        mols    = &(top.mols);
        atndx   = mols->index;
        ngroups = isize0[0];
        snew(isize, ngroups);
        snew(index, ngroups);
        for (i = 0; i < ngroups; i++)
        {
            if (index0[0][i] < 0 || index0[0][i] >= mols->nr)
            {
                gmx_fatal(FARGS, "Molecule index (%d) is out of range (%d-%d)",
                          index0[0][i]+1, 1, mols->nr);
            }
            isize[i] = atndx[index0[0][i]+1] - atndx[index0[0][i]];
            snew(index[i], isize[i]);
            for (j = 0; j < isize[i]; j++)
            {
                index[i][j] = atndx[index0[0][i]] + j;
            }
        }
    }
    else
    {
        isize = isize0;
        index = index0;
    }
    if (bCom)
    {
        snew(mass, top.atoms.nr);
        for (i = 0; i < top.atoms.nr; i++)
        {
            mass[i] = top.atoms.atom[i].m;
        }
    }
    else
    {
        mass = NULL;
    }

    flags = 0;
    if (bOX)
    {
        flags = flags | TRX_READ_X;
        outx  = xvgropen(opt2fn("-ox", NFILE, fnm),
                         bCom ? "Center of mass" : "Coordinate",
                         output_env_get_xvgr_tlabel(oenv), "Coordinate (nm)", oenv);
        make_legend(outx, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOXT)
    {
        flags      = flags | TRX_READ_X;
        status_out = open_trx(opt2fn("-oxt", NFILE, fnm), "w");
    }
    if (bOV)
    {
        flags = flags | TRX_READ_V;
        outv  = xvgropen(opt2fn("-ov", NFILE, fnm),
                         bCom ? "Center of mass velocity" : "Velocity",
                         output_env_get_xvgr_tlabel(oenv), "Velocity (nm/ps)", oenv);
        make_legend(outv, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOF)
    {
        flags = flags | TRX_READ_F;
        outf  = xvgropen(opt2fn("-of", NFILE, fnm), "Force",
                         output_env_get_xvgr_tlabel(oenv), "Force (kJ mol\\S-1\\N nm\\S-1\\N)",
                         oenv);
        make_legend(outf, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv);
    }
    if (bOB)
    {
        outb = xvgropen(opt2fn("-ob", NFILE, fnm), "Box vector elements",
                        output_env_get_xvgr_tlabel(oenv), "(nm)", oenv);

        xvgr_legend(outb, 6, box_leg, oenv);
    }
    if (bOT)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_V;
        outt      = xvgropen(opt2fn("-ot", NFILE, fnm), "Temperature",
                             output_env_get_xvgr_tlabel(oenv), "(K)", oenv);
        make_legend(outt, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bEKT)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_V;
        outekt    = xvgropen(opt2fn("-ekt", NFILE, fnm), "Center of mass translation",
                             output_env_get_xvgr_tlabel(oenv), "Energy (kJ mol\\S-1\\N)", oenv);
        make_legend(outekt, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bEKR)
    {
        bDum[XX]  = FALSE;
        bDum[YY]  = FALSE;
        bDum[ZZ]  = FALSE;
        bDum[DIM] = TRUE;
        flags     = flags | TRX_READ_X | TRX_READ_V;
        outekr    = xvgropen(opt2fn("-ekr", NFILE, fnm), "Center of mass rotation",
                             output_env_get_xvgr_tlabel(oenv), "Energy (kJ mol\\S-1\\N)", oenv);
        make_legend(outekr, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv);
    }
    if (bVD)
    {
        flags = flags | TRX_READ_V;
    }
    if (bCV)
    {
        flags = flags | TRX_READ_X | TRX_READ_V;
    }
    if (bCF)
    {
        flags = flags | TRX_READ_X | TRX_READ_F;
    }
    if ((flags == 0) && !bOB)
    {
        fprintf(stderr, "Please select one or more output file options\n");
        exit(0);
    }

    read_first_frame(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &fr, flags);


    if ((bOV || bOF) && fn2ftp(ftp2fn(efTRX, NFILE, fnm)) == efXTC)
    {
        gmx_fatal(FARGS, "Cannot extract velocities or forces since your input XTC file does not contain them.");
    }

    if (bCV || bCF)
    {
        snew(sumx, fr.natoms);
    }
    if (bCV)
    {
        snew(sumv, fr.natoms);
    }
    if (bCF)
    {
        snew(sumf, fr.natoms);
    }
    nr_xfr = 0;
    nr_vfr = 0;
    nr_ffr = 0;

    if (bCom && bPBC)
    {
        gpbc = gmx_rmpbc_init(&top.idef, ePBC, fr.natoms);
    }

    do
    {
        time = output_env_conv_time(oenv, fr.time);

        if (fr.bX && bNoJump && fr.bBox)
        {
            if (xp)
            {
                remove_jump(fr.box, fr.natoms, xp, fr.x);
            }
            else
            {
                snew(xp, fr.natoms);
            }
            for (i = 0; i < fr.natoms; i++)
            {
                copy_rvec(fr.x[i], xp[i]);
            }
        }

        if (fr.bX && bCom && bPBC)
        {
            gmx_rmpbc_trxfr(gpbc, &fr);
        }

        if (bVD && fr.bV)
        {
            update_histo(isize[0], index[0], fr.v, &nvhisto, &vhisto, binwidth);
        }

        if (bOX && fr.bX)
        {
            print_data(outx, time, fr.x, mass, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOXT && fr.bX)
        {
            t_trxframe frout = fr;
            if (!frout.bAtoms)
            {
                frout.atoms  = &top.atoms;
                frout.bAtoms = TRUE;
            }
            frout.bV = FALSE;
            frout.bF = FALSE;
            write_trx_x(status_out, &frout, mass, bCom, ngroups, isize, index);
        }
        if (bOV && fr.bV)
        {
            print_data(outv, time, fr.v, mass, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOF && fr.bF)
        {
            print_data(outf, time, fr.f, NULL, bCom, ngroups, isize, index, bDim, sffmt);
        }
        if (bOB && fr.bBox)
        {
            fprintf(outb, "\t%g", fr.time);
            fprintf(outb, sffmt6,
                    fr.box[XX][XX], fr.box[YY][YY], fr.box[ZZ][ZZ],
                    fr.box[YY][XX], fr.box[ZZ][XX], fr.box[ZZ][YY]);
            fprintf(outb, "\n");
        }
        if (bOT && fr.bV)
        {
            fprintf(outt, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outt, sffmt, temp(fr.v, mass, isize[i], index[i]));
            }
            fprintf(outt, "\n");
        }
        if (bEKT && fr.bV)
        {
            fprintf(outekt, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outekt, sffmt, ektrans(fr.v, mass, isize[i], index[i]));
            }
            fprintf(outekt, "\n");
        }
        if (bEKR && fr.bX && fr.bV)
        {
            fprintf(outekr, " %g", time);
            for (i = 0; i < ngroups; i++)
            {
                fprintf(outekr, sffmt, ekrot(fr.x, fr.v, mass, isize[i], index[i]));
            }
            fprintf(outekr, "\n");
        }
        if ((bCV || bCF) && fr.bX &&
            (ctime < 0 || (fr.time >= ctime*0.999999 &&
                           fr.time <= ctime*1.000001)))
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumx[i], fr.x[i]);
            }
            nr_xfr++;
        }
        if (bCV && fr.bV)
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumv[i], fr.v[i]);
            }
            nr_vfr++;
        }
        if (bCF && fr.bF)
        {
            for (i = 0; i < fr.natoms; i++)
            {
                rvec_inc(sumf[i], fr.f[i]);
            }
            nr_ffr++;
        }

    }
    while (read_next_frame(oenv, status, &fr));

    if (gpbc != NULL)
    {
        gmx_rmpbc_done(gpbc);
    }

    /* clean up a bit */
    close_trj(status);

    if (bOX)
    {
        xvgrclose(outx);
    }
    if (bOXT)
    {
        close_trx(status_out);
    }
    if (bOV)
    {
        xvgrclose(outv);
    }
    if (bOF)
    {
        xvgrclose(outf);
    }
    if (bOB)
    {
        xvgrclose(outb);
    }
    if (bOT)
    {
        xvgrclose(outt);
    }
    if (bEKT)
    {
        xvgrclose(outekt);
    }
    if (bEKR)
    {
        xvgrclose(outekr);
    }

    if (bVD)
    {
        print_histo(opt2fn("-vd", NFILE, fnm), nvhisto, vhisto, binwidth, oenv);
    }

    if (bCV || bCF)
    {
        if (nr_xfr > 1)
        {
            if (ePBC != epbcNONE && !bNoJump)
            {
                fprintf(stderr, "\nWARNING: More than one frame was used for option -cv or -cf\n"
                        "If atoms jump across the box you should use the -nojump or -ctime option\n\n");
            }
            for (i = 0; i < isize[0]; i++)
            {
                svmul(1.0/nr_xfr, sumx[index[0][i]], sumx[index[0][i]]);
            }
        }
        else if (nr_xfr == 0)
        {
            fprintf(stderr, "\nWARNING: No coordinate frames found for option -cv or -cf\n\n");
        }
    }
    if (bCV)
    {
        write_pdb_bfac(opt2fn("-cv", NFILE, fnm),
                       opt2fn("-av", NFILE, fnm), "average velocity", &(top.atoms),
                       ePBC, topbox, isize[0], index[0], nr_xfr, sumx,
                       nr_vfr, sumv, bDim, scale, oenv);
    }
    if (bCF)
    {
        write_pdb_bfac(opt2fn("-cf", NFILE, fnm),
                       opt2fn("-af", NFILE, fnm), "average force", &(top.atoms),
                       ePBC, topbox, isize[0], index[0], nr_xfr, sumx,
                       nr_ffr, sumf, bDim, scale, oenv);
    }

    /* view it */
    view_all(oenv, NFILE, fnm);

    return 0;
}
Ejemplo n.º 24
0
int main(int argc, char* argv[])
{
    int i = 0;
    msg_type messages[4];
    unsigned num_msg = sizeof(messages) / sizeof(messages[0]);
    struct timespec timeread;
    struct timespec timedelay;
    int fd = -1;
    char* port = "/dev/can1";
    char line[1024];
    char* read = NULL;
    int linenum = 0;
    uint8_t extended = 0;
    int nmax = 0;
    int opt = 0;
    int verbose = 0;

    // parse the command-line args
    while ((opt = getopt(argc, argv, "e:n:p:v:z")) != -1)
    {
	printf ("opt = %d\n", opt);
	switch (opt)
	{
	case 'e':
	    extended = 1;
	    break;
	case 'n':
	    nmax = atoi(optarg);
	    break;
	case 'p':
	    port = strdup(optarg);
	    break;
	case 'v':
	    verbose = 1;
	    break;
	}
    }

    memset(messages, 0, sizeof(messages));
    for (i = 0; i < num_msg; ++i)
    {
	messages[i].frequency = i * 10 + 10; // 10Hz, 20Hz, 30Hz, etc...
	messages[i].period = 1000 / messages[i].frequency;
    }

    // read 10 lines of messages from stdin
    read = fgets(line, sizeof(line), stdin);
    while ((int)read != EOF && read != NULL)
    {
	char* token = strtok(line, " \t");
	int num_msg_incoming = atoi(token);
	int id;

	// check number of messages matches the number we can store
	if (num_msg_incoming != num_msg)
	{
	    fprintf(stderr, "number of messages don't match: %d, %d\n",
		    num_msg_incoming, num_msg);
	    continue;
	}

	
	for (i = 0; i < num_msg_incoming; i++)
	{
	    msg_descriptor_t* p = NULL;
	    uint64_t msg_raw = 0;
	    
	    token = strtok(NULL, " \t");
	    id = atoi(token);
	    p = &msg_descriptors[id / 100 - 1];

	    if (messages[i].id != p->identifier)
	    {
		if (messages[i].id == 0)
		    messages[i].id = p->identifier;
		else
		{
		    fprintf(stderr, "identifers don't match.");
		    continue;
		}
	    }

	    msg_raw = parse_msg_input(p, NULL, NULL);
	    messages[i].data[linenum] = msg_raw;

	    if (verbose)
	    {
		printf ("msg parsed: ");
		print_data(msg_raw);
		putchar('\n');
	    }
	}

	linenum++;
	read = fgets(line, sizeof(line), stdin);
    }

    puts("input data correctly parsed.");

    // initialize the timedelay structure
    timedelay.tv_sec = 0;
    timedelay.tv_nsec = 10000000;   /* 10 millsecs */

    // open can port
    fd = can_open(port, O_WRONLY);
    if (fd == -1)
    {
	fprintf (stderr, "error opening %s\n", port);
	exit(1);
    }
    printf ("can port opened. fd = %d\n", fd);

    // keep on sending data until someone decides to press ctrl+C
    for (;;) 
    {
	unsigned now_ms;

	clock_gettime(CLOCK_REALTIME, &timeread);
	now_ms = timeread.tv_sec * 1000 + timeread.tv_nsec / 1000000;

	for (i = 0; i < num_msg; ++i)
	{
	    // see how long it has been since that message was last sent
	    unsigned long diff = now_ms - messages[i].lastsent;

	    // if longer than period, send again
	    if (diff >= messages[i].period)
	    {
		int rand_msg = rand() % 10;
		can_write(fd, 
			  messages[i].id, 
			  0, 
			  &messages[i].data[rand_msg], // pick random
			  8);
		
		if (verbose)
		{
		    printf ("msg sent: i=%d, id=%d, msg_index=%d, data= ",
			    i, messages[i].id,
			    rand_msg);
		    print_data(messages[i].data[rand_msg]);
		    putchar('\n');
		}
		    

		messages[i].lastsent = now_ms;
	    }
	}

	// sleep for 10 ms to avoid using all the cpu
//	nanosleep(&timedelay, NULL);
    }
    
    return 0;
}