Example #1
0
void
c_setpool(dvec3_t start, dvec3_t end)
{
	int L1, L2;
	int poolnum;

	pool=(float*)m_realloc(pool, sizeof(float)*10240);
	poolnum=0;

	col_poly=(bool*)m_realloc(col_poly, sizeof(bool)*m_numpolygons);
	memset(col_poly, false, sizeof(bool)*m_numpolygons);
	col_curvepoly=(bool*)m_realloc(col_curvepoly, sizeof(bool)*b_numpolygons);
	memset(col_curvepoly, false, sizeof(bool)*b_numpolygons);

	c_checkpath(1, start, end);

	for(L1=0;L1<m_numpolygons;L1++)
	{
		if(!col_poly[L1])continue;
		for(L2=0;L2<m_polygon[L1].numvertex-2;L2++)
		{
			pool[poolnum*9]=m_polygon[L1].vertex[0].x;
			pool[poolnum*9+1]=m_polygon[L1].vertex[0].y;
			pool[poolnum*9+2]=m_polygon[L1].vertex[0].z;

			pool[poolnum*9+3]=m_polygon[L1].vertex[L2+1].x;
			pool[poolnum*9+4]=m_polygon[L1].vertex[L2+1].y;
			pool[poolnum*9+5]=m_polygon[L1].vertex[L2+1].z;

			pool[poolnum*9+6]=m_polygon[L1].vertex[L2+2].x;
			pool[poolnum*9+7]=m_polygon[L1].vertex[L2+2].y;
			pool[poolnum*9+8]=m_polygon[L1].vertex[L2+2].z;

			poolnum++;
		}
	}
	for(L1=0;L1<b_numpolygons;L1++)
	{
		if(!col_curvepoly[L1])continue;
		for(L2=0;L2<b_polygon[L1].numvertex-2;L2++)
		{
			pool[poolnum*9]=b_polygon[L1].vertex[0].x;
			pool[poolnum*9+1]=b_polygon[L1].vertex[0].y;
			pool[poolnum*9+2]=b_polygon[L1].vertex[0].z;

			pool[poolnum*9+3]=b_polygon[L1].vertex[L2+1].x;
			pool[poolnum*9+4]=b_polygon[L1].vertex[L2+1].y;
			pool[poolnum*9+5]=b_polygon[L1].vertex[L2+1].z;

			pool[poolnum*9+6]=b_polygon[L1].vertex[L2+2].x;
			pool[poolnum*9+7]=b_polygon[L1].vertex[L2+2].y;
			pool[poolnum*9+8]=b_polygon[L1].vertex[L2+2].z;

			poolnum++;
		}
	}

	SetTrianglePool(poolnum, pool, 0);
}
Example #2
0
/* Note: we always use the highest level.
 * TO boost the performance we may want to add some
 * additional code for level 1
 */
static int
gather_random( void (*add)(const void*, size_t, int), int requester,
					  size_t length, int level )
{
    unsigned int result;
    unsigned int nbytes;

    if( !level )
	return 0;

    if( !slow_seeder )
	load_and_init_winseed();

    /* Our estimation on how much entropy we should use is very vague.
     * Winseed delivers some amount of entropy on each slow poll and
     * we add it to our random pool.  Depending on the required quality
     * level we adjust the requested length so that for higher quality
     * we make sure to add more entropy to our pool.  However, as we don't
     * like to waste any entropy collected by winseed, we always add
     * at least everything we got from winseed.
     */
    if( level > 1 )
	length *= 100;
    else if( level > 0 )
	length *= 10;

    for(;;) {
	nbytes = entropy_buffer_size;
	result = get_seed( slow_seeder, entropy_buffer, &nbytes);
	if( result == PCP_SEEDER_TOO_SMALL ) {
	    unsigned int n1 = get_internal_seed_size( slow_seeder );

	    if( n1 > MAX_SEEDER_SIZE ) {
		g10_log_fatal("rndw32: internal seeder problem (size=%u)\n",
									  n1);
		return -1; /* actually never reached */
	    }
	    n1 += SEEDER_INC_CHUNK;
	    set_internal_seed_size( slow_seeder, n1 );
	    if( n1 > entropy_buffer_size ) {
		entropy_buffer_size =  n1;
		entropy_buffer = m_realloc( entropy_buffer,
					    entropy_buffer_size );
	    }
	    continue;
	}


	if( result ) {
	    g10_log_fatal("rndw32: get_seed(slow) failed: rc=%u\n", result);
	    return -1; /* actually never reached */
	}
	/*g10_log_info("rndw32: slow poll level %d, need %u, got %u\n",
		      level, (unsigned int)length, (unsigned int)nbytes );*/
	(*add)( entropy_buffer, nbytes, requester );
	if( length <= nbytes )
	    return 0; /* okay */
	length -= nbytes;
    }
}
Example #3
0
/* resize a buffer, pos and len will be repositioned if required */
void buf_resize(buffer *buf, unsigned int newsize) {

	buf->data = m_realloc(buf->data, newsize);
	buf->size = newsize;
	buf->len = MIN(newsize, buf->len);
	buf->pos = MIN(newsize, buf->pos);

}
Example #4
0
/*
 * Read the next filename from a filedescriptor and create a file_info struct
 * for it. If there is nothing to read return NULL.
 */
static struct file_info *
getfi(const char *root, int fd)
{
  static char* fn = NULL;
  static size_t fnlen = 0;
  size_t i= 0;
  struct file_info *fi;
  size_t rl = strlen(root);

  if (fn == NULL) {
    fnlen = rl + MAXFILENAME;
    fn = m_malloc(fnlen);
  } else if (fnlen < (rl + MAXFILENAME)) {
    fnlen = rl + MAXFILENAME;
    fn = m_realloc(fn, fnlen);
  }
  i=sprintf(fn,"%s/",root);
  
  while (1) {
    int	res;
    if (i>=fnlen) {
      fnlen += MAXFILENAME;
      fn = m_realloc(fn, fnlen);
    }
    if ((res=read(fd, (fn+i), sizeof(*fn)))<0) {
      if ((errno==EINTR) || (errno==EAGAIN))
	continue;
      else
	return NULL;
    }
    if (res==0)	// EOF -> parent died
      return NULL;
    if (fn[i] == '\0')
      break;

    i++;

    if (i >= MAXFILENAME)
      ohshit(_("file name '%.50s...' is too long"), fn + rl + 1);
  }

  fi = file_info_new(fn + rl + 1);
  lstat(fn, &(fi->st));

  return fi;
}
Example #5
0
static void
command_grow_argv(struct command *cmd, int need)
{
	/* Check if we already have enough room. */
	if ((cmd->argv_size - cmd->argc) >= need)
		return;

	cmd->argv_size = (cmd->argv_size + need) * 2;
	cmd->argv = m_realloc(cmd->argv, cmd->argv_size * sizeof(const char *));
}
/* resize a buffer, pos and len will be repositioned if required when
 * downsizing */
