Beispiel #1
0
void my_free(void *ptr){
  byte *original_ptr = ((byte *)ptr) - EXTRA_BYTE;
  size_t size;

  if(!ptr)
    return;

  size = retreive_size(original_ptr);

  if((bcmp(original_ptr ,extra_data, EXTRA_BYTE)) && ((get_verbose_level()>=ERROR))){
    fprintf(stderr,"cannot find special string ***before*** %p!\n",ptr);
    fprintf(stderr,"memory is probably corrupted here!\n");
  }

  if((bcmp(original_ptr + size -EXTRA_BYTE ,extra_data, EXTRA_BYTE)) && ((get_verbose_level()>=ERROR))){
    fprintf(stderr,"cannot find special string ***after*** %p!\n",ptr);
    fprintf(stderr,"memory is probably corrupted here!\n");
  }

  if(get_verbose_level()>=DEBUG)
    printf("my_free freeing: %p\n",(void*)original_ptr);


  free(original_ptr);
}
Beispiel #2
0
ssize_t
recvfrom(int fd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen)
{
    ssize_t                  retval;
    static recvfrom_handle   orig_recvfrom = NULL;

    dd("calling my recvfrom");

    if ((get_mocking_type() & MOCKING_READS)
        && fd <= MAX_FD
        && polled_fds[fd]
        && !(active_fds[fd] & POLLIN))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"recvfrom\" on fd %d to "
                    "signal EAGAIN\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    init_libc_handle();

    if (orig_recvfrom == NULL) {
        orig_recvfrom = dlsym(libc_handle, "recvfrom");
        if (orig_recvfrom == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying recvfrom: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if ((get_mocking_type() & MOCKING_READS)
        && fd <= MAX_FD
        && polled_fds[fd]
        && len)
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"recvfrom\" on fd %d to read "
                    "1 byte only\n", fd);
        }

        dd("calling the original recvfrom on fd %d", fd);

        retval = (*orig_recvfrom)(fd, buf, 1, flags, src_addr, addrlen);
        active_fds[fd] &= ~POLLIN;

    } else {
        retval = (*orig_recvfrom)(fd, buf, len, flags, src_addr, addrlen);
    }

    return retval;
}
Beispiel #3
0
ssize_t
read(int fd, void *buf, size_t len)
{
    ssize_t                  retval;
    static read_handle       orig_read = NULL;

    dd("calling my read");

    if ((get_mocking_type() & MOCKING_READS)
        && fd <= MAX_FD
        && polled_fds[fd]
        && !(active_fds[fd] & (POLLIN | POLLHUP)))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"read\" on fd %d to "
                    "signal EAGAIN\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    init_libc_handle();

    if (orig_read == NULL) {
        orig_read = dlsym(libc_handle, "read");
        if (orig_read == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying read: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if ((get_mocking_type() & MOCKING_READS)
        && fd <= MAX_FD
        && polled_fds[fd]
        && len)
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"read\" on fd %d to read "
                    "1 byte only\n", fd);
        }

        dd("calling the original read on fd %d", fd);

        retval = (*orig_read)(fd, buf, 1);
        active_fds[fd] &= ~POLLIN;

    } else {
        retval = (*orig_read)(fd, buf, len);
    }

    return retval;
}
Beispiel #4
0
void my_mem_check(void){
    hash_t  *s;
    int nb_errors = 0;
    for(s=size_hash; s != NULL; s=s->hh.next) {
      if(get_verbose_level() >= ERROR) {
        printf("pointer %p of size %ld has not been freed!\n", s->key, s->size);
      }
      nb_errors ++;
    }

    if(get_verbose_level() >= INFO)
      printf ("Number of errors in managing memory: %d\n",nb_errors);
}
Beispiel #5
0
/*
  shuffle the constraints such that for each node there are more constraints on the left subtree than on the right subtree

  This is required to avoid handling permutations. On a 2:2:2:2 tree, if the
  contraints are (0,1,3), it is equivalent to (0,1,2) The canonical form is the
  second one. This help to handle the case (0,6,7,9,11,13,14,15) which are
  symetric constaints and for which the canonical form is (0,1,2,4,6,8,9,12))



  We store in *perm the way to go from the canonical form to the original constraints.
  perm is a way to go from canonical[i] to the corresponding  constraints[k]: perm[canonical[i]]=constraints[k]
 */