void buf_resize(buffer *buf, unsigned int newsize) {

	if (newsize > BUF_MAX_SIZE) {
		dropbear_exit("buf->size too big");
	}

	buf->data = m_realloc(buf->data, newsize);
	buf->size = newsize;
	buf->len = MIN(newsize, buf->len);
	buf->pos = MIN(newsize, buf->pos);

}
Example #7
0
STATIC mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg) {
    assert(MP_OBJ_IS_TYPE(self_in, &array_type));
    mp_obj_array_t *self = self_in;
    if (self->free == 0) {
        int item_sz = mp_binary_get_size(self->typecode);
        // TODO: alloc policy
        self->free = 8;
        self->items = m_realloc(self->items,  item_sz * self->len, item_sz * (self->len + self->free));
    }
    mp_binary_set_val(self->typecode, self->items, self->len++, arg);
    self->free--;
    return mp_const_none; // return None, as per CPython
}
Example #8
0
/* resize a buffer, pos and len will be repositioned if required when
 * downsizing */
buffer* buf_resize(buffer *buf, unsigned int newsize) {

	if (newsize > BUF_MAX_SIZE) {
		dropbear_exit("buf->size too big");
	}

	buf = m_realloc(buf, sizeof(buffer)+newsize);
	buf->data = (unsigned char*)buf + sizeof(buffer);
	buf->size = newsize;
	buf->len = MIN(newsize, buf->len);
	buf->pos = MIN(newsize, buf->pos);
	return buf;
}
Example #9
0
void
varbuf_grow(struct varbuf *v, size_t need_size)
{
  /* Make sure the varbuf is in a sane state. */
  if (v->size < v->used)
    internerr("varbuf used(%zu) > size(%zu)", v->used, v->size);

  /* Check if we already have enough room. */
  if ((v->size - v->used) >= need_size)
    return;

  v->size = (v->size + need_size) * 2;
  v->buf = m_realloc(v->buf, v->size);
}
Example #10
0
STATIC mp_obj_t socket_recv(uint n_args, const mp_obj_t *args) {
    mp_obj_socket_t *self = args[0];
    int sz = MP_OBJ_SMALL_INT_VALUE(args[1]);
    int flags = 0;

    if (n_args > 2) {
        flags = MP_OBJ_SMALL_INT_VALUE(args[2]);
    }

    char *buf = m_new(char, sz);
    int out_sz = recv(self->fd, buf, sz, flags);
    RAISE_ERRNO(out_sz, errno);

    buf = m_realloc(buf, sz, out_sz);
    return MP_OBJ_NEW_QSTR(qstr_from_strn_take(buf, out_sz, out_sz));
}
Example #11
0
/* Add the pid of a child to the list for exit-handling */
static void addchildpid(struct ChanSess *chansess, pid_t pid) {

	unsigned int i;
	for (i = 0; i < ses.childpidsize; i++) {
		if (ses.childpids[i].pid == -1) {
			break;
		}
	}

	/* need to increase size */
	if (i == ses.childpidsize) {
		ses.childpids = (struct ChildPid*)m_realloc(ses.childpids,
				sizeof(struct ChildPid) * ses.childpidsize+1);
	}
	
	ses.childpids[i].pid = pid;
	ses.childpids[i].chansess = chansess;

}
Example #12
0
static char *
get_control_dir(char *cidir)
{
  if (f_noact) {
    char *tmpdir;

    tmpdir = mkdtemp(path_make_temp_template("dpkg"));
    if (tmpdir == NULL)
      ohshite(_("unable to create temporary directory"));

    cidir = m_realloc(cidir, strlen(tmpdir) + MAXCONTROLFILENAME + 10);

    strcpy(cidir, tmpdir);

    free(tmpdir);
  } else {
    const char *admindir;

    admindir = dpkg_db_get_dir();

    /* The admindir length is always constant on a dpkg execution run. */
    if (cidir == NULL)
      cidir = m_malloc(strlen(admindir) + sizeof(CONTROLDIRTMP) +
                       MAXCONTROLFILENAME + 10);

    /* We want it to be on the same filesystem so that we can
     * use rename(2) to install the postinst &c. */
    strcpy(cidir, admindir);
    strcat(cidir, "/" CONTROLDIRTMP);

    /* Make sure the control information directory is empty. */
    ensure_pathname_nonexisting(cidir);
  }

  strcat(cidir, "/");

  return cidir;
}
Example #13
0
int parsedb(const char *filename, enum parsedbflags flags,
            struct pkginfo **donep, FILE *warnto, int *warncount) {
  /* warnto, warncount and donep may be null.
   * If donep is not null only one package's information is expected.
   */
  
  static int fd;
  struct pkginfo newpig, *pigp;
  struct pkginfoperfile *newpifp, *pifp;
  struct arbitraryfield *arp, **larpp;
  struct trigaw *ta;
  int pdone;
  int fieldencountered[array_count(fieldinfos)];
  const struct fieldinfo *fip;
  const struct nickname *nick;
  char *data, *dataptr, *endptr;
  const char *fieldstart, *valuestart;
  char *value= NULL;
  int fieldlen= 0, valuelen= 0;
  int *ip, c;
  struct stat st;
  struct parsedb_state ps;

  ps.filename = filename;
  ps.flags = flags;
  ps.lno = 0;
  ps.warnto = warnto;
  ps.warncount = 0;

  newpifp= (flags & pdb_recordavailable) ? &newpig.available : &newpig.installed;
  fd= open(filename, O_RDONLY);
  if (fd == -1) ohshite(_("failed to open package info file `%.255s' for reading"),filename);

  push_cleanup(cu_closefd, ~ehflag_normaltidy, NULL, 0, 1, &fd);

  if (fstat(fd, &st) == -1)
    ohshite(_("can't stat package info file `%.255s'"),filename);

  if (st.st_size > 0) {
#ifdef USE_MMAP
    dataptr = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (dataptr == MAP_FAILED)
      ohshite(_("can't mmap package info file `%.255s'"),filename);
#else
    dataptr = m_malloc(st.st_size);

    fd_buf_copy(fd, dataptr, st.st_size, _("copy info file `%.255s'"), filename);
#endif
    data= dataptr;
    endptr = dataptr + st.st_size;
  } else {
    data= dataptr= endptr= NULL;
  }

  pdone= 0;
#define EOF_mmap(dataptr, endptr)	(dataptr >= endptr)
#define getc_mmap(dataptr)		*dataptr++;
#define ungetc_mmap(c, dataptr, data)	dataptr--;

  for (;;) { /* loop per package */
    memset(fieldencountered, 0, sizeof(fieldencountered));
    blankpackage(&newpig);

/* Skip adjacent new lines */
    while(!EOF_mmap(dataptr, endptr)) {
      c= getc_mmap(dataptr); if (c!='\n' && c!=MSDOS_EOF_CHAR ) break;
      ps.lno++;
    }
    if (EOF_mmap(dataptr, endptr)) break;
    for (;;) { /* loop per field */
      fieldstart= dataptr - 1;
      while (!EOF_mmap(dataptr, endptr) && !isspace(c) && c!=':' && c!=MSDOS_EOF_CHAR)
        c= getc_mmap(dataptr);
      fieldlen= dataptr - fieldstart - 1;
      while (!EOF_mmap(dataptr, endptr) && c != '\n' && isspace(c)) c= getc_mmap(dataptr);
      if (EOF_mmap(dataptr, endptr))
        parse_error(&ps, &newpig,
                    _("EOF after field name `%.*s'"), fieldlen, fieldstart);
      if (c == '\n')
        parse_error(&ps, &newpig,
                    _("newline in field name `%.*s'"), fieldlen, fieldstart);
      if (c == MSDOS_EOF_CHAR)
        parse_error(&ps, &newpig,
                    _("MSDOS EOF (^Z) in field name `%.*s'"),
                    fieldlen, fieldstart);
      if (c != ':')
        parse_error(&ps, &newpig,
                    _("field name `%.*s' must be followed by colon"),
                    fieldlen, fieldstart);
/* Skip space after ':' but before value and eol */
      while(!EOF_mmap(dataptr, endptr)) {
        c= getc_mmap(dataptr);
        if (c == '\n' || !isspace(c)) break;
      }
      if (EOF_mmap(dataptr, endptr))
        parse_error(&ps, &newpig,
                    _("EOF before value of field `%.*s' (missing final newline)"),
                 fieldlen,fieldstart);
      if (c == MSDOS_EOF_CHAR)
        parse_error(&ps, &newpig,
                    _("MSDOS EOF char in value of field `%.*s' (missing newline?)"),
                    fieldlen,fieldstart);
      valuestart= dataptr - 1;
      for (;;) {
        if (c == '\n' || c == MSDOS_EOF_CHAR) {
          ps.lno++;
	  if (EOF_mmap(dataptr, endptr)) break;
          c= getc_mmap(dataptr);
/* Found double eol, or start of new field */
          if (EOF_mmap(dataptr, endptr) || c == '\n' || !isspace(c)) break;
          ungetc_mmap(c,dataptr, data);
          c= '\n';
        } else if (EOF_mmap(dataptr, endptr)) {
          parse_error(&ps, &newpig,
                      _("EOF during value of field `%.*s' (missing final newline)"),
                      fieldlen,fieldstart);
        }
        c= getc_mmap(dataptr);
      }
      valuelen= dataptr - valuestart - 1;
/* trim ending space on value */
      while (valuelen && isspace(*(valuestart+valuelen-1)))
 valuelen--;
      for (nick = nicknames;
           nick->nick && (strncasecmp(nick->nick, fieldstart, fieldlen) ||
                          nick->nick[fieldlen] != '\0'); nick++) ;
      if (nick->nick) {
	fieldstart= nick->canon;
	fieldlen= strlen(fieldstart);
      }
      for (fip= fieldinfos, ip= fieldencountered;
           fip->name && strncasecmp(fieldstart,fip->name, fieldlen);
           fip++, ip++);
      if (fip->name) {
        value = m_realloc(value, valuelen + 1);
	memcpy(value,valuestart,valuelen);
        *(value + valuelen) = '\0';
        if ((*ip)++)
          parse_error(&ps, &newpig,
                      _("duplicate value for `%s' field"), fip->name);
        fip->rcall(&newpig, newpifp, &ps, value, fip);
      } else {
        if (fieldlen<2)
          parse_error(&ps, &newpig,
                      _("user-defined field name `%.*s' too short"),
                      fieldlen, fieldstart);
        larpp= &newpifp->arbs;
        while ((arp= *larpp) != NULL) {
          if (!strncasecmp(arp->name,fieldstart,fieldlen))
            parse_error(&ps, &newpig,
                       _("duplicate value for user-defined field `%.*s'"),
                       fieldlen, fieldstart);
          larpp= &arp->next;
        }
        arp= nfmalloc(sizeof(struct arbitraryfield));
        arp->name= nfstrnsave(fieldstart,fieldlen);
        arp->value= nfstrnsave(valuestart,valuelen);
        arp->next= NULL;
        *larpp= arp;
      }
      if (EOF_mmap(dataptr, endptr) || c == '\n' || c == MSDOS_EOF_CHAR) break;
    } /* loop per field */
    if (pdone && donep)
      parse_error(&ps, &newpig,
                  _("several package info entries found, only one allowed"));
    parse_must_have_field(&ps, &newpig, newpig.name, "package name");
    if ((flags & pdb_recordavailable) || newpig.status != stat_notinstalled) {
      parse_ensure_have_field(&ps, &newpig,
                              &newpifp->description, "description");
      parse_ensure_have_field(&ps, &newpig,
                              &newpifp->maintainer, "maintainer");
      if (newpig.status != stat_halfinstalled)
        parse_must_have_field(&ps, &newpig,
                              newpifp->version.version, "version");
    }
    if (flags & pdb_recordavailable)
      parse_ensure_have_field(&ps, &newpig,
                              &newpifp->architecture, "architecture");

    /* Check the Config-Version information:
     * If there is a Config-Version it is definitely to be used, but
     * there shouldn't be one if the package is `installed' (in which case
     * the Version and/or Revision will be copied) or if the package is
     * `not-installed' (in which case there is no Config-Version).
     */
    if (!(flags & pdb_recordavailable)) {
      if (newpig.configversion.version) {
        if (newpig.status == stat_installed || newpig.status == stat_notinstalled)
          parse_error(&ps, &newpig,
                      _("Configured-Version for package with inappropriate Status"));
      } else {
        if (newpig.status == stat_installed) newpig.configversion= newpifp->version;
      }
    }

    if (newpig.trigaw.head &&
        (newpig.status <= stat_configfiles ||
         newpig.status >= stat_triggerspending))
      parse_error(&ps, &newpig,
                  _("package has status %s but triggers are awaited"),
                  statusinfos[newpig.status].name);
    else if (newpig.status == stat_triggersawaited && !newpig.trigaw.head)
      parse_error(&ps, &newpig,
                  _("package has status triggers-awaited but no triggers "
                    "awaited"));

    if (!(newpig.status == stat_triggerspending ||
          newpig.status == stat_triggersawaited) &&
        newpig.trigpend_head)
      parse_error(&ps, &newpig,
                  _("package has status %s but triggers are pending"),
                  statusinfos[newpig.status].name);
    else if (newpig.status == stat_triggerspending && !newpig.trigpend_head)
      parse_error(&ps, &newpig,
                  _("package has status triggers-pending but no triggers "
                    "pending"));

    /* FIXME: There was a bug that could make a not-installed package have
     * conffiles, so we check for them here and remove them (rather than
     * calling it an error, which will do at some point).
     */
    if (!(flags & pdb_recordavailable) &&
        newpig.status == stat_notinstalled &&
        newpifp->conffiles) {
      parse_warn(&ps, &newpig,
                 _("Package which in state not-installed has conffiles, "
                   "forgetting them"));
      newpifp->conffiles= NULL;
    }

    /* XXX: Mark not-installed leftover packages for automatic removal on
     * next database dump. This code can be removed after dpkg 1.16.x, when
     * there's guarantee that no leftover is found on the status file on
     * major distributions. */
    if (!(flags & pdb_recordavailable) &&
        newpig.status == stat_notinstalled &&
        newpig.eflag == eflag_ok &&
        (newpig.want == want_purge ||
         newpig.want == want_deinstall ||
         newpig.want == want_hold)) {
      newpig.want = want_unknown;
    }

    pigp= findpackage(newpig.name);
    pifp= (flags & pdb_recordavailable) ? &pigp->available : &pigp->installed;

    if ((flags & pdb_ignoreolder) &&
	versioncompare(&newpifp->version, &pifp->version) < 0)
      continue;

    /* Copy the priority and section across, but don't overwrite existing
     * values if the pdb_weakclassification flag is set.
     */
    if (newpig.section && *newpig.section &&
        !((flags & pdb_weakclassification) && pigp->section && *pigp->section))
      pigp->section= newpig.section;
    if (newpig.priority != pri_unknown &&
        !((flags & pdb_weakclassification) && pigp->priority != pri_unknown)) {
      pigp->priority= newpig.priority;
      if (newpig.priority == pri_other) pigp->otherpriority= newpig.otherpriority;
    }

    /* Sort out the dependency mess. */
    copy_dependency_links(pigp,&pifp->depends,newpifp->depends,
                          (flags & pdb_recordavailable) ? 1 : 0);
    /* Leave the `depended' pointer alone, we've just gone to such
     * trouble to get it right :-).  The `depends' pointer in
     * pifp was indeed also updated by copy_dependency_links,
     * but since the value was that from newpifp anyway there's
     * no need to copy it back.
     */
    newpifp->depended= pifp->depended;

    /* Copy across data */
    memcpy(pifp,newpifp,sizeof(struct pkginfoperfile));
    if (!(flags & pdb_recordavailable)) {
      pigp->want= newpig.want;
      pigp->eflag= newpig.eflag;
      pigp->status= newpig.status;
      pigp->configversion= newpig.configversion;
      pigp->files= NULL;

      pigp->trigpend_head = newpig.trigpend_head;
      pigp->trigaw = newpig.trigaw;
      for (ta = pigp->trigaw.head; ta; ta = ta->sameaw.next) {
        assert(ta->aw == &newpig);
        ta->aw = pigp;
        /* ->othertrigaw_head is updated by trig_note_aw in *(findpackage())
         * rather than in newpig */
      }

    } else if (!(flags & pdb_ignorefiles)) {
      pigp->files= newpig.files;
    }

    if (donep) *donep= pigp;
    pdone++;
    if (EOF_mmap(dataptr, endptr)) break;
    if (c == '\n')
      ps.lno++;
  }
  if (data != NULL) {
#ifdef USE_MMAP
    munmap(data, st.st_size);
#else
    free(data);
#endif
  }
  free(value);
  pop_cleanup(ehflag_normaltidy);
  if (close(fd)) ohshite(_("failed to close after read: `%.255s'"),filename);
  if (donep && !pdone) ohshit(_("no package information in `%.255s'"),filename);

  if (warncount)
    *warncount = ps.warncount;

  return pdone;
}
Example #14
0
/* Expands %i and %o in the args to the full temp files within the
   temp directory. */
static int expand_args(struct exec_info *info,const char *args_in)
{
  const char *ch=args_in;
  unsigned int size,len;

  info->use_temp_files=0;
  info->keep_temp_files=0;

  if(DBG_EXTPROG)
    log_debug("expanding string \"%s\"\n",args_in);

  size=100;
  info->command=m_alloc(size);
  len=0;
  info->command[0]='\0';

  while(*ch!='\0')
    {
      if(*ch=='%')
	{
	  char *append=NULL;

	  ch++;

	  switch(*ch)
	    {
	    case 'O':
	      info->keep_temp_files=1;
	      /* fall through */

	    case 'o': /* out */
	      if(!info->madedir)
		{
		  if(make_tempdir(info))
		    goto fail;
		}
	      append=info->tempfile_out;
	      info->use_temp_files=1;
	      break;

	    case 'I':
	      info->keep_temp_files=1;
	      /* fall through */

	    case 'i': /* in */
	      if(!info->madedir)
		{
		  if(make_tempdir(info))
		    goto fail;
		}
	      append=info->tempfile_in;
	      info->use_temp_files=1;
	      break;

	    case '%':
	      append="%";
	      break;
	    }

	  if(append)
	    {
	      size_t applen=strlen(append);

	      if(applen+len>size-1)
		{
		  if(applen<100)
		    applen=100;

		  size+=applen;
		  info->command=m_realloc(info->command,size);
		}

	      strcat(info->command,append);
	      len+=strlen(append);
	    }
	}
      else
	{
	  if(len==size-1) /* leave room for the \0 */
	    {
	      size+=100;
	      info->command=m_realloc(info->command,size);
	    }

	  info->command[len++]=*ch;
	  info->command[len]='\0';
	}

      ch++;
    }

  if(DBG_EXTPROG)
    log_debug("args expanded to \"%s\", use %d, keep %d\n",
	      info->command,info->use_temp_files,info->keep_temp_files);

  return 0;

 fail:

  m_free(info->command);
  info->command=NULL;

  return G10ERR_GENERAL;
}
Example #15
0
/* If remotechan, transwindow and transmaxpacket are not know (for a new
 * outgoing connection, with them to be filled on confirmation), they should
 * all be set to 0 */