void canonize_constraints(tm_topology_t *topology, int *constraints, int **canonical, int n, int **perm, int *m)
{
  int *p = NULL, *c = NULL;
  int i;
  unsigned int vl = get_verbose_level();

  *m = compute_nb_leaves_from_level(0,topology);

  p = (int*) MALLOC(sizeof(int)*(*m));
  for( i = 0 ; i < *m ; i++ )
    p[i] = i;

  c = (int*) MALLOC(sizeof(int)*n);

  if(vl>=DEBUG){
    printf("constraints:");
    print_1D_tab(constraints, n);
  }

  recursive_canonicalization(0, topology, constraints, c, p, n, *m);

  if(vl>=DEBUG){
    printf("canonical:");
    print_1D_tab(c, n);
    printf("perm:");
    print_1D_tab(p, *m);
  }

  *perm = p;
  *canonical = c;
}
Beispiel #6
0
static void
init_matchbufs()
{
    const char          *p;
    int                  len;

    if (matchbufs != NULL) {
        return;
    }

    p = getenv("MOCKEAGAIN_WRITE_TIMEOUT_PATTERN");
    if (p == NULL || *p == '\0') {
        dd("write_timeout env empty");
        matchbuf_len = 0;
        return;
    }

    len = strlen(p);

    matchbufs = malloc((MAX_FD + 1) * sizeof(char *));
    if (matchbufs == NULL) {
        fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n");
        return;
    }

    memset(matchbufs, 0, (MAX_FD + 1) * sizeof(char *));
    matchbuf_len = len + 1;

    pattern = p;

    if (get_verbose_level()) {
        fprintf(stderr, "mockeagain: reading write timeout pattern: %s\n",
            pattern);
    }
}
Beispiel #7
0
int eventfd(unsigned int initval, int flags)
#endif
{
    int                         fd;
    static eventfd_handle       orig_eventfd = NULL;

    init_libc_handle();

    if (orig_eventfd == NULL) {
        orig_eventfd = dlsym(libc_handle, "eventfd");
        if (orig_eventfd == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying"
                    " eventfd: %s\n", dlerror());
            exit(1);
        }
    }

    fd = orig_eventfd(initval, flags);
    if (fd < 0) {
        return fd;
    }

    if (get_verbose_level()) {
        fprintf(stderr, "mockeagain: eventfd: blacklist fd %d\n", fd);
    }

    blacklist_fds[fd] = 1;

    return fd;
}
Beispiel #8
0
void update_comm_speed(double **comm_speed,int old_size,int new_size)
{
  double *old_tab = NULL,*new_tab= NULL;
  int i;
  unsigned int vl = get_verbose_level();

  if(vl >= DEBUG)
    printf("comm speed [%p]: ",(void *)*comm_speed);

  old_tab = *comm_speed;
  new_tab = (double*)MALLOC(sizeof(double)*new_size);
  *comm_speed = new_tab;

  for( i = 0 ; i < new_size ; i++ ){
    if( i < old_size)
      new_tab[i] = old_tab[i];
    else
      new_tab[i] = new_tab[i-1];

    if(vl >= DEBUG)
      printf("%f ",new_tab[i]);
  }
  if(vl >= DEBUG)
    printf("\n");
}
Beispiel #9
0
int signalfd(int fd, const sigset_t *mask, int flags)
{
    static signalfd_handle       orig_signalfd = NULL;

    init_libc_handle();

    if (orig_signalfd == NULL) {
        orig_signalfd = dlsym(libc_handle, "signalfd");
        if (orig_signalfd == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying"
                    " signalfd: %s\n", dlerror());
            exit(1);
        }
    }

    fd = orig_signalfd(fd, mask, flags);
    if (fd < 0) {
        return fd;
    }

    if (get_verbose_level()) {
        fprintf(stderr, "mockeagain: signalfd: blacklist fd %d\n", fd);
    }

    blacklist_fds[fd] = 1;

    return fd;
}
Beispiel #10
0
void save_size(void *ptr, size_t size) {
  hash_t *elem;
  elem = (hash_t*) malloc(sizeof(hash_t));
  elem -> key = ptr;
  elem -> size = size;
  if(get_verbose_level() >= DEBUG)
    printf("Storing (%p,%ld)\n",ptr,size);
  HASH_ADD_PTR( size_hash, key, elem );
}
Beispiel #11
0
tm_topology_t* get_local_topo_with_hwloc(void)
{
  hwloc_topology_t topology;
  tm_topology_t *res = NULL;
  hwloc_obj_t *objs = NULL;
  unsigned topodepth,depth;
  int nb_nodes,i;

  /* Build the topology */
  hwloc_topology_init(&topology);
  hwloc_topology_ignore_all_keep_structure(topology);
  hwloc_topology_load(topology);

  /* Test if symetric */
  if(!symetric(topology)){
    if(get_verbose_level() >= CRITICAL)
      fprintf(stderr,"Local toplogy not symetric!\n");
    exit(-1);
  }

  /* work on depth */
  topodepth = hwloc_topology_get_depth(topology);

  res = (tm_topology_t*)MALLOC(sizeof(tm_topology_t));
  res->nb_levels = topodepth;
  res->node_id = (int**)MALLOC(sizeof(int*)*res->nb_levels);
  res->nb_nodes = (int*)MALLOC(sizeof(int)*res->nb_levels);
  res->arity = (int*)MALLOC(sizeof(int)*res->nb_levels);

  /* Build TreeMatch topology */
  for( depth = 0 ; depth < topodepth ; depth++ ){
    nb_nodes = hwloc_get_nbobjs_by_depth(topology, depth);
    res->nb_nodes[depth] = nb_nodes;
    res->node_id[depth] = (int*)MALLOC(sizeof(int)*nb_nodes);

    objs = (hwloc_obj_t*)MALLOC(sizeof(hwloc_obj_t)*nb_nodes);
    objs[0] = hwloc_get_next_obj_by_depth(topology,depth,NULL);
    hwloc_get_closest_objs(topology,objs[0],objs+1,nb_nodes-1);
    res->arity[depth] = objs[0]->arity;

    /* printf("%d:",res->arity[depth]); */

    /* Build process id tab */
    for (i = 0; i < nb_nodes; i++){
      res->node_id[depth][i] = objs[i]->os_index;
      /* if(depth==topodepth-1) */
    }
    FREE(objs);
  }

  /* Destroy HWLOC topology object. */
  hwloc_topology_destroy(topology);

  /* printf("\n"); */
  return res;
}
Beispiel #12
0
void init_comm(char *filename,int N,double **comm)
{
  FILE *pf = NULL;
  char *ptr= NULL;
  char line[LINE_SIZE];
  int i,j;
  unsigned int vl = get_verbose_level();



  if(!(pf=fopen(filename,"r"))){
    if(vl >= CRITICAL)
      fprintf(stderr,"Cannot open %s\n",filename);
    exit(-1);
  }

  j = -1;
  i = 0;
  while(fgets(line,LINE_SIZE,pf)){
    char *l = line;
    j = 0;
    comm[i][N] = 0;
    /* printf("%s|",line); */
    while((ptr=strtok(l," \t"))){
      l = NULL;
      if((ptr[0]!='\n')&&(!isspace(ptr[0]))&&(*ptr)){
	comm[i][j] = atof(ptr);
	comm[i][N] += comm [i][j];
	/* printf ("comm[%d][%d]=%f|%s|\n",i,j,comm[i][j],ptr); */
	j++;
      }
    }
    if( j != N){
      if(vl >= CRITICAL)
	fprintf(stderr,"Error at %d %d (%d!=%d)for %s\n",i,j,j,N,filename);
      exit(-1);
    }
    i++;
  }
  if( i != N ){
    if(vl >= CRITICAL)
      fprintf(stderr,"Error at %d %d for %s\n",i,j,filename);
    exit(-1);
  }
  /*
    printf("%s:\n",filename);
  for(i=0;i<N;i++){
    for(j=0;j<N+1;j++){
      printf("%6.1f ",comm[i][j]);
    }
    printf("\n");
    }
  */

  fclose (pf);
}
Beispiel #13
0
int  build_binding_constraints(char *filename, int **ptab)
{
  int *tab = NULL;
  FILE *pf = NULL;
  char  line[LINE_SIZE],*l = NULL;
  char *ptr = NULL;
  int i,n;
  unsigned int vl = get_verbose_level();

  if (!(pf = fopen(filename,"r"))) {
    if(vl >= CRITICAL)
      fprintf(stderr,"Cannot open %s\n",filename);
    exit(-1);
  }

  /* compute the size od the array to store the constraints*/
  n = 0;
  fgets(line, LINE_SIZE, pf);
  l = line;
  while((ptr=strtok(l," \t"))){
    l = NULL;
    if((ptr[0] != '\n') && ( !isspace(ptr[0])) && (*ptr) && (ptr))
      n++;
  }

  tab = (int*)MALLOC((n+1)*sizeof(int));

  rewind(pf);
  fgets(line, LINE_SIZE, pf);
  l = line;
  i = 0;
  while((ptr=strtok(l," \t"))){
    l = NULL;
    if((ptr[0] != '\n') && ( !isspace(ptr[0])) && (*ptr) && (ptr)){
      if(i <= n)
	tab[i] = atoi(ptr);
      else{
	if(vl >= CRITICAL)
	  fprintf(stderr, "More than %d entries in %s\n", n, filename);
	exit(-1);
      }
      i++;
    }
  }

  if( i != n ){
    if(vl >= CRITICAL)
      fprintf(stderr, "Read %d entries while expecting %d ones\n", i, n);
    exit(-1);
  }

  *ptab = tab;
  fclose(pf);
  return n;
}
/*============================================================================
   mainRoutine:

   Function: Generates the polynomials, initialises and calls the sieve,
             implementing cache blocking (breaking the sieve interval into
             small blocks for the small primes.

============================================================================*/
static int mainRoutine(
  unsigned long numPrimes,
  unsigned long Mdiv2,
  unsigned long relSought,
  mpz_t n,
  mpz_t* farray,
  unsigned long multiplier)
{
    mpz_t A, B, C, D, Bdivp2, q, r, nsqrtdiv, temp, temp2, temp3, temp4;
    int i, j, l, s, fact, span, min, nfactors, verbose;
    unsigned long u1, p, reps, numRelations, M;
    unsigned long curves = 0;
    unsigned long npartials = 0;
    unsigned long relsFound = 0;
    unsigned long  * relations;
    unsigned short * primecount;
    unsigned char  * sieve;
    int            * exponents;
    unsigned long  * aind;
    unsigned long  * amodp;
    unsigned long  * Ainv;
    unsigned long  * soln1;
    unsigned long  * soln2;
    unsigned char  * flags;
    unsigned long ** Ainv2B;
    unsigned char ** offsets;
    unsigned char ** offsets2;
    mpz_t          * XArr;
    mpz_t          * Bterms;
    mpz_t          * sqrts;
    matrix_t m;

    verbose = get_verbose_level();
    s = mpz_sizeinbase(n,2)/28+1;

    New(  0, exponents, firstprime, int );
    Newz( 0, aind,          s, unsigned long );
    Newz( 0, amodp,         s, unsigned long );
    Newz( 0, Ainv,  numPrimes, unsigned long );
    Newz( 0, soln1, numPrimes, unsigned long );
    Newz( 0, soln2, numPrimes, unsigned long );
    Newz( 0, Ainv2B,        s, unsigned long*);
    Newz( 0, XArr,  relSought, mpz_t );
    New(  0, Bterms,        s, mpz_t );
    if (exponents == 0 || aind == 0 || amodp == 0 || Ainv == 0 ||
        soln1 == 0 || soln2 == 0 || Ainv2B == 0 || Bterms == 0 ||
        XArr == 0)
      croak("SIMPQS: Unable to allocate memory!\n");

    flags = 0;
    if (secondprime < numPrimes) {
      New(0, flags, numPrimes, unsigned char);
      if (flags == 0) croak("SIMPQS: Unable to allocate memory!\n");
    }
Beispiel #15
0
void *my_malloc(size_t size, char *file, int line){
  byte *ptr;
  init_extra_data();

  size+=2*EXTRA_BYTE;
  ptr = malloc(size);

  if(get_verbose_level()>=DEBUG)
    printf("my_malloc of size %ld: %p (%s: %d)\n",size-2*EXTRA_BYTE,(void*)ptr,file,line);

  save_size(ptr,size);

  memcpy(ptr, extra_data, EXTRA_BYTE);
  memcpy(ptr + size - EXTRA_BYTE, extra_data, EXTRA_BYTE);


  if(get_verbose_level()>=DEBUG)
    printf("my_malloc returning: %p\n",(void*)(ptr+EXTRA_BYTE));

  return (void *)(ptr + EXTRA_BYTE);
}
Beispiel #16
0
int nb_lines(char *filename)
{
    FILE *pf = NULL;
    char line[LINE_SIZE];
    int N = 0;

    if(!(pf = fopen(filename,"r"))){
        if(get_verbose_level() >= CRITICAL)
            fprintf(stderr,"Cannot open %s\n",filename);
        exit(-1);
    }

    while(fgets(line,LINE_SIZE,pf))
        N++;

    if(get_verbose_level() >= DEBUG)
        printf("Number of lines of file %s = %d\n",filename,N);

    fclose(pf);
    return N;
}
Beispiel #17
0
void topology_numbering(tm_topology_t *topology,int **numbering,int *nb_nodes)
{
  int nb_levels;
  unsigned int vl = get_verbose_level();

  nb_levels = topology->nb_levels;
  *nb_nodes = topology->nb_nodes[nb_levels-1];
  if(vl >= INFO)
    printf("nb_nodes=%d\n",*nb_nodes);
  *numbering = (int*)MALLOC(sizeof(int)*(*nb_nodes));
  memcpy(*numbering,topology->node_id[nb_levels-1],sizeof(int)*(*nb_nodes));
}
Beispiel #18
0
int  build_comm(char *filename,double ***pcomm)
{
  double **comm = NULL;
  int i,N;

  if(get_verbose_level() >= INFO)
    printf("Reading communication matrix file: %s\n",filename);

  N = nb_lines(filename);
  comm = (double**)MALLOC(N*sizeof(double*));
  for( i = 0 ; i < N ; i++)
    /* the last column stores the sum of the line*/
    comm[i] = (double*)MALLOC((N+1)*sizeof(double));
  init_comm(filename,N,comm);
  *pcomm = comm;

  if(get_verbose_level() >= INFO)
    printf("Communication matrix built from %s!\n",filename);

  return N;
}
Beispiel #19
0
/* Once we have found a D and q, this will find a curve and point.
 * Returns: 0 (composite), 1 (didn't work), 2 (success)
 * It's debatable what to do with a 1 return.
 */
static int find_curve(mpz_t a, mpz_t b, mpz_t x, mpz_t y,
                      long D, int poly_index, mpz_t m, mpz_t q, mpz_t N, int maxroots)
{
  long nroots, npoints, i, rooti, unity, result;
  mpz_t g, t, t2;
  mpz_t* roots = 0;

  /* TODO: A better way to do this, I believe, would be to have the root
   *       finder set up as an iterator.  That way we'd get the first root,
   *       try to find a curve, and probably we'd be done.  Only if we tried
   *       10+ points on that root would we get another root.  This would
   *       probably be set up as a stack (array) of polynomials plus one
   *       saved root (for when we solve a degree 2 poly).
   */
  /* Step 1: Get the roots of the Hilbert class polynomial. */
  nroots = find_roots(D, poly_index, N, &roots, maxroots);
  if (nroots == 0)
    return 1;

  /* Step 2: Loop selecting curves and trying points.
   *         On average it takes about 3 points, but we'll try 100+. */

  mpz_init(g);  mpz_init(t);  mpz_init(t2);
  npoints = 0;
  result = 1;
  for (rooti = 0; result == 1 && rooti < 50*nroots; rooti++) {
    /* Given this D and root, select curve a,b */
    select_curve_params(a, b, g,  D, roots, rooti % nroots, N, t);
    if (mpz_sgn(g) == 0) { result = 0; break; }

    /* See Cohen 5.3.1, page 231 */
    unity = (D == -3) ? 6 : (D == -4) ? 4 : 2;
    for (i = 0; result == 1 && i < unity; i++) {
      if (i > 0)
        update_ab(a, b, D, g, N);
      npoints++;
      select_point(x, y,  a, b, N, t, t2);
      result = ecpp_check_point(x, y, m, q, a, N, t, t2);
    }
  }
  if (npoints > 10 && get_verbose_level() > 0)
    printf("  # point finding took %ld points\n", npoints);

  if (roots != 0) {
    for (rooti = 0; rooti < nroots; rooti++)
      mpz_clear(roots[rooti]);
    Safefree(roots);
  }
  mpz_clear(g);  mpz_clear(t);  mpz_clear(t2);

  return result;
}
Beispiel #20
0
size_t retreive_size(void *someaddr){
  size_t res;
  hash_t *elem = NULL;
  HASH_FIND_PTR(size_hash, &someaddr, elem);
  if(!elem){
    fprintf(stderr,"cannot find ptr %p to free!\n",someaddr);
    return 0;
  }

  res  = elem->size;
  if(get_verbose_level()>=DEBUG)
    printf("Retreiving (%p,%ld)\n",someaddr, res);

  HASH_DEL( size_hash, elem);
  return res;
}
Beispiel #21
0
/* Once we have found a D and q, this will find a curve and point.
 * Returns: 0 (composite), 1 (didn't work), 2 (success)
 * It's debatable what to do with a 1 return.
 */
static int find_curve(mpz_t a, mpz_t b, mpz_t x, mpz_t y,
                      long D, mpz_t m, mpz_t q, mpz_t N)
{
  long nroots, npoints, i, rooti, unity, result;
  mpz_t g, t, t2;
  mpz_t* roots = 0;
  int verbose = get_verbose_level();

  /* Step 1: Get the roots of the Hilbert class polynomial. */
  nroots = find_roots(D, N, &roots);
  if (nroots == 0)
    return 1;

  /* Step 2: Loop selecting curves and trying points.
   *         On average it takes about 3 points, but we'll try 100+. */

  mpz_init(g);  mpz_init(t);  mpz_init(t2);
  npoints = 0;
  result = 1;
  for (rooti = 0; result == 1 && rooti < 50*nroots; rooti++) {
    /* Given this D and root, select curve a,b */
    select_curve_params(a, b, g,  D, roots, rooti % nroots, N, t);
    if (mpz_sgn(g) == 0) { result = 0; break; }

    /* See Cohen 5.3.1, page 231 */
    unity = (D == -3) ? 6 : (D == -4) ? 4 : 2;
    for (i = 0; result == 1 && i < unity; i++) {
      if (i > 0)
        update_ab(a, b, D, g, N);
      npoints++;
      select_point(x, y,  a, b, N, t, t2);
      result = ecpp_check_point(x, y, m, q, a, N, t, t2);
    }
  }
  if (verbose && npoints > 10)
    printf("  # point finding took %ld points\n", npoints);

  if (roots != 0) {
    for (rooti = 0; rooti < nroots; rooti++)
      mpz_clear(roots[rooti]);
    Safefree(roots);
  }
  mpz_clear(g);  mpz_clear(t);  mpz_clear(t2);

  return result;
}
Beispiel #22
0
static int find_roots(long D, int poly_index, mpz_t N, mpz_t** roots, int maxroots)
{
  mpz_t* T;
  UV degree;
  long dT, i, nroots;
  int poly_type;

  if (D == -3 || D == -4) {
    *roots = 0;
    return 1;
  }

  degree = poly_class_poly_num(poly_index, NULL, &T, &poly_type);
  if (degree == 0 || (poly_type != 1 && poly_type != 2 && poly_type != 3))
    return 0;

  dT = degree;
  polyz_mod(T, T, &dT, N);

  polyz_roots_modp(roots, &nroots, maxroots, T, dT, N);
  if (nroots == 0) {
    gmp_printf("N = %Zd\n", N);
    croak("Failed to find roots for D = %ld\n", D);
  }
  for (i = 0; i <= dT; i++)
    mpz_clear(T[i]);
  Safefree(T);
#if 0
  if (nroots != dT && get_verbose_level())
    printf("  found %ld roots of the %ld degree poly\n", nroots, dT);
#endif

  /* Convert Weber and Ramanujan roots to Hilbert roots */
  if (poly_type == 2)
    for (i = 0; i < nroots; i++)
      weber_root_to_hilbert_root((*roots)[i], N, D);
  if (poly_type == 3)
    for (i = 0; i < nroots; i++)
      ramanujan_root_to_hilbert_root((*roots)[i], N, D);

  return nroots;
}
Beispiel #23
0
static int find_roots(long D, mpz_t N, mpz_t** roots)
{
  mpz_t* T;
  UV degree;
  long dT, i, nroots;
  int poly_type;
  gmp_randstate_t* p_randstate = get_randstate();

  if (D == -3 || D == -4) {
    *roots = 0;
    return 1;
  }

  degree = poly_class_poly(D, &T, &poly_type);
  if (degree == 0 || (poly_type != 1 && poly_type != 2))
    return 0;

  dT = degree;
  polyz_mod(T, T, &dT, N);

  /* Don't bother getting more than 4 roots */
  polyz_roots_modp(roots, &nroots,  4, T, dT, N, p_randstate);
  if (nroots == 0) {
    gmp_printf("N = %Zd\n", N);
    croak("Failed to find roots for D = %ld\n", D);
  }
  for (i = 0; i <= dT; i++)
    mpz_clear(T[i]);
  Safefree(T);
#if 0
  if (nroots != dT && get_verbose_level())
    printf("  found %ld roots of the %ld degree poly\n", nroots, dT);
#endif

  /* Convert Weber roots to Hilbert roots */
  if (poly_type == 2)
    for (i = 0; i < nroots; i++)
      weber_root_to_hilbert_root((*roots)[i], N, D);

  return nroots;
}
Beispiel #24
0
void   build_synthetic_proc_id(tm_topology_t *topology)
{
  int i;
  size_t j,n = 1;

  topology->node_id = (int**)MALLOC(sizeof(int*)*topology->nb_levels);
  topology->nb_nodes = (int*)MALLOC(sizeof(int)*topology->nb_levels);

  for( i = 0 ; i < topology->nb_levels ; i++ ){
    /* printf("n= %lld, arity := %d\n",n, topology->arity[i]); */
    topology->nb_nodes[i] = n;
    topology->node_id[i] = (int*)MALLOC(sizeof(long int)*n);
    if ( !topology->node_id[i] ){
      if(get_verbose_level() >= CRITICAL)
	fprintf(stderr,"Cannot allocate level %d (of size %ld) of the topology\n", i, (unsigned long int)n);
      exit(-1);
    }
    for( j = 0 ; j < n ; j++ )
      topology->node_id[i][j] = j;
    n *= topology->arity[i];
  }
}
Beispiel #25
0
int decompose(int n,int optimize,int *tab)
{
  int primes[6] = {2,3,5,7,11,0};
  int i = 0,j = 1,flag = 2;
  unsigned int vl = get_verbose_level();

  while( primes[i] && (n!=1) ){
    /*    printf("[%d] before=%d\n",primes[i],n); */
    if( flag && optimize && (n%primes[i]!= 0) ){
      n += primes[i] - n%primes[i];
      flag--;
      i = 0;
      continue;
    }
    /* printf("after=%d\n",n); */
    if( n%primes[i] == 0 ){
      tab[j++] = primes[i];
      n /= primes[i];
    }else{
      i++;
      flag = 1;
    }
  }
  if( n != 1 )
    tab[j++] = n;

  qsort(tab+1,j-1,sizeof(int),int_cmp);

  if(vl >= DEBUG){
    for( i = 0 ; i < j ; i++ )
      printf("%d:",tab[i]);
    printf("\n");
  }

  tab[j] = 0;

  return (j+1);
}
Beispiel #26
0
/* Recursive routine to prove via ECPP */
static int ecpp_down(int i, mpz_t Ni, int facstage, IV* dlist, mpz_t* sfacs, int* nsfacs, char** prooftextptr)
{
  mpz_t a, b, u, v, m, q, minfactor, sqrtn, mD, t, t2;
  mpz_t mlist[6];
  UV nm1a;
  IV np1lp, np1lq;
  struct ec_affine_point P;
  int k, dnum, nidigits, facresult, curveresult, downresult, stage, D;
  int verbose = get_verbose_level();

  nidigits = mpz_sizeinbase(Ni, 10);

  k = _GMP_is_prob_prime(Ni);
  if (k == 0)  return 0;
  if (k == 2) {
    /* No need to put anything in the proof */
    if (verbose) printf("%*sN[%d] (%d dig)  PRIME\n", i, "", i, nidigits);
    return 2;
  }
  downresult = 0;

  if (verbose) {
    printf("%*sN[%d] (%d dig)", i, "", i, nidigits);
    if (facstage > 1) printf(" FS %d", facstage);
    fflush(stdout);
  }

  mpz_init(a);  mpz_init(b);
  mpz_init(u);  mpz_init(v);
  mpz_init(m);  mpz_init(q);
  mpz_init(mD); mpz_init(minfactor);  mpz_init(sqrtn);
  mpz_init(t);  mpz_init(t2);
  mpz_init(P.x);mpz_init(P.y);
  for (k = 0; k < 6; k++)
    mpz_init(mlist[k]);

  /* Any factors q found must be strictly > minfactor.
   * See Atkin and Morain, 1992, section 6.4 */
  mpz_root(minfactor, Ni, 4);
  mpz_add_ui(minfactor, minfactor, 1);
  mpz_mul(minfactor, minfactor, minfactor);
  mpz_sqrt(sqrtn, Ni);

  for (stage = (i == 0) ? facstage : 1; stage <= facstage; stage++) {
    int next_stage = (stage > 1) ? stage : 1;
    for (dnum = 0; dlist[dnum] != 0; dnum++) {
      int poly_type;  /* just for debugging/verbose */
      int poly_degree;
      D = -dlist[dnum];
      if (D > 1) continue;  /* Marked for skip */

      if (D == 1) {   /* n-1 test */
        mpz_sub_ui(m, Ni, 1);          /* m = N-1 */
        mpz_sub_ui(t2, sqrtn, 1);
        mpz_tdiv_q_2exp(t2, t2, 1);    /* t2 = minfactor */

        facresult = check_for_factor2(q, m, t2, t, stage, sfacs, nsfacs, 0);
        if (facresult <= 0)
          continue;
        if (verbose)
          { printf(" n-1\n"); fflush(stdout); }
        downresult = ecpp_down(i+1, q, next_stage, dlist, sfacs, nsfacs, prooftextptr);
        if (downresult == 0)     /* composite */
          goto end_down;
        if (downresult == 1) {   /* nothing found at this stage */
          if (verbose) {
            printf("%*sN[%d] (%d dig)", i, "", i, nidigits);
            if (facstage > 1) printf(" FS %d", facstage);
            fflush(stdout);
          }
          continue;
        }
        if (verbose)
          { printf("%*sN[%d] (%d dig) n-1", i, "", i, nidigits); fflush(stdout); }
        curveresult = _GMP_primality_bls_3(Ni, q, &nm1a);
        if (verbose) { printf("  %d\n", curveresult); fflush(stdout); }
        if ( ! curveresult ) {
          /* This ought not happen */
          dlist[dnum] = -2; /* skip this D value from now on */
          if (verbose) gmp_printf("\n  Could not prove n-1 with N = %Zd\n", D, Ni);
          downresult = 0;
          continue;
        }
        goto end_down;
      }
      if (D == -1) {  /* n+1 test */
        mpz_add_ui(m, Ni, 1);          /* m = N+1 */
        mpz_add_ui(t2, sqrtn, 1);
        mpz_tdiv_q_2exp(t2, t2, 1);    /* t2 = minfactor */

        facresult = check_for_factor2(q, m, t2, t, stage, sfacs, nsfacs, 0);
        if (facresult <= 0)
          continue;
        if (verbose)
          { printf(" n+1\n"); fflush(stdout); }
        downresult = ecpp_down(i+1, q, next_stage, dlist, sfacs, nsfacs, prooftextptr);
        if (downresult == 0)     /* composite */
          goto end_down;
        if (downresult == 1) {   /* nothing found at this stage */
          if (verbose) {
            printf("%*sN[%d] (%d dig)", i, "", i, nidigits);
            if (facstage > 1) printf(" FS %d", facstage);
            fflush(stdout);
          }
          continue;
        }
        if (verbose)
          { printf("%*sN[%d] (%d dig) n-1", i, "", i, nidigits); fflush(stdout); }
        curveresult = _GMP_primality_bls_15(Ni, q, &np1lp, &np1lq);
        if (verbose) { printf("  %d\n", curveresult); fflush(stdout); }
        if ( ! curveresult ) {
          /* This ought not happen */
          dlist[dnum] = -2; /* skip this D value from now on */
          if (verbose) gmp_printf("\n  Could not prove n-1 with N = %Zd\n", D, Ni);
          downresult = 0;
          continue;
        }
        goto end_down;
      }

      if ( (-D % 4) != 3 && (-D % 16) != 4 && (-D % 16) != 8 )
        croak("Invalid discriminant '%d' in list\n", D);
      /* D must also be squarefree in odd divisors, but assume it. */
      /* Make sure we can get a class polynomial for this D. */
      poly_degree = poly_class_poly(D, NULL, &poly_type);
      if (poly_degree == 0)  continue;
      /* We'll save time in the long run by not looking at big polys once
       * we've found a good path from the start.  TODO: Needs more tuning. */
      if (stage == 0 && i >= 0 && poly_degree > 2) break;
      if (facstage == 1) {
        if (i >  2 && nidigits < 1100 && poly_degree > 24)  break;
        if (i >  3 && nidigits <  950 && poly_degree > 15)  break;
        if (i >  4 && nidigits <  800 && poly_degree > 11)  break;
        if (i >  8 && nidigits <  700 && poly_degree >  9)  break;
        if (i > 16 && nidigits <  600 && poly_degree >  8)  break;
      }
      mpz_set_si(mD, D);
      /* (D/N) must be 1, and we have to have a u,v solution */
      if (mpz_jacobi(mD, Ni) != 1)
        continue;
      if ( ! modified_cornacchia(u, v, mD, Ni) )
        continue;

      if (verbose > 1)
        { printf(" %d", D); fflush(stdout); }

      choose_m(mlist, D, u, v, Ni, t, t2);
      for (k = 0; k < 6; k++) {
        facresult = check_for_factor2(q, mlist[k], minfactor, t, stage, sfacs, nsfacs, poly_degree);
        /* -1 = couldn't find, 0 = no big factors, 1 = found */
        if (facresult <= 0)
          continue;
        mpz_set(m, mlist[k]);
        if (verbose)
          { printf(" %d (%s %d)\n", D, (poly_type == 1) ? "Hilbert" : "Weber", poly_degree); fflush(stdout); }
        /* Great, now go down. */
        downresult = ecpp_down(i+1, q, next_stage, dlist, sfacs, nsfacs, prooftextptr);
        if (downresult == 0)     /* composite */
          goto end_down;
        if (downresult == 1) {   /* nothing found at this stage */
          if (verbose) {
            printf("%*sN[%d] (%d dig)", i, "", i, nidigits);
            if (facstage > 1) printf(" FS %d", facstage);
            fflush(stdout);
          }
          continue;
        }

        /* Awesome, we found the q chain and are in STAGE 2 */
        if (verbose)
          { printf("%*sN[%d] (%d dig) %d (%s %d)", i, "", i, nidigits, D, (poly_type == 1) ? "Hilbert" : "Weber", poly_degree); fflush(stdout); }

        curveresult = find_curve(a, b, P.x, P.y, D, m, q, Ni);
        if (verbose) { printf("  %d\n", curveresult); fflush(stdout); }
        if (curveresult == 1) {
          /* Oh no!  We can't find a point on the curve.  Something is right
           * messed up, and we've wasted a lot of time.  Sigh. */
          dlist[dnum] = -2; /* skip this D value from now on */
          if (verbose) gmp_printf("\n  Invalidated D = %d with N = %Zd\n", D, Ni);
          downresult = 0;
          continue;
        }
        /* We found it was composite or proved it */
        goto end_down;
      } /* k loop for D */
    } /* D */
  } /* fac stage */
  /* Nothing at this level */
  downresult = 1;
  if (verbose) { printf(" ---\n"); fflush(stdout); }

end_down:

  if (downresult == 2) {
    if (0 && verbose > 1) {
      if (D == 1) {
        gmp_printf("\n");
        gmp_printf("Type BLS3\n");
        gmp_printf("N  %Zd\n", Ni);
        gmp_printf("Q  %Zd\n", q);
        gmp_printf("A  %lu\n", (unsigned long) nm1a);
        gmp_printf("\n");
        fflush(stdout);
      } else if (D == -1) {
        gmp_printf("\n");
        gmp_printf("Type BLS15\n");
        gmp_printf("N  %Zd\n", Ni);
        gmp_printf("Q  %Zd\n", q);
        gmp_printf("LP %ld\n", (signed long) np1lp);
        gmp_printf("LQ %ld\n", (signed long) np1lq);
        gmp_printf("\n");
        fflush(stdout);
      } else {
        gmp_printf("\n");
        gmp_printf("Type ECPP\n");
        gmp_printf("N  %Zd\n", Ni);
        gmp_printf("A  %Zd\n", a);
        gmp_printf("B  %Zd\n", b);
        gmp_printf("M  %Zd\n", m);
        gmp_printf("Q  %Zd\n", q);
        gmp_printf("X  %Zd\n", P.x);
        gmp_printf("Y  %Zd\n", P.y);
        gmp_printf("\n");
        fflush(stdout);
      }
    }
    /* Prepend our proof to anything that exists. */
    if (prooftextptr != 0) {
      char *proofstr, *proofptr;
      int curprooflen = (*prooftextptr == 0) ? 0 : strlen(*prooftextptr);

      if (D == 1) {
        int myprooflen = 20 + 2*(4 + mpz_sizeinbase(Ni, 10)) + 1*21;
        New(0, proofstr, myprooflen + curprooflen + 1, char);
        proofptr = proofstr;
        proofptr += gmp_sprintf(proofptr, "Type BLS3\nN  %Zd\nQ  %Zd\nA  %"UVuf"\n", Ni, q, nm1a);
      } else if (D == -1) {
Beispiel #27
0
int is_aks_prime(mpz_t n)
{
  mpz_t *px, *py;
  int retval;
  UV i, s, r, a;
  UV starta = 1;
  int _verbose = get_verbose_level();

  if (mpz_cmp_ui(n, 4) < 0)
    return (mpz_cmp_ui(n, 1) <= 0) ? 0 : 1;

  /* Just for performance: check small divisors: 2*3*5*7*11*13*17*19*23 */
  if (mpz_gcd_ui(0, n, 223092870UL) != 1 && mpz_cmp_ui(n, 23) > 0)
    return 0;

  if (mpz_perfect_power_p(n))
    return 0;

#if AKS_VARIANT == AKS_VARIANT_V6    /* From the V6 AKS paper */
  {
    mpz_t sqrtn, t;
    double log2n;
    UV limit, startr;
    PRIME_ITERATOR(iter);

    mpz_init(sqrtn);
    mpz_sqrt(sqrtn, n);

    log2n = mpz_log2(n);
    limit = (UV) floor( log2n * log2n );

    if (_verbose>1) gmp_printf("# AKS checking order_r(%Zd) to %"UVuf"\n", n, (unsigned long) limit);

    /* Using a native r limits us to ~2000 digits in the worst case (r ~ log^5n)
     * but would typically work for 100,000+ digits (r ~ log^3n).  This code is
     * far too slow to matter either way.  Composite r is ok here, but it will
     * always end up prime, so save time and just check primes. */
    retval = 0;
    /* Start order search at a good spot.  Idea from Nemana and Venkaiah. */
    startr = (mpz_sizeinbase(n,2)-1) * (mpz_sizeinbase(n,2)-1);
    startr = (startr < 1002) ? 2 : startr - 100;
    for (r = 2; /* */; r = prime_iterator_next(&iter)) {
      if (mpz_divisible_ui_p(n, r) ) /* r divides n.  composite. */
        { retval = 0; break; }
      if (mpz_cmp_ui(sqrtn, r) <= 0) /* no r <= sqrtn divides n.  prime. */
        { retval = 1; break; }
      if (r < startr) continue;
      if (mpz_order_ui(r, n, limit) > limit)
        { retval = 2; break; }
    }
    prime_iterator_destroy(&iter);
    mpz_clear(sqrtn);
    if (retval != 2) return retval;

    /* Since r is prime, phi(r) = r-1. */
    s = (UV) floor( sqrt(r-1) * log2n );
  }
#elif AKS_VARIANT == AKS_VARIANT_BORNEMANN /* Bernstein + Voloch */
  {
    UV slim;
    double c2, x;
    /* small t = few iters of big poly.  big t = many iters of small poly */
    double const t = (mpz_sizeinbase(n, 2) <= 64) ? 32 : 40;
    double const t1 = (1.0/((t+1)*log(t+1)-t*log(t)));
    double const dlogn = mpz_logn(n);
    mpz_t tmp;
    PRIME_ITERATOR(iter);

    mpz_init(tmp);
    prime_iterator_setprime(&iter, (UV) (t1*t1 * dlogn*dlogn) );
    r = prime_iterator_next(&iter);
    while (!is_primitive_root_uiprime(n,r))
      r = prime_iterator_next(&iter);
    prime_iterator_destroy(&iter);

    slim = (UV) (2*t*(r-1));
    c2 = dlogn * floor(sqrt(r));
    { /* Binary search for first s in [1,slim] where x >= 0 */
      UV bi = 1;
      UV bj = slim;
      while (bi < bj) {
        s = bi + (bj-bi)/2;
        mpz_bin_uiui(tmp, r+s-1, s);
        x = mpz_logn(tmp) / c2 - 1.0;
        if (x < 0)  bi = s+1;
        else        bj = s;
      }
      s = bi-1;
    }
    s = (s+3) >> 1;
    /* Bornemann checks factors up to (s-1)^2, we check to max(r,s) */
    /* slim = (s-1)*(s-1); */
    slim = (r > s) ? r : s;
    if (_verbose > 1) printf("# aks trial to %"UVuf"\n", slim);
    if (_GMP_trial_factor(n, 2, slim) > 1)
      { mpz_clear(tmp); return 0; }
    mpz_sqrt(tmp, n);
    if (mpz_cmp_ui(tmp, slim) <= 0)
      { mpz_clear(tmp); return 1; }
    mpz_clear(tmp);
  }
#elif AKS_VARIANT == AKS_VARIANT_BERN21
  { /* Bernstein 2003, theorem 2.1 (simplified) */
    UV q;
    double slim, scmp, x;
    mpz_t t, t2;
    PRIME_ITERATOR(iter);
    mpz_init(t);  mpz_init(t2);
    r = s = 0;
    while (1) {
      /* todo: Check r|n and r >= sqrt(n) here instead of waiting */
      if (mpz_cmp_ui(n, r) <= 0) break;
      r = prime_iterator_next(&iter);
      q = largest_factor(r-1);
      mpz_set_ui(t, r);
      mpz_powm_ui(t, n, (r-1)/q, t);
      if (mpz_cmp_ui(t, 1) <= 0) continue;
      scmp = 2 * floor(sqrt(r)) * mpz_log2(n);

      slim = 20 * (r-1);

      /* Check viability */
      mpz_bin_uiui(t, q+slim-1, slim); if (mpz_log2(t) < scmp) continue;

      for (s = 2; s < slim; s++) {
        mpz_bin_uiui(t, q+s-1, s);
        if (mpz_log2(t) > scmp) break;
      }
      if (s < slim) break;
    }
    mpz_clear(t);  mpz_clear(t2);
    prime_iterator_destroy(&iter);
    if (_GMP_trial_factor(n, 2, s) > 1)
      return 0;
  }
#elif AKS_VARIANT == AKS_VARIANT_BERN22
  { /* Bernstein 2003, theorem 2.2 (simplified) */
    UV q;
    double slim, scmp, x;
    mpz_t t, t2;
    PRIME_ITERATOR(iter);
    mpz_init(t);  mpz_init(t2);
    r = s = 0;
    while (1) {
      /* todo: Check r|n and r >= sqrt(n) here instead of waiting */
      if (mpz_cmp_ui(n, r) <= 0) break;
      r = prime_iterator_next(&iter);
      if (!is_primitive_root_uiprime(n,r)) continue;
      q = r-1;   /* Since r is prime, phi(r) = r-1 */
      scmp = 2 * floor(sqrt(r-1)) * mpz_log2(n);

      slim = 20 * (r-1);

      /* Check viability */
      mpz_bin_uiui(t, q+slim-1, slim); if (mpz_log2(t) < scmp) continue;

      for (s = 2; s < slim; s++) {
        mpz_bin_uiui(t, q+s-1, s);
        if (mpz_log2(t) > scmp) break;
      }
      if (s < slim) break;
    }
    mpz_clear(t);  mpz_clear(t2);
    prime_iterator_destroy(&iter);
    if (_GMP_trial_factor(n, 2, s) > 1)
      return 0;
  }
#elif AKS_VARIANT == AKS_VARIANT_BERN23
  { /* Bernstein 2003, theorem 2.3 (simplified) */
    UV q, d, limit;
    double slim, scmp, sbin, x, log2n;
    mpz_t t, t2;
    PRIME_ITERATOR(iter);
    mpz_init(t);  mpz_init(t2);
    log2n = mpz_log2(n);
    limit = (UV) floor( log2n * log2n );
    r = 2;
    s = 0;
    while (1) {
      /* todo: Check r|n and r >= sqrt(n) here instead of waiting */
      if (mpz_cmp_ui(n, r) <= 0) break;
      r++;
      UV gcd = mpz_gcd_ui(NULL, n, r);
      if (gcd != 1) { mpz_clear(t); mpz_clear(t2); return 0; }
      UV v = mpz_order_ui(r, n, limit);
      if (v >= limit) continue;

      mpz_set_ui(t2, r);
      totient(t, t2);
      q = mpz_get_ui(t);
      UV phiv = q/v;
      /* printf("phi(%lu)/v = %lu/%lu = %lu\n", r, q, v, phiv); */

      /* This is extremely inefficient. */

      /* Choose an s value we'd be happy with */
      slim = 20 * (r-1);

      /* Quick check to see if it could work with s=slim, d=1 */
      mpz_bin_uiui(t, q+slim-1, slim);
      sbin = mpz_log2(t);
      if (sbin < 2*floor(sqrt(q))*log2n)
        continue;

      for (s = 2; s < slim; s++) {
        mpz_bin_uiui(t, q+s-1, s);
        sbin = mpz_log2(t);
        if (sbin < 2*floor(sqrt(q))*log2n) continue;   /* d=1 */
        /* Check each number dividing phi(r)/v */
        for (d = 2; d < phiv; d++) {
          if ((phiv % d) != 0) continue;
          scmp = 2 * d * floor(sqrt(q/d)) * log2n;
          if (sbin < scmp) break;
        }
        /* if we did not exit early, this s worked for each d.  This s wins. */
        if (d >= phiv) break;
      }
      if (s < slim) break;
    }
    mpz_clear(t);  mpz_clear(t2);
    prime_iterator_destroy(&iter);
    if (_GMP_trial_factor(n, 2, s) > 1)
      return 0;
  }
#elif AKS_VARIANT == AKS_VARIANT_BERN41
  {
    double const log2n = mpz_log2(n);
    /* Tuning: Initial 'r' selection */
    double const r0 = 0.008 * log2n * log2n;
    /* Tuning: Try a larger 'r' if 's' looks very large */
    UV const rmult = 8;
    UV slim;
    mpz_t tmp, tmp2;
    PRIME_ITERATOR(iter);

    mpz_init(tmp);  mpz_init(tmp2);
    /* r has to be at least 3. */
    prime_iterator_setprime(&iter, (r0 < 2) ? 2 : (UV) r0);
    r = prime_iterator_next(&iter);

    /* r must be a primitive root.  For performance, skip if s looks too big. */
    while ( !is_primitive_root_uiprime(n, r) ||
            !bern41_acceptable(n, r, rmult*(r-1), tmp, tmp2) )
      r = prime_iterator_next(&iter);
    prime_iterator_destroy(&iter);

    { /* Binary search for first s in [1,lim] where conditions met */
      UV bi = 1;
      UV bj = rmult * (r-1);
      while (bi < bj) {
        s = bi + (bj-bi)/2;
        if (!bern41_acceptable(n,r,s,tmp,tmp2))  bi = s+1;
        else                                     bj = s;
      }
      s = bj;
      /* Our S goes from 2 to s+1. */
      starta = 2;
      s = s+1;
    }
    /* printf("chose r=%lu s=%lu d = %lu i = %lu j = %lu\n", r, s, d, i, j); */

    /* Check divisibility to s(s-1) to cover both gcd conditions */
    slim = s * (s-1);
    if (_verbose > 1) printf("# aks trial to %"UVuf"\n", slim);
    if (_GMP_trial_factor(n, 2, slim) > 1)
      { mpz_clear(tmp); mpz_clear(tmp2); return 0; }
    /* If we checked divisibility to sqrt(n), then it is prime. */
    mpz_sqrt(tmp, n);
    if (mpz_cmp_ui(tmp, slim) <= 0)
      { mpz_clear(tmp); mpz_clear(tmp2); return 1; }

    /* Check b^(n-1) = 1 mod n for b in [2..s] */
    if (_verbose > 1) printf("# aks checking fermat to %"UVuf"\n", s);
    mpz_sub_ui(tmp2, n, 1);
    for (i = 2; i <= s; i++) {
      mpz_set_ui(tmp, i);
      mpz_powm(tmp, tmp, tmp2, n);
      if (mpz_cmp_ui(tmp, 1) != 0)
        { mpz_clear(tmp); mpz_clear(tmp2); return 0; }
    }

    mpz_clear(tmp);  mpz_clear(tmp2);
  }

#endif

  if (_verbose) gmp_printf("# AKS %Zd.  r = %"UVuf" s = %"UVuf"\n", n, (unsigned long) r, (unsigned long) s);

  /* Create the three polynomials we will use */
  New(0, px, r, mpz_t);
  New(0, py, r, mpz_t);
  if ( !px || !py )
    croak("allocation failure\n");
  for (i = 0; i < r; i++) {
    mpz_init(px[i]);
    mpz_init(py[i]);
  }

  retval = 1;
  for (a = starta; a <= s; a++) {
    retval = test_anr(a, n, r, px, py);
    if (!retval) break;
    if (_verbose>1) { printf("."); fflush(stdout); }
  }
  if (_verbose>1) { printf("\n"); fflush(stdout); };

  /* Free the polynomials */
  for (i = 0; i < r; i++) {
    mpz_clear(px[i]);
    mpz_clear(py[i]);
  }
  Safefree(px);
  Safefree(py);

  return retval;
}
Beispiel #28
0
int
poll(struct pollfd *ufds, nfds_t nfds, int timeout)
{
    static void             *libc_handle;
    int                      retval;
    static poll_handle       orig_poll = NULL;
    struct pollfd           *p;
    int                      i;
    int                      fd = -1;
    int                      begin = 0;
    int                      elapsed = 0;

    dd("calling my poll");

    init_libc_handle();

    if (orig_poll == NULL) {
        orig_poll = dlsym(libc_handle, "poll");
        if (orig_poll == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying poll: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    init_matchbufs();

    dd("calling the original poll");

    if (pattern) {
        begin = now();
    }

    retval = (*orig_poll)(ufds, nfds, timeout);

    if (pattern) {
        elapsed = now() - begin;
    }

    if (retval > 0) {
        struct timeval  tm;

        p = ufds;
        for (i = 0; i < nfds; i++, p++) {
            fd = p->fd;
            if (fd > MAX_FD || weird_fds[fd]) {
                dd("skipping fd %d", fd);
                continue;
            }

            if (pattern && (p->revents & POLLOUT) && snd_timeout_fds[fd]) {

                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: poll: should suppress write "
                            "event on fd %d.\n", fd);
                }

                p->revents &= ~POLLOUT;

                if (p->revents == 0) {
                    retval--;
                    continue;
                }
            }

            if (blacklist_fds[fd]) {
                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: poll: skip fd %d because it "
                            "is in blacklist\n", fd);
                }

                continue;
            }

            active_fds[fd] = p->revents;
            polled_fds[fd] = 1;

            if (get_verbose_level()) {
                fprintf(stderr, "mockeagain: poll: fd %d polled with events "
                        "%d\n", fd, p->revents);
            }
        }

        if (retval == 0) {
            if (get_verbose_level()) {
                fprintf(stderr, "mockeagain: poll: emulating timeout on "
                        "fd %d.\n", fd);
            }

            if (timeout < 0) {
                tm.tv_sec = 3600 * 24;
                tm.tv_usec = 0;

                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: poll: sleeping 1 day "
                            "on fd %d.\n", fd);
                }

                select(0, NULL, NULL, NULL, &tm);

            } else {

                if (elapsed < timeout) {
                    int     diff;

                    diff = timeout - elapsed;

                    tm.tv_sec = diff / 1000;
                    tm.tv_usec = diff % 1000 * 1000;

                    if (get_verbose_level()) {
                        fprintf(stderr, "mockeagain: poll: sleeping %d ms "
                                "on fd %d.\n", diff, fd);
                    }

                    select(0, NULL, NULL, NULL, &tm);
                }
            }
        }
    }

    return retval;
}
Beispiel #29
0
ssize_t
send(int fd, const void *buf, size_t len, int flags)
{
    ssize_t                  retval;
    static send_handle       orig_send = NULL;

    dd("calling my send");

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && written_fds[fd]
        && !(active_fds[fd] & POLLOUT))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to "
                    "signal EAGAIN\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    written_fds[fd] = 1;

    init_libc_handle();

    if (orig_send == NULL) {
        orig_send = dlsym(libc_handle, "send");
        if (orig_send == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying send: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && len)
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"send\" on fd %d to emit "
                    "1 byte data only\n", fd);
        }

        if (pattern && len) {
            char          *p;
            size_t         len;
            char           c;

            c = *(char *) buf;

            if (matchbufs[fd] == NULL) {

                matchbufs[fd] = malloc(matchbuf_len);
                if (matchbufs[fd] == NULL) {
                    fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n");
                }

                p = matchbufs[fd];
                memset(p, 0, matchbuf_len);

                p[0] = c;

                len = 1;

            } else {
                p = matchbufs[fd];

                len = strlen(p);

                if (len < matchbuf_len - 1) {
                    p[len] = c;
                    len++;

                } else {
                    memmove(p, p + 1, matchbuf_len - 2);

                    p[matchbuf_len - 2] = c;
                }
            }

            /* test if the pattern matches the matchbuf */

            dd("matchbuf: %.*s (len: %d)", (int) len, p,
                    (int) matchbuf_len - 1);

            if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) {
                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: \"writev\" has found a match for "
                            "the timeout pattern \"%s\" on fd %d.\n", pattern, fd);
                }

                snd_timeout_fds[fd] = 1;
            }
        }

        retval = (*orig_send)(fd, buf, 1, flags);
        active_fds[fd] &= ~POLLOUT;

    } else {

        dd("calling the original send on fd %d", fd);

        retval = (*orig_send)(fd, buf, len, flags);
    }

    return retval;
}
Beispiel #30
0
ssize_t
writev(int fd, const struct iovec *iov, int iovcnt)
{
    ssize_t                  retval;
    static writev_handle     orig_writev = NULL;
    struct iovec             new_iov[1] = { {NULL, 0} };
    const struct iovec      *p;
    int                      i;
    size_t                   len = 0;

    if ((get_mocking_type() & MOCKING_WRITES)
        && get_verbose_level()
        && fd <= MAX_FD)
    {
        fprintf(stderr, "mockeagain: writev(%d): polled=%d, written=%d, "
                "active=%d\n", fd, (int) polled_fds[fd], (int) written_fds[fd],
                (int) active_fds[fd]);
    }

    if ((get_mocking_type() & MOCKING_WRITES)
        && fd <= MAX_FD
        && polled_fds[fd]
        && written_fds[fd]
        && !(active_fds[fd] & POLLOUT))
    {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to "
                    "signal EAGAIN.\n", fd);
        }

        errno = EAGAIN;
        return -1;
    }

    written_fds[fd] = 1;

    init_libc_handle();

    if (orig_writev == NULL) {
        orig_writev = dlsym(libc_handle, "writev");
        if (orig_writev == NULL) {
            fprintf(stderr, "mockeagain: could not find the underlying writev: "
                    "%s\n", dlerror());
            exit(1);
        }
    }

    if (!(get_mocking_type() & MOCKING_WRITES)) {
        return (*orig_writev)(fd, iov, iovcnt);
    }

    if (fd <= MAX_FD && polled_fds[fd]) {
        p = iov;
        for (i = 0; i < iovcnt; i++, p++) {
            if (p->iov_base == NULL || p->iov_len == 0) {
                continue;
            }

            new_iov[0].iov_base = p->iov_base;
            new_iov[0].iov_len = 1;
            break;
        }

        len = 0;
        p = iov;
        for (i = 0; i < iovcnt; i++, p++) {
            len += p->iov_len;
        }
    }

    if (new_iov[0].iov_base == NULL) {
        retval = (*orig_writev)(fd, iov, iovcnt);

    } else {
        if (get_verbose_level()) {
            fprintf(stderr, "mockeagain: mocking \"writev\" on fd %d to emit "
                    "1 of %llu bytes.\n", fd, (unsigned long long) len);
        }

        if (pattern && new_iov[0].iov_len) {
            char          *p;
            size_t         len;
            char           c;

            c = *(char *) new_iov[0].iov_base;

            if (matchbufs[fd] == NULL) {

                matchbufs[fd] = malloc(matchbuf_len);
                if (matchbufs[fd] == NULL) {
                    fprintf(stderr, "mockeagain: ERROR: failed to allocate memory.\n");
                }

                p = matchbufs[fd];
                memset(p, 0, matchbuf_len);

                p[0] = c;

                len = 1;

            } else {
                p = matchbufs[fd];

                len = strlen(p);

                if (len < matchbuf_len - 1) {
                    p[len] = c;
                    len++;

                } else {
                    memmove(p, p + 1, matchbuf_len - 2);

                    p[matchbuf_len - 2] = c;
                }
            }

            /* test if the pattern matches the matchbuf */

            dd("matchbuf: %.*s (len: %d)", (int) len, p,
                    (int) matchbuf_len - 1);

            if (len == matchbuf_len - 1 && strncmp(p, pattern, len) == 0) {
                if (get_verbose_level()) {
                    fprintf(stderr, "mockeagain: \"writev\" has found a match for "
                            "the timeout pattern \"%s\" on fd %d.\n", pattern, fd);
                }

                snd_timeout_fds[fd] = 1;
            }
        }

        dd("calling the original writev on fd %d", fd);
        retval = (*orig_writev)(fd, new_iov, 1);
        active_fds[fd] &= ~POLLOUT;
    }

    return retval;
}