struct Channel* newchannel(unsigned int remotechan, unsigned char type, 
		unsigned int transwindow, unsigned int transmaxpacket) {

	struct Channel * newchan;
	unsigned int i, j;

	TRACE(("enter newchannel"));
	
	/* first see if we can use existing channels */
	for (i = 0; i < ses.chansize; i++) {
		if (ses.channels[i] == NULL) {
			break;
		}
	}

	/* otherwise extend the list */
	if (i == ses.chansize) {
		if (ses.chansize > MAX_CHANNELS) {
			TRACE(("leave newchannel: max chans reached"));
			return NULL;
		}

		/* extend the channels */
		ses.channels = (struct Channel**)m_realloc(ses.channels,
				(ses.chansize+CHAN_EXTEND_SIZE)*sizeof(struct Channel*));

		ses.chansize += CHAN_EXTEND_SIZE;

		/* set the new channels to null */
		for (j = i; j < ses.chansize; j++) {
			ses.channels[j] = NULL;
		}

	}
	
	newchan = (struct Channel*)m_malloc(sizeof(struct Channel));
	newchan->type = type;
	newchan->index = i;
	newchan->sentclosed = 0;
	newchan->recveof = newchan->transeof = newchan->erreof = 0;

	newchan->remotechan = remotechan;
	newchan->transwindow = transwindow;
	newchan->transmaxpacket = transmaxpacket;
	
	newchan->typedata = NULL;
	newchan->infd = -1;
	newchan->outfd = -1;
	newchan->errfd = -1;
	newchan->initconn = 0;

	newchan->writebuf = buf_new(RECV_MAXWINDOW);
	newchan->recvwindow = RECV_MAXWINDOW;
	newchan->recvmaxpacket = RECV_MAXPACKET;

	ses.channels[i] = newchan;

	TRACE(("leave newchannel"));

	return newchan;
}
Example #16
0
int
commandfd(const char *const *argv)
{
  struct varbuf linevb = VARBUF_INIT;
  const char * pipein;
  const char **newargs = NULL;
  char *ptr, *endptr;
  FILE *in;
  long infd;
  int ret = 0;
  int c, lno, i;
  bool skipchar;

  pipein = *argv++;
  if (pipein == NULL || *argv)
    badusage(_("--%s takes exactly one argument"), cipaction->olong);

  infd = dpkg_options_parse_arg_int(cipaction, pipein);
  in = fdopen(infd, "r");
  if (in == NULL)
    ohshite(_("couldn't open '%i' for stream"), (int)infd);

  for (;;) {
    bool mode = false;
    int argc= 1;
    lno= 0;

    push_error_context();

    do {
      c = getc(in);
      if (c == '\n')
        lno++;
    } while (c != EOF && c_isspace(c));
    if (c == EOF) break;
    if (c == '#') {
      do { c= getc(in); if (c == '\n') lno++; } while (c != EOF && c != '\n');
      continue;
    }
    varbuf_reset(&linevb);
    do {
      varbuf_add_char(&linevb, c);
      c= getc(in);
      if (c == '\n') lno++;

      /* This isn't fully accurate, but overestimating can't hurt. */
      if (c_isspace(c))
        argc++;
    } while (c != EOF && c != '\n');
    if (c == EOF)
      ohshit(_("unexpected end of file before end of line %d"), lno);
    if (!argc) continue;
    varbuf_end_str(&linevb);
    newargs = m_realloc(newargs, sizeof(const char *) * (argc + 1));
    argc= 1;
    ptr= linevb.buf;
    endptr = ptr + linevb.used + 1;
    skipchar = false;
    while(ptr < endptr) {
      if (skipchar) {
	skipchar = false;
      } else if (*ptr == '\\') {
	memmove(ptr, (ptr+1), (linevb.used-(linevb.buf - ptr)-1));
	endptr--;
	skipchar = true;
	continue;
      } else if (c_isspace(*ptr)) {
	if (mode == true) {
	  *ptr = '\0';
	  mode = false;
	}
      } else {
	if (mode == false) {
	  newargs[argc]= ptr;
	  argc++;
	  mode = true;
	}
      }
      ptr++;
    }
    *ptr = '\0';
    newargs[argc++] = NULL;

    /* We strdup() each argument, but never free it, because the
     * error messages contain references back to these strings.
     * Freeing them, and reusing the memory, would make those
     * error messages confusing, to say the least. */
    for(i=1;i<argc;i++)
      if (newargs[i])
        newargs[i] = m_strdup(newargs[i]);

    setaction(NULL, NULL);
    dpkg_options_parse((const char *const **)&newargs, cmdinfos, printforhelp);
    if (!cipaction) badusage(_("need an action option"));

    ret |= cipaction->action(newargs);

    pop_error_context(ehflag_normaltidy);
  }

  return ret;
}
Example #17
0
File: main.c Project: jtniehof/dpkg
void commandfd(const char *const *argv) {
  jmp_buf ejbuf;
  struct varbuf linevb = VARBUF_INIT;
  const char * pipein;
  const char **newargs = NULL;
  char *ptr, *endptr;
  FILE *in;
  unsigned long infd;
  int c, lno, i;
  bool skipchar;
  void (*actionfunction)(const char *const *argv);

  pipein = *argv++;
  if (pipein == NULL)
    badusage(_("--command-fd takes one argument, not zero"));
  if (*argv)
    badusage(_("--command-fd only takes one argument"));
  errno = 0;
  infd = strtoul(pipein, &endptr, 10);
  if (pipein == endptr || *endptr || infd > INT_MAX)
    ohshite(_("invalid integer for --%s: `%.250s'"), "command-fd", pipein);
  if ((in= fdopen(infd, "r")) == NULL)
    ohshite(_("couldn't open `%i' for stream"), (int) infd);

  if (setjmp(ejbuf)) { /* expect warning about possible clobbering of argv */
    error_unwind(ehflag_bombout); exit(2);
  }

  for (;;) {
    bool mode = false;
    int argc= 1;
    lno= 0;
    push_error_handler(&ejbuf, print_error_fatal, NULL);

    do { c= getc(in); if (c == '\n') lno++; } while (c != EOF && isspace(c));
    if (c == EOF) break;
    if (c == '#') {
      do { c= getc(in); if (c == '\n') lno++; } while (c != EOF && c != '\n');
      continue;
    }
    varbufreset(&linevb);
    do {
      varbufaddc(&linevb,c);
      c= getc(in);
      if (c == '\n') lno++;
      if (isspace(c)) argc++;  /* This isn't fully accurate, but overestimating can't hurt. */
    } while (c != EOF && c != '\n');
    if (c == EOF) ohshit(_("unexpected eof before end of line %d"),lno);
    if (!argc) continue;
    varbufaddc(&linevb,0);
    newargs = m_realloc(newargs, sizeof(const char *) * (argc + 1));
    argc= 1;
    ptr= linevb.buf;
    endptr= ptr + linevb.used;
    skipchar = false;
    while(ptr < endptr) {
      if (skipchar) {
	skipchar = false;
      } else if (*ptr == '\\') {
	memmove(ptr, (ptr+1), (linevb.used-(linevb.buf - ptr)-1));
	endptr--;
	skipchar = true;
	continue;
      } else if (isspace(*ptr)) {
	if (mode == true) {
	  *ptr = '\0';
	  mode = false;
	}
      } else {
	if (mode == false) {
	  newargs[argc]= ptr;
	  argc++;
	  mode = true;
	}
      }
      ptr++;
    }
    *ptr = '\0';
    newargs[argc++] = NULL;

/* We strdup each argument, but never free it, because the error messages
 * contain references back to these strings.  Freeing them, and reusing
 * the memory, would make those error messages confusing, to say the
 * least.
 */
    for(i=1;i<argc;i++)
      if (newargs[i])
        newargs[i] = m_strdup(newargs[i]);

    cipaction= NULL;
    myopt((const char *const**)&newargs,cmdinfos);
    if (!cipaction) badusage(_("need an action option"));

    actionfunction= (void (*)(const char* const*))cipaction->farg;
    actionfunction(newargs);
    set_error_display(NULL, NULL);
    error_unwind(ehflag_normaltidy);
  }
}
Example #18
0
ghmm_cseq *ghmm_sgenerate_extensions (ghmm_cmodel * smo, ghmm_cseq * sqd_short,
                                    int seed, int global_len,
                                    sgeneration_mode_t mode)
{
#define CUR_PROC "ghmm_sgenerate_extensions"
  ghmm_cseq *sq = NULL;
  int i, j, t, n, m, len = global_len, short_len, max_short_len = 0, up = 0;
#ifdef bausparkasse
  int tilgphase = 0;
#endif
  /* int *v_path = NULL; */
  double log_p, *initial_distribution, **alpha, *scale, p, sum;
  /* aicj */
  int class = -1;
  int pos;

  /* TEMP */
  if (mode == all_viterbi || mode == viterbi_viterbi || mode == viterbi_all) {
    GHMM_LOG(LCONVERTED, "Error: mode not implemented yet\n");
    goto STOP;
  }

  if (len <= 0)
    /* no global length; model should have a final state */
    len = (int) GHMM_MAX_SEQ_LEN;
  max_short_len = ghmm_cseq_max_len (sqd_short);

  /*---------------alloc-------------------------------------------------*/
  sq = ghmm_cseq_calloc (sqd_short->seq_number);
  if (!sq) {
    GHMM_LOG_QUEUED(LCONVERTED);
    goto STOP;
  }
  ARRAY_CALLOC (initial_distribution, smo->N);
  /* is needed in cfoba_forward() */
  alpha = ighmm_cmatrix_alloc (max_short_len, smo->N);
  if (!alpha) {
    GHMM_LOG_QUEUED(LCONVERTED);
    goto STOP;
  }
  ARRAY_CALLOC (scale, max_short_len);
  ghmm_rng_init ();
  GHMM_RNG_SET (RNG, seed);

  /*---------------main loop over all seqs-------------------------------*/
  for (n = 0; n < sqd_short->seq_number; n++) {
    ARRAY_CALLOC (sq->seq[n], len*(smo->dim));
    short_len = sqd_short->seq_len[n];
    if (len < short_len) {
      GHMM_LOG(LCONVERTED, "Error: given sequence is too long\n");
      goto STOP;
    }
    ghmm_cseq_copy (sq->seq[n], sqd_short->seq[n], short_len);
#ifdef GHMM_OBSOLETE
    sq->seq_label[n] = sqd_short->seq_label[n];
#endif /* GHMM_OBSOLETE */

    /* Initial distribution */
    /* 1. Viterbi-state */
#if 0
    /* wieder aktivieren, wenn ghmm_cmodel_viterbi realisiert */
    if (mode == viterbi_all || mode == viterbi_viterbi) {
      v_path = cviterbi (smo, sqd_short->seq[n], short_len, &log_p);
      if (v_path[short_len - 1] < 0 || v_path[short_len - 1] >= smo->N) {
        GHMM_LOG(LCONVERTED, "Warning:Error: from viterbi()\n");
        sq->seq_len[n] = short_len;
        m_realloc (sq->seq[n], short_len);
        continue;
      }
      m_memset (initial_distribution, 0, smo->N);
      initial_distribution[v_path[short_len - 1]] = 1.0;        /* all other 0 */
      m_free (v_path);
    }
#endif

    /* 2. Initial Distribution ???
       Pi(i) = alpha_t(i)/P(O|lambda) */
    if (mode == all_all || mode == all_viterbi) {
      if (short_len > 0) {
        if (ghmm_cmodel_forward (smo, sqd_short->seq[n], short_len, NULL /* ?? */ ,
                           alpha, scale, &log_p)) {
          GHMM_LOG_QUEUED(LCONVERTED);
          goto STOP;
        }
        sum = 0.0;
        for (i = 0; i < smo->N; i++) {
          /* alpha ist skaliert! */
          initial_distribution[i] = alpha[short_len - 1][i];
          sum += initial_distribution[i];
        }
        /* nicht ok.? auf eins skalieren? */
        for (i = 0; i < smo->N; i++)
          initial_distribution[i] /= sum;
      }
      else {
        for (i = 0; i < smo->N; i++)
          initial_distribution[i] = smo->s[i].pi;
      }
    }
    /* if short_len > 0:
       Initial state == final state from sqd_short; no output here
       else
       choose inittial state according to pi and do output
     */
    p = GHMM_RNG_UNIFORM (RNG);
    sum = 0.0;
    for (i = 0; i < smo->N; i++) {
      sum += initial_distribution[i];
      if (sum >= p)
        break;
    }
    /* error due to incorrect normalization ?? */
    if (i == smo->N) {
      i--;
      while (i > 0 && initial_distribution[i] == 0.0)
        i--;
    }
    t = 0;
    pos = t * smo->dim;
    if (short_len == 0) {
      /* Output in state i */
      p = GHMM_RNG_UNIFORM (RNG);
      sum = 0.0;
      for (m = 0; m < smo->M; m++) {
        sum += smo->s[i].c[m];
        if (sum >= p)
          break;
      }
      /* error due to incorrect normalization ?? */
      if (m == smo->M) {
        m--;
        while (m > 0 && smo->s[i].c[m] == 0.0)
          m--;
      }
      ghmm_cmodel_get_random_var(smo, i, m, sq->seq[n]+pos);

      if (smo->cos == 1) {
        class = 0;
      }
      else {
        if (!smo->class_change->get_class) {
          printf ("ERROR: get_class not initialized\n");
          goto STOP;
        }
        /*printf("1: cos = %d, k = %d, t = %d\n",smo->cos,smo->class_change->k,t);*/
        class = smo->class_change->get_class (smo, sq->seq[n], n, t);
      }


      t++;
      pos += smo->dim;
    }
Example #19
0
static inline void *writeroutput_realloc(xmlwriteroutput *output, void *mem, size_t len)
{
    return m_realloc(output->imalloc, mem, len);
}
Example #20
0
/**
 * Read a deb-split part archive.
 *
 * @return Part info (nfmalloc'd) if was an archive part and we read it,
 *         NULL if it wasn't.
 */
struct partinfo *
read_info(struct dpkg_ar *ar, struct partinfo *ir)
{
  static char *readinfobuf= NULL;
  static size_t readinfobuflen= 0;

  size_t thisilen;
  intmax_t templong;
  char magicbuf[sizeof(DPKG_AR_MAGIC) - 1], *rip, *partnums, *slash;
  const char *err;
  struct ar_hdr arh;
  ssize_t rc;

  rc = fd_read(ar->fd, magicbuf, sizeof(magicbuf));
  if (rc != sizeof(magicbuf)) {
    if (rc < 0)
      ohshite(_("error reading %.250s"), ar->name);
    else
      return NULL;
  }
  if (memcmp(magicbuf, DPKG_AR_MAGIC, sizeof(magicbuf)))
    return NULL;

  rc = fd_read(ar->fd, &arh, sizeof(arh));
  if (rc != sizeof(arh))
    read_fail(rc, ar->name, "ar header");

  dpkg_ar_normalize_name(&arh);

  if (strncmp(arh.ar_name, PARTMAGIC, sizeof(arh.ar_name)) != 0)
    return NULL;
  if (dpkg_ar_member_is_illegal(&arh))
    ohshit(_("file '%.250s' is corrupt - bad magic at end of first header"),
           ar->name);
  thisilen = dpkg_ar_member_get_size(ar, &arh);
  if (thisilen >= readinfobuflen) {
    readinfobuflen = thisilen + 2;
    readinfobuf= m_realloc(readinfobuf,readinfobuflen);
  }
  rc = fd_read(ar->fd, readinfobuf, thisilen + (thisilen & 1));
  if (rc != (ssize_t)(thisilen + (thisilen & 1)))
    read_fail(rc, ar->name, "reading header member");
  if (thisilen & 1) {
    int c = readinfobuf[thisilen + 1];

    if (c != '\n')
      ohshit(_("file '%.250s' is corrupt - bad padding character (code %d)"),
             ar->name, c);
  }
  readinfobuf[thisilen] = '\0';
  if (memchr(readinfobuf,0,thisilen))
    ohshit(_("file '%.250s' is corrupt - nulls in info section"), ar->name);

  ir->filename = ar->name;

  rip= readinfobuf;
  err = deb_version_parse(&ir->fmtversion,
                          nextline(&rip, ar->name, _("format version number")));
  if (err)
    ohshit(_("file '%.250s' has invalid format version: %s"), ar->name, err);
  if (ir->fmtversion.major != 2)
    ohshit(_("file '%.250s' is format version %d.%d; get a newer dpkg-split"),
           ar->name, ir->fmtversion.major, ir->fmtversion.minor);

  ir->package = nfstrsave(nextline(&rip, ar->name, _("package name")));
  ir->version = nfstrsave(nextline(&rip, ar->name, _("package version number")));
  ir->md5sum = nfstrsave(nextline(&rip, ar->name, _("package file MD5 checksum")));
  if (strlen(ir->md5sum) != MD5HASHLEN ||
      strspn(ir->md5sum, "0123456789abcdef") != MD5HASHLEN)
    ohshit(_("file '%.250s' is corrupt - bad MD5 checksum '%.250s'"),
           ar->name, ir->md5sum);

  ir->orglength = parse_intmax(nextline(&rip, ar->name, _("archive total size")),
                               ar->name, _("archive total size"));
  ir->maxpartlen = parse_intmax(nextline(&rip, ar->name, _("archive part offset")),
                                ar->name, _("archive part offset"));

  partnums = nextline(&rip, ar->name, _("archive part numbers"));
  slash= strchr(partnums,'/');
  if (!slash)
    ohshit(_("file '%.250s' is corrupt - no slash between archive part numbers"), ar->name);
  *slash++ = '\0';

  templong = parse_intmax(slash, ar->name, _("number of archive parts"));
  if (templong <= 0 || templong > INT_MAX)
    ohshit(_("file '%.250s' is corrupt - bad number of archive parts"), ar->name);
  ir->maxpartn= templong;
  templong = parse_intmax(partnums, ar->name, _("archive parts number"));
  if (templong <= 0 || templong > ir->maxpartn)
    ohshit(_("file '%.250s' is corrupt - bad archive part number"), ar->name);
  ir->thispartn= templong;

  /* If the package was created with dpkg 1.16.1 or later it will include
   * the architecture. */
  if (*rip != '\0')
    ir->arch = nfstrsave(nextline(&rip, ar->name, _("package architecture")));
  else
    ir->arch = NULL;

  rc = fd_read(ar->fd, &arh, sizeof(arh));
  if (rc != sizeof(arh))
    read_fail(rc, ar->name, "reading data part member ar header");

  dpkg_ar_normalize_name(&arh);

  if (dpkg_ar_member_is_illegal(&arh))
    ohshit(_("file '%.250s' is corrupt - bad magic at end of second header"),
           ar->name);
  if (strncmp(arh.ar_name,"data",4))
    ohshit(_("file '%.250s' is corrupt - second member is not data member"),
           ar->name);

  ir->thispartlen = dpkg_ar_member_get_size(ar, &arh);
  ir->thispartoffset= (ir->thispartn-1)*ir->maxpartlen;

  if (ir->maxpartn != (ir->orglength+ir->maxpartlen-1)/ir->maxpartlen)
    ohshit(_("file '%.250s' is corrupt - wrong number of parts for quoted sizes"),
           ar->name);
  if (ir->thispartlen !=
      (ir->thispartn == ir->maxpartn
       ? ir->orglength - ir->thispartoffset : ir->maxpartlen))
    ohshit(_("file '%.250s' is corrupt - size is wrong for quoted part number"),
           ar->name);

  ir->filesize = (strlen(DPKG_AR_MAGIC) +
                  sizeof(arh) + thisilen + (thisilen & 1) +
                  sizeof(arh) + ir->thispartlen + (ir->thispartlen & 1));

  if (S_ISREG(ar->mode)) {
    /* Don't do this check if it's coming from a pipe or something.  It's
     * only an extra sanity check anyway. */
    if (ar->size < ir->filesize)
      ohshit(_("file '%.250s' is corrupt - too short"), ar->name);
  }

  ir->headerlen = strlen(DPKG_AR_MAGIC) +
                  sizeof(arh) + thisilen + (thisilen & 1) + sizeof(arh);

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

  int i = 0, j = 0;
  int cnt = 0;
  int target = 0, rsize = 0;
  int tsize = 0;

  /* Error Checking */
  if (argc < 2) {
    printf("Usage: %s [-b or -w] input_file\n", argv[0]);
    exit(1);
  }

  load(argv[argc-1]);


  while(cnt != argc-1){
    if(strcmp(argv[cnt], "-b") == 0){
      fit_flag = BEST_FIT;
    }
    else if(strcmp(argv[cnt], "-w") == 0) {
      fit_flag = WORST_FIT;
    } else if(strcmp(argv[cnt], "-np") == 0) {
      print_flag =0;
    }

    cnt++;
  }

  for(i = 0 ; i < query_cnt ; i++) {

    switch(query_list[i].type) {
      case 'm':
      alloc_list[j] = m_malloc(strlen(query_list[i].val) + 1);
      strcpy(alloc_list[j], query_list[i].val);
      j++;
      break;
      case 'f':
      target = atoi(query_list[i].val);
      m_free(alloc_list[target]);
      break;
      case 'a':
      sscanf(query_list[i].val, "%d %d", &target, &rsize);
      tsize = strlen(alloc_list[target]) + rsize;
      m_realloc(alloc_list[target], tsize);
      break;
      case 'd':
      sscanf(query_list[i].val, "%d %d", &target, &rsize);
      tsize = strlen(alloc_list[target]) - rsize;
      m_realloc(alloc_list[target], tsize);
      *(alloc_list[target] + tsize) = '\0';
      break;
      case 'e':
      alloc_list[j++] = m_malloc(atoi(query_list[i].val));
      break;
    }

    print_block_list();
  }

  return 0;
}
Example #22
0
static void
slow_gatherer_windowsNT( void (*add)(const void*, size_t, int), int requester )
{
    static int is_initialized = 0;
    static NETSTATISTICSGET pNetStatisticsGet = NULL;
    static NETAPIBUFFERSIZE pNetApiBufferSize = NULL;
    static NETAPIBUFFERFREE pNetApiBufferFree = NULL;
    static int is_workstation = 1;

    static int cbPerfData = PERFORMANCE_BUFFER_SIZE;
    PERF_DATA_BLOCK *pPerfData;
    HANDLE hDevice, hNetAPI32 = NULL;
    DWORD dwSize, status;
    int nDrive;

    if ( !is_initialized ) {
	HKEY hKey;

	if ( debug_me )
	    log_debug ("rndw32#slow_gatherer_nt: init toolkit\n" );
	/* Find out whether this is an NT server or workstation if necessary */
	if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
			  "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
			  0, KEY_READ, &hKey) == ERROR_SUCCESS) {
	    BYTE szValue[32];
	    dwSize = sizeof (szValue);

	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: check product options\n" );
	    status = RegQueryValueEx (hKey, "ProductType", 0, NULL,
				      szValue, &dwSize);
	    if (status == ERROR_SUCCESS && stricmp (szValue, "WinNT")) {
		/* Note: There are (at least) three cases for ProductType:
		 * WinNT = NT Workstation, ServerNT = NT Server, LanmanNT =
		 * NT Server acting as a Domain Controller */
		is_workstation = 0;
		if ( debug_me )
		    log_debug ("rndw32: this is a NT server\n");
	    }
	    RegCloseKey (hKey);
	}

	/* Initialize the NetAPI32 function pointers if necessary */
	if ( (hNetAPI32 = LoadLibrary ("NETAPI32.DLL")) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: netapi32 loaded\n" );
	    pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
						       "NetStatisticsGet");
	    pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
						       "NetApiBufferSize");
	    pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
						       "NetApiBufferFree");

	    if ( !pNetStatisticsGet
		 || !pNetApiBufferSize || !pNetApiBufferFree ) {
		FreeLibrary (hNetAPI32);
		hNetAPI32 = NULL;
		g10_log_debug ("rndw32: No NETAPI found\n" );
	    }
	}

	is_initialized = 1;
    }

    /* Get network statistics.	Note: Both NT Workstation and NT Server by
     * default will be running both the workstation and server services.  The
     * heuristic below is probably useful though on the assumption that the
     * majority of the network traffic will be via the appropriate service.
     * In any case the network statistics return almost no randomness */
    {	LPBYTE lpBuffer;
	if (hNetAPI32 && !pNetStatisticsGet (NULL,
			   is_workstation ? L"LanmanWorkstation" :
			   L"LanmanServer", 0, 0, &lpBuffer) ) {
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get netstats\n" );
	    pNetApiBufferSize (lpBuffer, &dwSize);
	    (*add) ( lpBuffer, dwSize,requester );
	    pNetApiBufferFree (lpBuffer);
	}
    }

    /* Get disk I/O statistics for all the hard drives */
    for (nDrive = 0;; nDrive++) {
	DISK_PERFORMANCE diskPerformance;
	char szDevice[50];

	/* Check whether we can access this device */
	sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
	hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
			      NULL, OPEN_EXISTING, 0, NULL);
	if (hDevice == INVALID_HANDLE_VALUE)
	    break;

	/* Note: This only works if you have turned on the disk performance
	 * counters with 'diskperf -y'.  These counters are off by default */
	if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
			     &diskPerformance, sizeof (DISK_PERFORMANCE),
			     &dwSize, NULL))
	{
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: iostats drive %d\n",
								  nDrive );
	    (*add) ( &diskPerformance, dwSize, requester );
	}
	else {
	    log_info ("NOTE: you should run 'diskperf -y' "
		      "to enable the disk statistics\n");
	}
	CloseHandle (hDevice);
    }

  #if 0 /* we don't need this in GnuPG  */
    /* Wait for any async keyset driver binding to complete.  You may be
     * wondering what this call is doing here... the reason it's necessary is
     * because RegQueryValueEx() will hang indefinitely if the async driver
     * bind is in progress.  The problem occurs in the dynamic loading and
     * linking of driver DLL's, which work as follows:
     *
     * hDriver = LoadLibrary( DRIVERNAME );
     * pFunction1 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC1 );
     * pFunction2 = ( TYPE_FUNC1 ) GetProcAddress( hDriver, NAME_FUNC2 );
     *
     * If RegQueryValueEx() is called while the GetProcAddress()'s are in
     * progress, it will hang indefinitely.  This is probably due to some
     * synchronisation problem in the NT kernel where the GetProcAddress()
     * calls affect something like a module reference count or function
     * reference count while RegQueryValueEx() is trying to take a snapshot
     * of the statistics, which include the reference counts.  Because of
     * this, we have to wait until any async driver bind has completed
     * before we can call RegQueryValueEx() */
    waitSemaphore (SEMAPHORE_DRIVERBIND);
  #endif

    /* Get information from the system performance counters.  This can take
     * a few seconds to do.  In some environments the call to
     * RegQueryValueEx() can produce an access violation at some random time
     * in the future, adding a short delay after the following code block
     * makes the problem go away.  This problem is extremely difficult to
     * reproduce, I haven't been able to get it to occur despite running it
     * on a number of machines.  The best explanation for the problem is that
     * on the machine where it did occur, it was caused by an external driver
     * or other program which adds its own values under the
     * HKEY_PERFORMANCE_DATA key.  The NT kernel calls the required external
     * modules to map in the data, if there's a synchronisation problem the
     * external module would write its data at an inappropriate moment,
     * causing the access violation.  A low-level memory checker indicated
     * that ExpandEnvironmentStrings() in KERNEL32.DLL, called an
     * interminable number of calls down inside RegQueryValueEx(), was
     * overwriting memory (it wrote twice the allocated size of a buffer to a
     * buffer allocated by the NT kernel).  This may be what's causing the
     * problem, but since it's in the kernel there isn't much which can be
     * done.
     *
     * In addition to these problems the code in RegQueryValueEx() which
     * estimates the amount of memory required to return the performance
     * counter information isn't very accurate, since it always returns a
     * worst-case estimate which is usually nowhere near the actual amount
     * required.  For example it may report that 128K of memory is required,
     * but only return 64K of data */
    {	pPerfData =  m_alloc (cbPerfData);
	for (;;) {
	    dwSize = cbPerfData;
	    if ( debug_me )
		log_debug ("rndw32#slow_gatherer_nt: get perf data\n" );
	    status = RegQueryValueEx (HKEY_PERFORMANCE_DATA, "Global", NULL,
				      NULL, (LPBYTE) pPerfData, &dwSize);
	    if (status == ERROR_SUCCESS) {
		if (!memcmp (pPerfData->Signature, L"PERF", 8)) {
		    (*add) ( pPerfData, dwSize, requester );
		}
		else
		    g10_log_debug ( "rndw32: no PERF signature\n");
		break;
	    }
	    else if (status == ERROR_MORE_DATA) {
		cbPerfData += PERFORMANCE_BUFFER_STEP;
		pPerfData = m_realloc (pPerfData, cbPerfData);
	    }
	    else {
		g10_log_debug ( "rndw32: get performance data problem\n");
		break;
	    }
	}
	m_free (pPerfData);
    }
    /* Although this isn't documented in the Win32 API docs, it's necessary
       to explicitly close the HKEY_PERFORMANCE_DATA key after use (it's
       implicitly opened on the first call to RegQueryValueEx()).  If this
       isn't done then any system components which provide performance data
       can't be removed or changed while the handle remains active */
    RegCloseKey (HKEY_PERFORMANCE_DATA);
}