Example #1
0
  }
  t->elms[t->noelems++] = *elm;
}

void tableFree(Table *t)
{
  mem_free(t->elms);
  mem_free(t);
}

/* EXPORT */

void export(bdd_manager *bddm, unsigned p, Table *table) 
{
  if (!bdd_mark(bddm,p)) {
    BddNode *e = (BddNode *) mem_alloc(sizeof(BddNode));
    if (bdd_is_leaf(bddm,p)) {
      e->idx = -1;
      e->lo = bdd_leaf_value(bddm, p);
      e->hi = 0;
      tableInsert(table, e);
      bdd_set_mark(bddm,p,table->noelems); /* table index+1 put in mark */
    }
    else {
      e->idx = bdd_ifindex(bddm,p);
      e->lo = bdd_else(bddm,p);
      e->hi = bdd_then(bddm,p);
      tableInsert(table, e);
      bdd_set_mark(bddm,p,table->noelems); /* table index+1 put in mark */
      export(bddm, bdd_then(bddm,p), table);
      export(bddm, bdd_else(bddm,p), table);
Example #2
0
/**
 * create a fixed pool of relocatable objects.
 *
 * return (opaque) pointer to the newly created pool, or NULL if
 * there was insufficient memory.
 *
 * @param size     Size of each sub-object
 * @param num      Number of sub-objects
 * @param align    Alignment of sub-objects
 * @param flags    Flags
 * @param name     A name for this pool
 * @param overhead Allocate additional space in the non-moveable heap
 *
 * If flags include VC_POOL_FLAGS_SUBDIVISIBLE we get a single relocatable
 * memory block large enough for all 'n' objects; it can either be used
 * as a single block, or divided up into 'n' of them.
 * -------------------------------------------------------------------- */
VC_POOL_T *
vc_pool_create( size_t size, uint32_t num, uint32_t align, VC_POOL_FLAGS_T flags, const char *name, uint32_t overhead_size )
{
   int i;
   int mem_flags = MEM_FLAG_NO_INIT;

   vcos_assert(size != 0);
   vcos_assert(num != 0);
   vcos_assert(name);

   overhead_size = (overhead_size+OVERHEAD_ALIGN-1) & ~(OVERHEAD_ALIGN-1);

   // allocate and zero main struct
   int alloc_len = sizeof(VC_POOL_T) + num * sizeof(VC_POOL_OBJECT_T) + num * overhead_size;
   VC_POOL_T *pool = (VC_POOL_T*)rtos_prioritymalloc( alloc_len,
                                          RTOS_ALIGN_DEFAULT,
                                          RTOS_PRIORITY_UNIMPORTANT,
                                          "vc_pool" );
   if ( !pool ) return NULL; // failed to allocate pool
   memset( pool, 0, alloc_len );

   // array of pool objects
   pool->object = (VC_POOL_OBJECT_T *)((unsigned char *)pool + sizeof(VC_POOL_T));

   // initialise
   pool->magic = POOL_MAGIC;
   pool->latch = rtos_latch_unlocked();

   if ( flags & VC_POOL_FLAGS_DIRECT )
      mem_flags |= MEM_FLAG_DIRECT;

   if ( flags & VC_POOL_FLAGS_COHERENT )
      mem_flags |= MEM_FLAG_COHERENT;

   if ( flags & VC_POOL_FLAGS_HINT_PERMALOCK )
      mem_flags |= MEM_FLAG_HINT_PERMALOCK;

   if ( align == 0 ) align = 32; // minimum 256-bit aligned
   vcos_assert( _count(align) == 1 ); // must be power of 2
   pool->alignment = align;
   pool->overhead = (uint8_t*)(pool+1) + num*sizeof(VC_POOL_OBJECT_T);
   pool->overhead_size = overhead_size;
   pool->name = name;

   pool->max_objects = num;
   pool->pool_flags = flags;

   if ( flags & VC_POOL_FLAGS_SUBDIVISIBLE ) {

      // a single mem_handle, shared between objects
      uint32_t rounded_size = (size + align - 1) & ~(align - 1);
      pool->mem = mem_alloc( rounded_size, align, (MEM_FLAG_T)mem_flags, name );
      if ( pool->mem == MEM_INVALID_HANDLE ) {
         // out of memory... clean up nicely and return error
         rtos_priorityfree( pool );
         return NULL;
      }

      pool->nobjects = 0;
      pool->object_size = 0;
      pool->max_object_size = rounded_size;
   } else {

      // bunch of individual objects

      for (i=0; i<num; i++) {
         MEM_HANDLE_T mem = mem_alloc( size, align, (MEM_FLAG_T)mem_flags, name );
         pool->object[i].mem = mem;
         // all ->offset fields are 0 from the previous memset
         if ( mem == MEM_INVALID_HANDLE ) {
            // out of memory... clean up nicely and return error
            while (i > 0)
               mem_release( pool->object[--i].mem );
            rtos_priorityfree( pool );
            return NULL; // failed to allocate pool
         }
         // pointer to 'overhead' memory for this entry
         pool->object[i].overhead = pool->overhead + i*pool->overhead_size;
      }

      pool->mem = MEM_INVALID_HANDLE;
      pool->nobjects = num;
      pool->object_size = size;
      pool->max_object_size = size;
   }

   create_event( pool );

   // link into global list
   rtos_latch_get(&pool_list_latch);
   pool->next = vc_pool_list;
   vc_pool_list = pool;
   rtos_latch_put(&pool_list_latch);

   // done
   return pool;
}
Example #3
0
static int auloop_reset(struct audio_loop *al)
{
	struct auplay_prm auplay_prm;
	struct ausrc_prm ausrc_prm;
	const struct config *cfg = conf_config();
	int err;

	if (!cfg)
		return ENOENT;

	/* Optional audio codec */
	if (str_isset(aucodec))
		start_codec(al, aucodec);

	/* audio player/source must be stopped first */
	al->auplay = mem_deref(al->auplay);
	al->ausrc  = mem_deref(al->ausrc);

	al->sampv  = mem_deref(al->sampv);
	al->ab     = mem_deref(al->ab);

	al->srate = configv[al->index].srate;
	al->ch    = configv[al->index].ch;

	if (str_isset(aucodec)) {
		al->sampc = al->srate * al->ch * PTIME / 1000;
		al->sampv = mem_alloc(al->sampc * 2, NULL);
		if (!al->sampv)
			return ENOMEM;
	}

	info("Audio-loop: %uHz, %dch\n", al->srate, al->ch);

	err = aubuf_alloc(&al->ab, 320, 0);
	if (err)
		return err;

	auplay_prm.srate      = al->srate;
	auplay_prm.ch         = al->ch;
	auplay_prm.ptime      = PTIME;
	err = auplay_alloc(&al->auplay, cfg->audio.play_mod, &auplay_prm,
			   cfg->audio.play_dev, write_handler, al);
	if (err) {
		warning("auloop: auplay %s,%s failed: %m\n",
			cfg->audio.play_mod, cfg->audio.play_dev,
			err);
		return err;
	}

	ausrc_prm.srate      = al->srate;
	ausrc_prm.ch         = al->ch;
	ausrc_prm.ptime      = PTIME;
	err = ausrc_alloc(&al->ausrc, NULL, cfg->audio.src_mod,
			  &ausrc_prm, cfg->audio.src_dev,
			  read_handler, error_handler, al);
	if (err) {
		warning("auloop: ausrc %s,%s failed: %m\n", cfg->audio.src_mod,
			cfg->audio.src_dev, err);
		return err;
	}

	return err;
}
Example #4
0
void display_table_frames(struct table *t, int x, int y)
{
	signed char *fh, *fv;
	int i, j;
	int cx, cy;
	if ((unsigned)t->x > MAXINT) overalloc();
	if ((unsigned)t->y > MAXINT) overalloc();
	if (((unsigned)t->x + 2) * ((unsigned)t->y + 2) / ((unsigned)t->x + 2) != ((unsigned)t->y + 2)) overalloc();
	if (((unsigned)t->x + 2) * ((unsigned)t->y + 2) > MAXINT) overalloc();
	fh = mem_alloc((t->x + 2) * (t->y + 1));
	memset(fh, -1, (t->x + 2) * (t->y + 1));
	fv = mem_alloc((t->x + 1) * (t->y + 2));
	memset(fv, -1, (t->x + 1) * (t->y + 2));
#ifndef DEBUG
#define H_LINE_X(xx, yy) fh[(xx) + 1 + (t->x + 2) * (yy)]
#define V_LINE_X(xx, yy) fv[(yy) + 1 + (t->y + 2) * (xx)]
#else
#define H_LINE_X(xx, yy) (*(xx < -1 || xx > t->x + 1 || yy < 0 || yy > t->y ? (signed char *)NULL : &fh[(xx) + 1 + (t->x + 2) * (yy)]))
#define V_LINE_X(xx, yy) (*(xx < 0 || xx > t->x || yy < -1 || yy > t->y + 1 ? (signed char *)NULL : &fv[(yy) + 1 + (t->y + 2) * (xx)]))
#endif
#define H_LINE(xx, yy) (H_LINE_X((xx), (yy)) == -1 ? 0 : H_LINE_X((xx), (yy)))
#define V_LINE(xx, yy) (V_LINE_X((xx), (yy)) == -1 ? 0 : V_LINE_X((xx), (yy)))
	for (j = 0; j < t->y; j++) for (i = 0; i < t->x; i++) {
		int x, y;
		int xsp, ysp;
		struct table_cell *cell = CELL(t, i, j);
		if (!cell->used || cell->spanned) continue;
		if ((xsp = cell->colspan) == 0) xsp = t->x - i;
		if ((ysp = cell->rowspan) == 0) ysp = t->y - j;
		if (t->rules != R_NONE && t->rules != R_COLS) for (x = 0; x < xsp; x++) {H_LINE_X(i + x, j) = t->cellsp; H_LINE_X(i + x, j + ysp) = t->cellsp;}
		if (t->rules != R_NONE && t->rules != R_ROWS) for (y = 0; y < ysp; y++) {V_LINE_X(i, j + y) = t->cellsp; V_LINE_X(i + xsp, j + y) = t->cellsp;}
	}
	if (t->rules == R_GROUPS) {
		for (i = 1; i < t->x; i++) {
			if (/*i < t->xc &&*/ t->xcols[i]) continue;
			for (j = 0; j < t->y; j++) V_LINE_X(i, j) = 0;
		}
		for (j = 1; j < t->y; j++) {
			for (i = 0; i < t->x; i++) if (CELL(t, i, j)->group) goto c;
			for (i = 0; i < t->x; i++) H_LINE_X(i, j) = 0;
			c:;
		}
	}
	for (i = 0; i < t->x; i++) {
		H_LINE_X(i, 0) = t->border * !!(t->frame & F_ABOVE);
		H_LINE_X(i, t->y) = t->border * !!(t->frame & F_BELOW);
	}
	for (j = 0; j < t->y; j++) {
		V_LINE_X(0, j) = t->border * !!(t->frame & F_LHS);
		V_LINE_X(t->x, j) = t->border * !!(t->frame & F_RHS);
	}

	cy = y;
	for (j = 0; j <= t->y; j++) {
		cx = x;
		if ((j > 0 && j < t->y && get_hline_width(t, j) >= 0) || (j == 0 && t->border && (t->frame & F_ABOVE)) || (j == t->y && t->border && (t->frame & F_BELOW))) {
			for (i = 0; i < t->x; i++) {
				int w;
				if (i > 0) w = get_vline_width(t, i);
				else w = t->border && (t->frame & F_LHS) ? t->border : -1;
				if (w >= 0) {
					draw_frame_point(cx, cy, i, j);
					if (j < t->y) draw_frame_vline(cx, cy + 1, t->r_heights[j], i, j);
					cx++;
				}
				w = t->w_c[i];
				draw_frame_hline(cx, cy, w, i, j);
				cx += w;
			}
			if (t->border && (t->frame & F_RHS)) {
				draw_frame_point(cx, cy, i, j);
				if (j < t->y) draw_frame_vline(cx, cy + 1, t->r_heights[j], i, j);
				cx++;
			}
			cy++;
		} else if (j < t->y) {
			for (i = 0; i <= t->x; i++) {
				if ((i > 0 && i < t->x && get_vline_width(t, i) >= 0) || (i == 0 && t->border && (t->frame & F_LHS)) || (i == t->x && t->border && (t->frame & F_RHS))) {
					draw_frame_vline(cx, cy, t->r_heights[j], i, j);
					cx++;
				}
				if (i < t->x) cx += t->w_c[i];
			}
		}
		if (j < t->y) cy += t->r_heights[j];
		/*for (cyy = cy1; cyy < cy; cyy++) xxpand_line(t->p, cyy, cx - 1);*/
	}
	mem_free(fh);
	mem_free(fv);
}
Example #5
0
File: main.c Project: Aleyr/nesemu2
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	int ret;
	char *p,*p2,*cmdline;

	memset(configfilename,0,1024);
	MyRegisterClass(hInstance);
	if(InitInstance(hInstance,nCmdShow) == 0) {
		return(FALSE);
	}

	log_sethook(console_loghook);

	//make the exe path variable
	GetModuleFileName(hInstance,exepath,1024);
	if((p = strrchr(exepath,PATH_SEPERATOR)) != 0) {
		*p = 0;
	}

	if(emu_init() != 0)
		return(FALSE);

   ShowWindow(hWnd,nCmdShow);
   UpdateWindow(hWnd);

	p = cmdline = mem_strdup(lpCmdLine);
	if(*p == '\"') {
		p++;
		if((p2 = strchr(p,'\"')) != 0)
			*p2 = 0;
	}

	if(strcmp(p,"") != 0) {
		char *filename;

		//it is a relative path, make full path name
		if(p[1] != ':') {
			char *cwd = system_getcwd();
			int len = strlen(p) + strlen(cwd) + 2;

			filename = (char*)mem_alloc(len);
			sprintf(filename,"%s\\%s",cwd,p);
		}

		//already full path name
		else {
			filename = mem_strdup(p);
		}

		log_printf("trying lpcmdline as filename (%s)...\n",filename);
		loadrom(filename);
		mem_free(filename);
	}

	mem_free(cmdline);

	ret = (emu_mainloop() == 0) ? TRUE : FALSE;

	emu_kill();

	return(emu_exit(ret));
}
Example #6
0
void format_table(unsigned char *attr, unsigned char *html, unsigned char *eof, unsigned char **end, void *f)
{
	struct part *p = f;
	int border, cellsp, vcellpd, cellpd, align;
	int frame, rules, width, wf;
	struct rgb bgcolor;
	struct table *t;
	char *al;
	int cye;
	int x;
	int i;
	/*int llm = last_link_to_move;*/
	struct s_e *bad_html;
	int bad_html_n;
	struct node *n, *nn;
	int cpd_pass, cpd_width, cpd_last;
	/*if (!p->data) {
		debug("nested tables not supported");
		return;
	}*/
	table_level++;
	memcpy(&bgcolor, &par_format.bgcolor, sizeof(struct rgb));
	get_bgcolor(attr, &bgcolor);
	if ((border = get_num(attr, "border")) == -1) border = has_attr(attr, "border") || has_attr(attr, "rules") || has_attr(attr, "frame");
	/*if (!border) border = 1;*/

	if ((cellsp = get_num(attr, "cellspacing")) == -1) cellsp = 1;
	if ((cellpd = get_num(attr, "cellpadding")) == -1) {
		vcellpd = 0;
		cellpd = !!border;
	} else {
		vcellpd = cellpd >= HTML_CHAR_HEIGHT / 2 + 1;
		cellpd = cellpd >= HTML_CHAR_WIDTH / 2 + 1;
	}
	if (!border) cellsp = 0;
	else if (!cellsp) cellsp = 1;
	if (border > 2) border = 2;
	if (cellsp > 2) cellsp = 2;
	align = par_format.align;
	if (align == AL_NO || align == AL_BLOCK) align = AL_LEFT;
	if ((al = get_attr_val(attr, "align"))) {
		if (!strcasecmp(al, "left")) align = AL_LEFT;
		if (!strcasecmp(al, "center")) align = AL_CENTER;
		if (!strcasecmp(al, "right")) align = AL_RIGHT;
		mem_free(al);
	}
	frame = F_BOX;
	if ((al = get_attr_val(attr, "frame"))) {
		if (!strcasecmp(al, "void")) frame = F_VOID;
		if (!strcasecmp(al, "above")) frame = F_ABOVE;
		if (!strcasecmp(al, "below")) frame = F_BELOW;
		if (!strcasecmp(al, "hsides")) frame = F_HSIDES;
		if (!strcasecmp(al, "vsides")) frame = F_VSIDES;
		if (!strcasecmp(al, "lhs")) frame = F_LHS;
		if (!strcasecmp(al, "rhs")) frame = F_RHS;
		if (!strcasecmp(al, "box")) frame = F_BOX;
		if (!strcasecmp(al, "border")) frame = F_BOX;
		mem_free(al);
	}
	rules = border ? R_ALL : R_NONE;
	if ((al = get_attr_val(attr, "rules"))) {
		if (!strcasecmp(al, "none")) rules = R_NONE;
		if (!strcasecmp(al, "groups")) rules = R_GROUPS;
		if (!strcasecmp(al, "rows")) rules = R_ROWS;
		if (!strcasecmp(al, "cols")) rules = R_COLS;
		if (!strcasecmp(al, "all")) rules = R_ALL;
		mem_free(al);
	}
	if (!border) frame = F_VOID;
	wf = 0;
	if ((width = get_width(attr, "width", p->data || p->xp)) == -1) {
		width = par_format.width - par_format.leftmargin - par_format.rightmargin;
		if (width < 0) width = 0;
		wf = 1;
	}
	if (!(t = parse_table(html, eof, end, &bgcolor, p->data || p->xp, &bad_html, &bad_html_n))) {
		mem_free(bad_html);
		goto ret0;
	}
	for (i = 0; i < bad_html_n; i++) {
		while (bad_html[i].s < bad_html[i].e && WHITECHAR(*bad_html[i].s)) bad_html[i].s++;
		while (bad_html[i].s < bad_html[i].e && WHITECHAR(bad_html[i].e[-1])) bad_html[i].e--;
		if (bad_html[i].s < bad_html[i].e) parse_html(bad_html[i].s, bad_html[i].e, put_chars_f, line_break_f, special_f, p, NULL);
	}
	mem_free(bad_html);
	html_stack_dup();
	html_top.dontkill = 1;
	par_format.align = AL_LEFT;
	t->p = p;
	t->border = border;
	t->cellpd = cellpd;
	t->vcellpd = vcellpd;
	t->cellsp = cellsp;
	t->frame = frame;
	t->rules = rules;
	t->width = width;
	t->wf = wf;
	cpd_pass = 0;
	cpd_last = t->cellpd;
	cpd_width = 0;	/* not needed, but let the warning go away */
	again:
	get_cell_widths(t);
	if (get_column_widths(t)) goto ret2;
	get_table_width(t);
	if (!p->data && !p->xp) {
		if (!wf && t->max_t > width) t->max_t = width;
		if (t->max_t < t->min_t) t->max_t = t->min_t;
		if (t->max_t + par_format.leftmargin + par_format.rightmargin > p->xmax) p->xmax = t->max_t + par_format.leftmargin + par_format.rightmargin;
		if (t->min_t + par_format.leftmargin + par_format.rightmargin > p->x) p->x = t->min_t + par_format.leftmargin + par_format.rightmargin;
		goto ret2;
	}
	if (!cpd_pass && t->min_t > width && t->cellpd) {
		t->cellpd = 0;
		cpd_pass = 1;
		cpd_width = t->min_t;
		goto again;
	}
	if (cpd_pass == 1 && t->min_t > cpd_width) {
		t->cellpd = cpd_last;
		cpd_pass = 2;
		goto again;
	}
	/*debug("%d %d %d", t->min_t, t->max_t, width);*/
	if (t->min_t >= width) distribute_widths(t, t->min_t);
	else if (t->max_t < width && wf) distribute_widths(t, t->max_t);
	else distribute_widths(t, width);
	if (!p->data && p->xp == 1) {
		int ww = t->rw + par_format.leftmargin + par_format.rightmargin;
		if (ww > par_format.width) ww = par_format.width;
		if (ww < t->rw) ww = t->rw;
		if (ww > p->x) p->x = ww;
		p->cy += t->rh;
		goto ret2;
	}
#ifdef HTML_TABLE_2ND_PASS
	check_table_widths(t);
#endif
	x = par_format.leftmargin;
	if (align == AL_CENTER) x = (par_format.width + par_format.leftmargin - par_format.rightmargin - t->rw) / 2;
	if (align == AL_RIGHT) x = par_format.width - par_format.rightmargin - t->rw;
	if (x + t->rw > par_format.width) x = par_format.width - t->rw;
	if (x < 0) x = 0;
	/*display_table(t, x, p->cy, &cye);*/
	get_table_heights(t);
	if (!p->data) {
		if (t->rw + par_format.leftmargin + par_format.rightmargin > p->x) p->x = t->rw + par_format.leftmargin + par_format.rightmargin;
		p->cy += t->rh;
		goto ret2;
	}
	n = p->data->nodes.next;
	n->yw = p->yp - n->y + p->cy;
	display_complicated_table(t, x, p->cy, &cye);
	display_table_frames(t, x, p->cy);
	nn = mem_alloc(sizeof(struct node));
	nn->x = n->x;
	nn->y = p->yp + cye;
	nn->xw = n->xw;
	add_to_list(p->data->nodes, nn);
	/*sdbg(p->data);*/
	/*for (y = p->cy; y < cye; y++) {
		last_link_to_move = llm;
		align_line(p, y);
	}*/
	/*if (p->cy + t->rh != cye) internal("size does not match; 1:%d, 2:%d", p->cy + t->rh, cye);*/
	p->cy = cye;
	p->cx = -1;

	ret2:
	p->link_num = t->link_num;
	if (p->cy > p->y) p->y = p->cy;
	/*ret1:*/
	free_table(t);
	kill_html_stack_item(&html_top);
	ret0:
	/*ret:*/
	table_level--;
	if (!table_level) free_table_cache();
}
Example #7
0
void distribute_widths(struct table *t, int width)
{
	int i;
	int d = width - t->min_t;
	int om = 0;
	char *u;
	int *w, *mx;
	int mmax_c = 0;
	if (!t->x) return;
	if (d < 0) {
		/*internal("too small width %d, required %d", width, t->min_t);*/
		return;
	}
	for (i = 0; i < t->x; i++) if (t->max_c[i] > mmax_c) mmax_c = t->max_c[i];
	memcpy(t->w_c, t->min_c, t->x * sizeof(int));
	t->rw = width;
	if ((unsigned)t->x > MAXINT / sizeof(int)) overalloc();
	u = mem_alloc(t->x);
	w = mem_alloc(t->x * sizeof(int));
	mx = mem_alloc(t->x * sizeof(int));
	while (d) {
		int mss, mii;
		int p = 0;
		int wq;
		int dd;
		memset(w, 0, t->x * sizeof(int));
		memset(mx, 0, t->x * sizeof(int));
		for (i = 0; i < t->x; i++) {
			switch (om) {
				case 0:
					if (t->w_c[i] < t->xcols[i]) {
						w[i] = 1, mx[i] = (t->xcols[i] > t->max_c[i] ? t->max_c[i] : t->xcols[i]) - t->w_c[i];
						if (mx[i] <= 0) w[i] = 0;
					}
					break;
				case 1:
					if (t->xcols[i] < -1 && t->xcols[i] != -2) {
						w[i] = t->xcols[i] <= -2 ? -2 - t->xcols[i] : 1;
						mx[i] = t->max_c[i] - t->w_c[i];
						if (mx[i] <= 0) w[i] = 0;
					}
					break;
				case 2:
				case 3:
					if (t->w_c[i] < t->max_c[i] && (om == 3 || t->xcols[i] == W_AUTO)) {
						mx[i] = t->max_c[i] - t->w_c[i];
						if (mmax_c) w[i] = 5 + t->max_c[i] * 10 / mmax_c;
						else w[i] = 1;
					}
					break;
				case 4:
					if (t->xcols[i] >= 0) {
						w[i] = 1, mx[i] = t->xcols[i] - t->w_c[i];
						if (mx[i] <= 0) w[i] = 0;
					}
					break;
				case 5:
					if (t->xcols[i] < 0) w[i] = t->xcols[i] <= -2 ? -2 - t->xcols[i] : 1, mx[i] = MAXINT;
					break;
				case 6:
					w[i] = 1, mx[i] = MAXINT;
					break;
				default:
					/*internal("could not expand table");*/
					goto end2;
			}
			p += w[i];
		}
		if (!p) {
			om++;
			continue;
		}
		wq = 0;
		if (u) memset(u, 0, t->x);
		dd = d;
		a:
		mss = 0; mii = -1;
		for (i = 0; i < t->x; i++) if (w[i]) {
			int ss;
			if (u && u[i]) continue;
			if (!(ss = dd * w[i] / p)) ss = 1;
			if (ss > mx[i]) ss = mx[i];
			if (ss > mss) mss = ss, mii = i;
		}
		if (mii != -1) {
			int q = t->w_c[mii];
			if (u) u[mii] = 1;
			t->w_c[mii] += mss;
			d -= t->w_c[mii] - q;
			while (d < 0) t->w_c[mii]--, d++;
			if (t->w_c[mii] < q) {
				/*internal("shrinking cell");*/
				t->w_c[mii] = q;
			}
			wq = 1;
			if (d) goto a;
		} else if (!wq) om++;
	}
	end2:
	mem_free(mx);
	mem_free(w);
	if (u) mem_free(u);
}
static s64 device_gekko_io_readbytes(io_channel dev, s64 offset, s64 count, void *buf)
{
    //ext2_log_trace("dev %p, offset %lli, count %lli\n", dev, offset, count);
    // Get the device driver descriptor
    gekko_fd *fd = DEV_FD(dev);
    if (!fd) {
        errno = EBADF;
        return -1;
    }

    // Get the device interface
    const DISC_INTERFACE* interface = fd->interface;
    if (!interface) {
        errno = ENODEV;
        return -1;
    }

    if(offset < 0)
    {
        errno = EROFS;
        return -1;
    }

    if(!count)
        return 0;

    sec_t sec_start = (sec_t) fd->startSector;
    sec_t sec_count = 1;
    u32 buffer_offset = (u32) (offset % fd->sectorSize);
    u8 *buffer = NULL;

    // Determine the range of sectors required for this read
    if (offset > 0) {
        sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize);
    }
    if (buffer_offset+count > fd->sectorSize) {
        sec_count = (sec_t) ceil((f64) (buffer_offset+count) / (f64) fd->sectorSize);
    }

    // Don't read over the partitions limit
    if(sec_start+sec_count > fd->startSector+fd->sectorCount)
    {
        //ext2_log_trace("Error: read requested up to sector %lli while partition goes up to %lli\n", (s64) (sec_start+sec_count), (s64) (fd->startSector+fd->sectorCount));
        errno = EROFS;
        return -1;
    }

    // If this read happens to be on the sector boundaries then do the read straight into the destination buffer

    if((buffer_offset == 0) && (count % fd->sectorSize == 0))
    {
        // Read from the device
        //ext2_log_trace("direct read from sector %d (%d sector(s) long)\n", sec_start, sec_count);
        if (!device_gekko_io_readsectors(dev, sec_start, sec_count, buf))
        {
            ext2_log_trace("direct read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count);
            errno = EIO;
            return -1;
        }
    // Else read into a buffer and copy over only what was requested
    }
    else
	{

        // Allocate a buffer to hold the read data
        buffer = (u8*)mem_alloc(sec_count * fd->sectorSize);
        if (!buffer) {
            errno = ENOMEM;
            return -1;
        }

        // Read from the device
        //ext2_log_trace("buffered read from sector %d (%d sector(s) long)\n", sec_start, sec_count);
        //ext2_log_trace("count: %d  sec_count:%d  fd->sectorSize: %d )\n", (u32)count, (u32)sec_count,(u32)fd->sectorSize);
        if (!device_gekko_io_readsectors(dev, sec_start, sec_count, buffer)) {
            ext2_log_trace("buffered read failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count);
            mem_free(buffer);
            errno = EIO;
            return -1;
        }

        // Copy what was requested to the destination buffer
        memcpy(buf, buffer + buffer_offset, count);
        mem_free(buffer);

    }

    return count;
}
static s64 device_gekko_io_writebytes(io_channel dev, s64 offset, s64 count, const void *buf)
{
    //ext2_log_trace("dev %p, offset %lli, count %lli\n", dev, offset, count);

    // Get the device driver descriptor
    gekko_fd *fd = DEV_FD(dev);
    if (!fd) {
        errno = EBADF;
        return -1;
    }

    if(!(dev->flags & EXT2_FLAG_RW))
        return -1;

    // Get the device interface
    const DISC_INTERFACE* interface = fd->interface;
    if (!interface) {
        errno = ENODEV;
        return -1;
    }

    if(count < 0 || offset < 0) {
        errno = EROFS;
        return -1;
    }

    if(count == 0)
        return 0;

    sec_t sec_start = (sec_t) fd->startSector;
    sec_t sec_count = 1;
    u32 buffer_offset = (u32) (offset % fd->sectorSize);
    u8 *buffer = NULL;

    // Determine the range of sectors required for this write
    if (offset > 0) {
        sec_start += (sec_t) floor((f64) offset / (f64) fd->sectorSize);
    }
    if ((buffer_offset+count) > fd->sectorSize) {
        sec_count = (sec_t) ceil((f64) (buffer_offset+count) / (f64) fd->sectorSize);
    }

    // Don't write over the partitions limit
    if(sec_start+sec_count > fd->startSector+fd->sectorCount)
    {
        //ext2_log_trace("Error: write requested up to sector %lli while partition goes up to %lli\n", (s64) (sec_start+sec_count), (s64) (fd->startSector+fd->sectorCount));
        errno = EROFS;
        return -1;
    }

    // If this write happens to be on the sector boundaries then do the write straight to disc
    if((buffer_offset == 0) && (count % fd->sectorSize == 0))
    {
        // Write to the device
        //ext2_log_trace("direct write to sector %d (%d sector(s) long)\n", sec_start, sec_count);
        if (!device_gekko_io_writesectors(dev, sec_start, sec_count, buf)) {
            ext2_log_trace("direct write failure @ sector %d (%d sector(s) long)\n", sec_start, sec_count);
            errno = EIO;
            return -1;
        }
    // Else write from a buffer aligned to the sector boundaries
    }
    else
    {
        // Allocate a buffer to hold the write data
        buffer = (u8 *) mem_alloc(sec_count * fd->sectorSize);
        if (!buffer) {
            errno = ENOMEM;
            return -1;
        }
        // Read the first and last sectors of the buffer from disc (if required)
        // NOTE: This is done because the data does not line up with the sector boundaries,
        //       we just read in the buffer edges where the data overlaps with the rest of the disc
        if(buffer_offset != 0)
        {
            if (!device_gekko_io_readsectors(dev, sec_start, 1, buffer)) {
                //ext2_log_trace("read failure @ sector %d\n", sec_start);
                mem_free(buffer);
                errno = EIO;
                return -1;
            }
        }
        if((buffer_offset+count) % fd->sectorSize != 0)
        {
            if (!device_gekko_io_readsectors(dev, sec_start + sec_count - 1, 1, buffer + ((sec_count-1) * fd->sectorSize))) {
                //ext2_log_trace("read failure @ sector %d\n", sec_start + sec_count - 1);
                mem_free(buffer);
                errno = EIO;
                return -1;
            }
        }

        // Copy the data into the write buffer
        memcpy(buffer + buffer_offset, buf, count);

        // Write to the device
        //ext2_log_trace("buffered write to sector %d (%d sector(s) long)\n", sec_start, sec_count);
        if (!device_gekko_io_writesectors(dev, sec_start, sec_count, buffer)) {
            //ext2_log_trace("buffered write failure @ sector %d\n", sec_start);
            mem_free(buffer);
            errno = EIO;
            return -1;
        }

        // Free the buffer
        mem_free(buffer);
    }

    return count;
}
Example #10
0
void Run(unsigned short Port, NETADDR Dest)
{
	NETADDR Src = {NETTYPE_IPV4, {0,0,0,0}, Port};
	NETSOCKET Socket = net_udp_create(Src, 0);

	char aBuffer[1024*2];
	int ID = 0;
	int Delaycounter = 0;

	while(1)
	{
		static int Lastcfg = 0;
		int n = ((time_get()/time_freq())/m_ConfigInterval) % m_ConfigNumpingconfs;
		CPingConfig Ping = m_aConfigPings[n];

		if(n != Lastcfg)
			dbg_msg("crapnet", "cfg = %d", n);
		Lastcfg = n;

		// handle incomming packets
		while(1)
		{
			// fetch data
			int DataTrash = 0;
			NETADDR From;
			int Bytes = net_udp_recv(Socket, &From, aBuffer, 1024*2);
			if(Bytes <= 0)
				break;

			if((rand()%100) < Ping.m_Loss) // drop the packet
			{
				if(m_ConfigLog)
					dbg_msg("crapnet", "dropped packet");
				continue;
			}

			// create new packet
			CPacket *p = (CPacket *)mem_alloc(sizeof(CPacket)+Bytes, 1);

			if(net_addr_comp(&From, &Dest) == 0)
				p->m_SendTo = Src; // from the server
			else
			{
				Src = From; // from the client
				p->m_SendTo = Dest;
			}

			// queue packet
			p->m_pPrev = m_pLast;
			p->m_pNext = 0;
			if(m_pLast)
				m_pLast->m_pNext = p;
			else
			{
				m_pFirst = p;
				m_pLast = p;
			}
			m_pLast = p;

			// set data in packet
			p->m_Timestamp = time_get();
			p->m_DataSize = Bytes;
			p->m_ID = ID++;
			mem_copy(p->m_aData, aBuffer, Bytes);

			if(ID > 20 && Bytes > 6 && DataTrash)
			{
				p->m_aData[6+(rand()%(Bytes-6))] = rand()&255; // modify a byte
				if((rand()%10) == 0)
				{
					p->m_DataSize -= rand()%32;
					if(p->m_DataSize < 6)
						p->m_DataSize = 6;
				}
			}

			if(Delaycounter <= 0)
			{
				if(Ping.m_Delay)
					p->m_Timestamp += (time_freq()*1000)/Ping.m_Delay;
				Delaycounter = Ping.m_DelayFreq;
			}
			Delaycounter--;

			if(m_ConfigLog)
			{
				char aAddrStr[NETADDR_MAXSTRSIZE];
				net_addr_str(&From, aAddrStr, sizeof(aAddrStr), true);
				dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize);
			}
		}

		//
		/*while(1)
		{*/
		CPacket *p = 0;
		CPacket *pNext = m_pFirst;
		while(1)
		{
			p = pNext;
			if(!p)
				break;
			pNext = p->m_pNext;

			if((time_get()-p->m_Timestamp) > m_CurrentLatency)
			{
				char aFlags[] = "  ";

				if(m_ConfigReorder && (rand()%2) == 0 && p->m_pNext)
				{
					aFlags[0] = 'R';
					p = m_pFirst->m_pNext;
				}

				if(p->m_pNext)
					p->m_pNext->m_pPrev = p->m_pPrev;
				else
					m_pLast = p->m_pPrev;

				if(p->m_pPrev)
					p->m_pPrev->m_pNext = p->m_pNext;
				else
					m_pFirst = p->m_pNext;

				/*CPacket *cur = first;
				while(cur)
				{
					dbg_assert(cur != p, "p still in list");
					cur = cur->next;
				}*/

				// send and remove packet
				//if((rand()%20) != 0) // heavy packetloss
				net_udp_send(Socket, &p->m_SendTo, p->m_aData, p->m_DataSize);

				// update lag
				double Flux = rand()/(double)RAND_MAX;
				int MsSpike = Ping.m_Spike;
				int MsFlux = Ping.m_Flux;
				int MsPing = Ping.m_Base;
				m_CurrentLatency = ((time_freq()*MsPing)/1000) + (int64)(((time_freq()*MsFlux)/1000)*Flux); // 50ms

				if(MsSpike && (p->m_ID%100) == 0)
				{
					m_CurrentLatency += (time_freq()*MsSpike)/1000;
					aFlags[1] = 'S';
				}

				if(m_ConfigLog)
				{
					char aAddrStr[NETADDR_MAXSTRSIZE];
					net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true);
					dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags);
				}


				mem_free(p);
			}
		}

		thread_sleep(1);
	}
}
static errcode_t device_gekko_io_open(const char *name, int flags, io_channel *dev)
{
    // Get the device driver descriptor
    gekko_fd *fd = DEV_FD((*dev));
    if (!fd) {
        errno = EBADF;
        return -1;
    }

    // Get the device interface
    const DISC_INTERFACE* interface = fd->interface;
    if (!interface) {
        errno = ENODEV;
        return -1;
    }

    // Start the device interface and ensure that it is inserted
    if (!interface->startup()) {
        ext2_log_trace("device failed to start\n");
        errno = EIO;
        return -1;
    }
    if (!interface->isInserted()) {
        ext2_log_trace("device media is not inserted\n");
        errno = EIO;
        return -1;
    }

    // Allocate 4 x max sector size in case of 4096 sector size
    u8 *buffer = (u8 *) mem_alloc(4 * MAX_SECTOR_SIZE);
    if(!buffer)
    {
        ext2_log_trace("no memory for superblock");
        errno = ENOMEM;
        return -1;
    }

    // Check that there is a valid EXT boot sector at the start of the device
    if (!interface->readSectors(fd->startSector, 4, buffer))
    {
        ext2_log_trace("read failure @ sector %d\n", fd->startSector);
        errno = EROFS;
        mem_free(buffer);
        return -1;
    }

    struct ext2_super_block	* super = (struct ext2_super_block	*) (buffer + SUPERBLOCK_OFFSET);

    if(ext2fs_le16_to_cpu(super->s_magic) != EXT2_SUPER_MAGIC)
    {
        ext2_log_trace("super mismatch: read %04X - expected %04X\n", ext2fs_le16_to_cpu(super->s_magic), EXT2_SUPER_MAGIC);
        mem_free(buffer);
        errno = EROFS;
        return -1;
    }

    switch(ext2fs_le32_to_cpu(super->s_log_block_size))
    {
        case 1:
            (*dev)->block_size = 2048;
            break;
        case 2:
            (*dev)->block_size = 4096;
            break;
        case 3:
            (*dev)->block_size = 8192;
            break;
        default:
        case 0:
            (*dev)->block_size = 1024;
            break;
    }


    // Parse the boot sector
    fd->sectorSize = readSectorSize(interface);
    fd->offset = 0;
    fd->sectorCount = 0;
    fd->sectorCount = (sec_t) ((u64) ext2fs_le32_to_cpu(super->s_blocks_count) * (u64) ((*dev)->block_size) / (u64) fd->sectorSize);

    mem_free(buffer);

    // Create the cache
    fd->cache = cache_constructor(fd->cachePageCount, fd->cachePageSize, interface, fd->startSector, fd->startSector + fd->sectorCount, fd->sectorSize);

    return 0;
}
Example #12
0
void insertPHT(PairHashTable *t, unsigned p, unsigned q, unsigned n)
{
  PairHashTableEntry *e = &t->t[hashPHT(t->size, p, q)];

  if (e->p != -1) { /* no room at front? */
    if (t->overflows > t->size*2) { /* too many overflows, rehash */
      unsigned newsize = primes[++(t->prime)];
      PairHashTableEntry *r = 
	(PairHashTableEntry *) mem_alloc(sizeof(PairHashTableEntry)*newsize);
      int i;
      t->overflows = 0;
      for (i = 0; i < newsize; i++) { /* clear all */
	r[i].p = -1;
	r[i].overflow = 0;
      }
      for (i = 0; i < t->size; i++) { /* rehash */
	PairHashTableEntry *w = &t->t[i];
	if (w->p != -1)
	  while (w) {
	    PairHashTableEntry *s = &r[hashPHT(newsize, w->p, w->q)];
	    if (s->p != -1) { /* find back of list */
	      while (s->overflow)
		s = s->overflow;
	      s->overflow = 
		(PairHashTableEntry *) mem_alloc(sizeof(PairHashTableEntry));
	      s = s->overflow;
	      t->overflows++;
	    }
	    s->p = w->p;
	    s->q = w->q;
	    s->n = w->n;
	    s->overflow = 0;
	    w = w->overflow;
	  }
      }
      for (i = 0; i < t->size; i++) { /* free */
	PairHashTableEntry *e = t->t[i].overflow, *w;
	while (e) {
	  w = e->overflow;
	  mem_free(e);
	  e = w;
	}
      }
      mem_free(t->t);
      t->t = r;
      t->size = newsize;
      e = &t->t[hashPHT(t->size, p, q)];
    }
    if (e->p != -1) { /* still no room at front? */
      while (e->overflow) /* place at back of list */
	e = e->overflow;
      e->overflow = 
	(PairHashTableEntry *) mem_alloc(sizeof(PairHashTableEntry));
      e = e->overflow;
      t->overflows++;
    }
  }
  e->p = p;
  e->q = q;
  e->n = n;
  e->overflow = 0;
}
Example #13
0
CLIENT *
clnttcp_create (struct sockaddr_in *raddr, u_long prog, u_long vers,
		int *sockp, u_int sendsz, u_int recvsz)
{
  CLIENT *h;
  struct ct_data *ct;
  struct rpc_msg call_msg;

  h = (CLIENT *) mem_alloc (sizeof (*h));
  ct = (struct ct_data *) mem_alloc (sizeof (*ct));
  if (h == NULL || ct == NULL)
    {
      struct rpc_createerr *ce = &get_rpc_createerr ();
#ifdef USE_IN_LIBIO
      if (_IO_fwide (stderr, 0) > 0)
	(void) fwprintf (stderr, L"%s",
			   _("clnttcp_create: out of memory\n"));
      else
#endif
	(void) fputs (_("clnttcp_create: out of memory\n"), stderr);
      ce->cf_stat = RPC_SYSTEMERROR;
      ce->cf_error.re_errno = ENOMEM;
      goto fooy;
    }

  /*
   * If no port number given ask the pmap for one
   */
  if (raddr->sin_port == 0)
    {
      u_short port;
      if ((port = pmap_getport (raddr, prog, vers, IPPROTO_TCP)) == 0)
	{
	  mem_free ((caddr_t) ct, sizeof (struct ct_data));
	  mem_free ((caddr_t) h, sizeof (CLIENT));
	  return ((CLIENT *) NULL);
	}
      raddr->sin_port = htons (port);
    }

  /*
   * If no socket given, open one
   */
  if (*sockp < 0)
    {
      *sockp = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
      (void) bindresvport (*sockp, (struct sockaddr_in *) 0);
      if ((*sockp < 0)
	  || (connect (*sockp, (struct sockaddr *) raddr,
			 sizeof (*raddr)) < 0))
	{
	  struct rpc_createerr *ce = &get_rpc_createerr ();
	  ce->cf_stat = RPC_SYSTEMERROR;
	  ce->cf_error.re_errno = errno;
	  if (*sockp >= 0)
	    (void) close (*sockp);
	  goto fooy;
	}
      ct->ct_closeit = TRUE;
    }
  else
    {
      ct->ct_closeit = FALSE;
    }

  /*
   * Set up private data struct
   */
  ct->ct_sock = *sockp;
  ct->ct_wait.tv_usec = 0;
  ct->ct_waitset = FALSE;
  ct->ct_addr = *raddr;

  /*
   * Initialize call message
   */
  call_msg.rm_xid = _create_xid ();
  call_msg.rm_direction = CALL;
  call_msg.rm_call.cb_rpcvers = RPC_MSG_VERSION;
  call_msg.rm_call.cb_prog = prog;
  call_msg.rm_call.cb_vers = vers;

  /*
   * pre-serialize the static part of the call msg and stash it away
   */
  xdrmem_create (&(ct->ct_xdrs), ct->ct_mcall, MCALL_MSG_SIZE,
		 XDR_ENCODE);
  if (!xdr_callhdr (&(ct->ct_xdrs), &call_msg))
    {
      if (ct->ct_closeit)
	{
	  (void) close (*sockp);
	}
      goto fooy;
    }
  ct->ct_mpos = XDR_GETPOS (&(ct->ct_xdrs));
  XDR_DESTROY (&(ct->ct_xdrs));

  /*
   * Create a client handle which uses xdrrec for serialization
   * and authnone for authentication.
   */
  xdrrec_create (&(ct->ct_xdrs), sendsz, recvsz,
		 (caddr_t) ct, readtcp, writetcp);
  h->cl_ops = &tcp_ops;
  h->cl_private = (caddr_t) ct;
  h->cl_auth = authnone_create ();
  return h;

fooy:
  /*
   * Something goofed, free stuff and barf
   */
  mem_free ((caddr_t) ct, sizeof (struct ct_data));
  mem_free ((caddr_t) h, sizeof (CLIENT));
  return ((CLIENT *) NULL);
}
Example #14
0
/*
 * client mooshika create
 */
CLIENT *
clnt_rdma_create(RDMAXPRT *xprt,		/* init but NOT connect()ed descriptor */
		 rpcprog_t program,		/* program number */
		 rpcvers_t version,
		 const u_int flags)
{
	CLIENT *cl = NULL;		/* client handle */
	struct cx_data *cx = NULL;	/* private data */

	struct cm_data *cm = NULL;
	struct timeval now;

	if (!xprt || xprt->state != RDMAXS_INITIAL) {
		rpc_createerr.cf_stat = RPC_UNKNOWNADDR; /* FIXME, add a warnx? */
		rpc_createerr.cf_error.re_errno = 0;
		return (NULL);
	}

	/*
	 * Find the receive and the send size
	 */
//	u_int sendsz = 8*1024;
//	u_int recvsz = 4*8*1024;
	u_int sendsz = 1024;
	u_int recvsz = 1024;

	cl = mem_alloc(sizeof (CLIENT));
	/*
	 * Should be multiple of 4 for XDR.
	 */
	cx = alloc_cx_data(CX_MSK_DATA, sendsz, recvsz);
	cm = CM_DATA(cx);
	/* Other values can also be set through clnt_control() */
	cm->cm_xdrs.x_lib[1] = (void *)xprt;
	cm->cm_wait.tv_sec = 15; /* heuristically chosen */
	cm->cm_wait.tv_usec = 0;

	(void) gettimeofday(&now, NULL);
	//	cm->call_msg.rm_xid = __RPC_GETXID(&now);
	cm->call_msg.rm_xid = 1;
	cm->call_msg.rm_call.cb_prog = program;
	cm->call_msg.rm_call.cb_vers = version;

	rpc_rdma_connect(xprt);

	xdr_rdma_create(&cm->cm_xdrs, xprt, sendsz, recvsz, flags);

	rpc_rdma_connect_finalize(xprt);

	/*
	 * By default, closeit is always FALSE. It is users responsibility
	 * to do a close on it, else the user may use clnt_control
	 * to let clnt_destroy do it for him/her.
	 */
	cm->cm_closeit = FALSE;
	cl->cl_ops = clnt_rdma_ops();
	//	cl->cl_private = (caddr_t)(void *) cx;
	cl->cl_p1 =  (caddr_t)(void *) cx;
	cl->cl_p2 =  NULL;
	//	cl->cl_p2 =  rec;
	//	cl->cl_auth = authnone_create();
	cl->cl_tp = NULL;
	cl->cl_netid = NULL;

	return (cl);
}
Example #15
0
regexp_t *
TclCompileRegexp(
    Tcl_Interp *interp			/* For use in error reporting. */
    , unsigned char *string		/* String for which to produce
					 * compiled regular expression. */
    )
{
    register Interp *iPtr = (Interp *) interp;
    int i, length, size;
    regexp_t *result;

    length = strlen(string);
    for (i = 0; i < NUM_REGEXPS; i++) {
	if ((length == iPtr->patLengths[i])
		&& (strcmp(string, iPtr->patterns[i]) == 0)) {
	    /*
	     * Move the matched pattern to the first slot in the
	     * cache and shift the other patterns down one position.
	     */

	    if (i != 0) {
		int j;
		unsigned char *cachedString;

		cachedString = iPtr->patterns[i];
		result = iPtr->regexps[i];
		for (j = i-1; j >= 0; j--) {
		    iPtr->patterns[j+1] = iPtr->patterns[j];
		    iPtr->patLengths[j+1] = iPtr->patLengths[j];
		    iPtr->regexps[j+1] = iPtr->regexps[j];
		}
		iPtr->patterns[0] = cachedString;
		iPtr->patLengths[0] = length;
		iPtr->regexps[0] = result;
	    }
	    return iPtr->regexps[0];
	}
    }

    /*
     * No match in the cache.  Compile the string and add it to the
     * cache.
     */
    size = regexp_size (string);
    if (size <= 0) {
	Tcl_AppendResult(interp, "invalid regular expression pattern", 0);
	return 0;
    }
    result = (regexp_t*) mem_alloc (interp->pool, size);
    if (! regexp_compile (result, string)) {
	Tcl_AppendResult(interp, "couldn't compile regular expression pattern", 0);
	return 0;
    }
    if (iPtr->patterns[NUM_REGEXPS-1] != 0) {
	mem_free (iPtr->patterns[NUM_REGEXPS-1]);
	mem_free (iPtr->regexps[NUM_REGEXPS-1]);
    }
    for (i = NUM_REGEXPS - 2; i >= 0; i--) {
	iPtr->patterns[i+1] = iPtr->patterns[i];
	iPtr->patLengths[i+1] = iPtr->patLengths[i];
	iPtr->regexps[i+1] = iPtr->regexps[i];
    }
    iPtr->patterns[0] = (unsigned char *)mem_alloc (interp->pool, length+1);
    strcpy(iPtr->patterns[0], string);
    iPtr->patLengths[0] = length;
    iPtr->regexps[0] = result;
    return result;
}
Example #16
0
/*
 * XDR an array of arbitrary elements
 * *addrp is a pointer to the array, *sizep is the number of elements.
 * If addrp is NULL (*sizep * elsize) bytes are allocated.
 * elsize is the size (in bytes) of each element, and elproc is the
 * xdr procedure to call to handle each element of the array.
 */
bool_t
xdr_array(XDR *xdrs,
          caddr_t *addrp,		/* array pointer */
          u_int *sizep,		/* number of elements */
          u_int maxsize,		/* max numberof elements */
          u_int elsize,		/* size in bytes of each element */
          xdrproc_t elproc)		/* xdr routine to handle each element */
{
    u_int i;
    caddr_t target = *addrp;
    u_int c;  /* the actual element count */
    bool_t stat = TRUE;
    u_int nodesize;

    /* like strings, arrays are really counted arrays */
    if (!xdr_u_int(xdrs, sizep)) {
        return (FALSE);
    }
    c = *sizep;
    if ((c > maxsize || UINT_MAX/elsize < c) &&
            (xdrs->x_op != XDR_FREE)) {
        return (FALSE);
    }
    nodesize = c * elsize;

    /*
     * if we are deserializing, we may need to allocate an array.
     * We also save time by checking for a null array if we are freeing.
     */
    if (target == NULL)
        switch (xdrs->x_op) {
        case XDR_DECODE:
            if (c == 0)
                return (TRUE);
            *addrp = target = mem_alloc(nodesize);
            if (target == NULL) {
                printf("xdr_array: out of memory");
                return (FALSE);
            }
            memset(target, 0, nodesize);
            break;

        case XDR_FREE:
            return (TRUE);

        case XDR_ENCODE:
            break;
        }

    /*
     * now we xdr each element of array
     */
    for (i = 0; (i < c) && stat; i++) {
        stat = (*elproc)(xdrs, target);
        target += elsize;
    }

    /*
     * the array may need freeing
     */
    if (xdrs->x_op == XDR_FREE) {
        mem_free(*addrp, nodesize);
        *addrp = NULL;
    }
    return (stat);
}
Example #17
0
int
Tcl_SplitList(
    Tcl_Interp *interp		/* Interpreter to use for error reporting. */
    , unsigned char *list	/* Pointer to string with list structure. */
    , int *argcPtr		/* Pointer to location to fill in with
				 * the number of elements in the list. */
    , unsigned char ***argvPtr	/* Pointer to place to store pointer to array
				 * of pointers to list elements. */
    )
{
    unsigned char **argv;
    register unsigned char *p;
    int size, i, result, elSize, brace;
    unsigned char *element;

    /*
     * Figure out how much space to allocate.  There must be enough
     * space for both the array of pointers and also for a copy of
     * the list.  To estimate the number of pointers needed, count
     * the number of space characters in the list.
     */

    for (size = 1, p = list; *p != 0; p++) {
	if (isspace(*p)) {
	    size++;
	}
    }
    size++;			/* Leave space for final NULL pointer. */
    argv = (unsigned char**) mem_alloc (interp->pool, (unsigned)
	    ((size * sizeof(char *)) + (p - list) + 1));
    for (i = 0, p = ((unsigned char *) argv) + size*sizeof(char *);
	    *list != 0; i++) {
	result = TclFindElement(interp, list, &element, &list, &elSize, &brace);
	if (result != TCL_OK) {
	    mem_free (argv);
	    return result;
	}
	if (*element == 0) {
	    break;
	}
	if (i >= size) {
	    mem_free (argv);
	    Tcl_SetResult(interp, (unsigned char*) "internal error in Tcl_SplitList",
		    TCL_STATIC);
	    return TCL_ERROR;
	}
	argv[i] = p;
	if (brace) {
	    strncpy(p, element, elSize);
	    p += elSize;
	    *p = 0;
	    p++;
	} else {
	    TclCopyAndCollapse(elSize, element, p);
	    p += elSize+1;
	}
    }

    argv[i] = 0;
    *argvPtr = argv;
    *argcPtr = i;
    return TCL_OK;
}
Example #18
0
int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags)
{
	int Mipmap = 1;
	unsigned char *pTexData = (unsigned char *)pData;
	unsigned char *pTmpData = 0;
	int Oglformat = 0;
	int StoreOglformat = 0;
	int Tex = 0;
	
	// don't waste memory on texture if we are stress testing
	if(g_Config.m_DbgStress)
		return 	m_InvalidTexture;
	
	// grab texture
	Tex = m_FirstFreeTexture;
	m_FirstFreeTexture = m_aTextures[Tex].m_Next;
	m_aTextures[Tex].m_Next = -1;
	
	// resample if needed
	if(!(Flags&TEXLOAD_NORESAMPLE) && g_Config.m_GfxTextureQuality==0)
	{
		if(Width > 16 && Height > 16 && Format == CImageInfo::FORMAT_RGBA)
		{
			unsigned char *pTmpData;
			int c = 0;
			int x, y;

			pTmpData = (unsigned char *)mem_alloc(Width*Height*4, 1);

			Width/=2;
			Height/=2;

			for(y = 0; y < Height; y++)
				for(x = 0; x < Width; x++, c++)
				{
					pTmpData[c*4] = Sample(Width*2, Height*2, pTexData, x*2,y*2, 0);
					pTmpData[c*4+1] = Sample(Width*2, Height*2, pTexData, x*2,y*2, 1);
					pTmpData[c*4+2] = Sample(Width*2, Height*2, pTexData, x*2,y*2, 2);
					pTmpData[c*4+3] = Sample(Width*2, Height*2, pTexData, x*2,y*2, 3);
				}
			pTexData = pTmpData;
		}
	}
	
	Oglformat = GL_RGBA;
	if(Format == CImageInfo::FORMAT_RGB)
		Oglformat = GL_RGB;
	else if(Format == CImageInfo::FORMAT_ALPHA)
		Oglformat = GL_ALPHA;
	
	// upload texture
	if(g_Config.m_GfxTextureCompression)
	{
		StoreOglformat = GL_COMPRESSED_RGBA_ARB;
		if(StoreFormat == CImageInfo::FORMAT_RGB)
			StoreOglformat = GL_COMPRESSED_RGB_ARB;
		else if(StoreFormat == CImageInfo::FORMAT_ALPHA)
			StoreOglformat = GL_COMPRESSED_ALPHA_ARB;
	}
	else
	{
		StoreOglformat = GL_RGBA;
		if(StoreFormat == CImageInfo::FORMAT_RGB)
			StoreOglformat = GL_RGB;
		else if(StoreFormat == CImageInfo::FORMAT_ALPHA)
			StoreOglformat = GL_ALPHA;
	}
		
	glGenTextures(1, &m_aTextures[Tex].m_Tex);
	glBindTexture(GL_TEXTURE_2D, m_aTextures[Tex].m_Tex);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
	gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData);
	
	// calculate memory usage
	{
		int PixelSize = 4;
		if(StoreFormat == CImageInfo::FORMAT_RGB)
			PixelSize = 3;
		else if(StoreFormat == CImageInfo::FORMAT_ALPHA)
			PixelSize = 1;

		m_aTextures[Tex].m_MemSize = Width*Height*PixelSize;
		if(Mipmap)
		{
			while(Width > 2 && Height > 2)
			{
				Width>>=1;
				Height>>=1;
				m_aTextures[Tex].m_MemSize += Width*Height*PixelSize;
			}
		}
	}
	
	m_TextureMemoryUsage += m_aTextures[Tex].m_MemSize;
	mem_free(pTmpData);
	return Tex;
}
Example #19
0
struct table *parse_table(unsigned char *html, unsigned char *eof, unsigned char **end, struct rgb *bgcolor, int sh, struct s_e **bad_html, int *bhp)
{
	int qqq;
	struct table *t;
	struct table_cell *cell;
	unsigned char *t_name, *t_attr, *en;
	int t_namelen;
	int x = 0, y = -1;
	int p = 0;
	unsigned char *lbhp = NULL;
	int l_al = AL_LEFT;
	int l_val = VAL_MIDDLE;
	int csp, rsp;
	int group = 0;
	int i, j, k;
	struct rgb l_col;
	int c_al = AL_TR, c_val = VAL_TR, c_width = W_AUTO, c_span = 0;
	memcpy(&l_col, bgcolor, sizeof(struct rgb));
	*end = html;
	if (bad_html) {
		*bad_html = DUMMY;
		*bhp = 0;
	}
	if (!(t = new_table())) return NULL;
	se:
	en = html;
	see:
	html = en;
	if (bad_html && !p && !lbhp) {
		if (!(*bhp & (ALLOC_GR-1))) {
			if ((unsigned)*bhp > MAXINT / sizeof(struct s_e) - ALLOC_GR) overalloc();
			*bad_html = mem_realloc(*bad_html, (*bhp + ALLOC_GR) * sizeof(struct s_e));
		}
		lbhp = (*bad_html)[(*bhp)++].s = html;
	}
	while (html < eof && *html != '<') html++;
	if (html >= eof) {
		if (p) CELL(t, x, y)->end = html;
		if (lbhp) (*bad_html)[*bhp-1].e = html;
		goto scan_done;
	}
	if (html + 2 <= eof && (html[1] == '!' || html[1] == '?')) {
		html = skip_comment(html, eof);
		goto se;
	}
	if (parse_element(html, eof, &t_name, &t_namelen, &t_attr, &en)) {
		html++;
		goto se;
	}
	if (t_namelen == 5 && !casecmp(t_name, "TABLE", 5)) {
		en = skip_table(en, eof);
		goto see;
	}
	if (t_namelen == 6 && !casecmp(t_name, "/TABLE", 6)) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (p) CELL(t, x, y)->end = html;
		if (lbhp) (*bad_html)[*bhp-1].e = html;
		goto scan_done;
	}
	if (t_namelen == 8 && !casecmp(t_name, "COLGROUP", 8)) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
		c_al = AL_TR;
		c_val = VAL_TR;
		c_width = W_AUTO;
		get_align(t_attr, &c_al);
		get_valign(t_attr, &c_val);
		get_c_width(t_attr, &c_width, sh);
		if ((c_span = get_num(t_attr, "span")) == -1) c_span = 1;
		goto see;
	}
	if (t_namelen == 9 && !casecmp(t_name, "/COLGROUP", 9)) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
		c_span = 0;
		c_al = AL_TR;
		c_val = VAL_TR;
		c_width = W_AUTO;
		goto see;
	}
	if (t_namelen == 3 && !casecmp(t_name, "COL", 3)) {
		int sp, wi, al, val;
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
		if ((sp = get_num(t_attr, "span")) == -1) sp = 1;
		wi = c_width;
		al = c_al;
		val = c_val;
		get_align(t_attr, &al);
		get_valign(t_attr, &val);
		get_c_width(t_attr, &wi, sh);
		new_columns(t, sp, wi, al, val, !!c_span);
		c_span = 0;
		goto see;
	}
	if (t_namelen == 3 && (!casecmp(t_name, "/TR", 3) || !casecmp(t_name, "/TD", 3) || !casecmp(t_name, "/TH", 3))) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (p) CELL(t, x, y)->end = html, p = 0;
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
	}
	if (t_namelen == 2 && !casecmp(t_name, "TR", 2)) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (p) CELL(t, x, y)->end = html, p = 0;
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
		if (group) group--;
		l_al = AL_LEFT;
		l_val = VAL_MIDDLE;
		memcpy(&l_col, bgcolor, sizeof(struct rgb));
		get_align(t_attr, &l_al);
		get_valign(t_attr, &l_val);
		get_bgcolor(t_attr, &l_col);
		y++, x = 0;
		goto see;
	}
	if (t_namelen == 5 && ((!casecmp(t_name, "THEAD", 5)) || (!casecmp(t_name, "TBODY", 5)) || (!casecmp(t_name, "TFOOT", 5)))) {
		if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
		if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
		group = 2;
	}
	if (t_namelen != 2 || (casecmp(t_name, "TD", 2) && casecmp(t_name, "TH", 2))) goto see;
	if (c_span) new_columns(t, c_span, c_width, c_al, c_val, 1);
	if (lbhp) (*bad_html)[*bhp-1].e = html, lbhp = NULL;
	if (p) CELL(t, x, y)->end = html, p = 0;
	if (y == -1) y = 0, x = 0;
	nc:
	cell = new_cell(t, x, y);
	if (cell->used) {
		if (cell->colspan == -1) goto see;
		x++;
		goto nc;
	}
	cell->mx = x;
	cell->my = y;
	cell->used = 1;
	cell->start = en;
	p = 1;
	cell->align = l_al;
	cell->valign = l_val;
	if ((cell->b = upcase(t_name[1]) == 'H')) cell->align = AL_CENTER;
	if (group == 1) cell->group = 1;
	if (x < t->c) {
		if (t->cols[x].align != AL_TR) cell->align = t->cols[x].align;
		if (t->cols[x].valign != VAL_TR) cell->valign = t->cols[x].valign;
	}
	memcpy(&cell->bgcolor, &l_col, sizeof(struct rgb));
	get_align(t_attr, &cell->align);
	get_valign(t_attr, &cell->valign);
	get_bgcolor(t_attr, &cell->bgcolor);
	if ((csp = get_num(t_attr, "colspan")) == -1) csp = 1;
	if (!csp) csp = -1;
	if ((rsp = get_num(t_attr, "rowspan")) == -1) rsp = 1;
	if (!rsp) rsp = -1;
	if (csp >= 0 && rsp >= 0 && csp * rsp > 100000) {
		if (csp > 10) csp = -1;
		if (rsp > 10) rsp = -1;
	}
	cell->colspan = csp;
	cell->rowspan = rsp;
	if (csp == 1) {
		int w = W_AUTO;
		get_c_width(t_attr, &w, sh);
		if (w != W_AUTO) set_td_width(t, x, w, 0);
	}
	qqq = t->x;
	for (i = 1; csp != -1 ? i < csp : x + i < qqq; i++) {
		struct table_cell *sc = new_cell(t, x + i, y);
		if (sc->used) {
			csp = i;
			for (k = 0; k < i; k++) CELL(t, x + k, y)->colspan = csp;
			break;
		}
		sc->used = sc->spanned = 1;
		sc->rowspan = rsp;
		sc->colspan = csp;
		sc->mx = x;
		sc->my = y;
	}
	qqq = t->y;
	for (j = 1; rsp != -1 ? j < rsp : y + j < qqq; j++) {
		for (k = 0; k < i; k++) {
			struct table_cell *sc = new_cell(t, x + k, y + j);
			if (sc->used) {
				int l, m;
				if (sc->mx == x && sc->my == y) continue;
				/*internal("boo");*/
				for (l = 0; l < k; l++) memset(CELL(t, x + l, y + j), 0, sizeof(struct table_cell));
				rsp = j;
				for (l = 0; l < i; l++) for (m = 0; m < j; m++) CELL(t, x + l, y + m)->rowspan = j;
				goto brk;
			}
			sc->used = sc->spanned = 1;
			sc->rowspan = rsp;
			sc->colspan = csp;
			sc->mx = x;
			sc->my = y;
		}
	}
	brk:
	goto see;

	scan_done:
	*end = html;

	for (x = 0; x < t->x; x++) for (y = 0; y < t->y; y++) {
		struct table_cell *c = CELL(t, x, y);
		if (!c->spanned) {
			if (c->colspan == -1) c->colspan = t->x - x;
			if (c->rowspan == -1) c->rowspan = t->y - y;
		}
	}

	if ((unsigned)t->y > MAXINT / sizeof(int)) overalloc();
	t->r_heights = mem_alloc(t->y * sizeof(int));
	memset(t->r_heights, 0, t->y * sizeof(int));

	for (x = 0; x < t->c; x++) if (t->cols[x].width != W_AUTO) set_td_width(t, x, t->cols[x].width, 1);
	set_td_width(t, t->x, W_AUTO, 0);

	return t;
}
Example #20
0
solitaire* solitaire_theidiot(mem_context *context, visual_settings *settings) {
	visual_pile *deck, *pile1, *pile2, *pile3, *pile4, *done;
	rule *rule1, *rule2;
	condition *pile1_4_cond;

	/* The one solitaire instance we have.*/
	solitaire* s = mem_alloc(context, sizeof(solitaire));

	/* This is the internal data representation of this
	 * solitaire. This is a local struct hidden from other
	 * members. */
	internal* i = mem_alloc(context, sizeof(internal));
	s->data = i;

	s->visual = visual_create(context, settings);

	i->deck = pile_create(context, 52);
	deck = visual_pile_create(context, i->deck);
	deck->origin[0] = 0 - (settings->card_width / 2 + settings->card_spacing / 2 + settings->card_width * 2 + settings->card_spacing * 2 + settings->card_width / 2);
	deck->origin[1] = 40.0f;
	deck->rotation = 45.0f;
	deck->action = action_deal(context, s, i);
	visual_add_pile(context, s->visual, deck);

	i->pile1 = pile_create(context, 13);
	pile1 = visual_pile_create(context, i->pile1);
	pile1->origin[0] = 0 - (settings->card_width / 2 + settings->card_spacing / 2 + settings->card_width + settings->card_spacing);
	pile1->origin[1] = 70.0f;
	pile1->translateY = 0 - settings->card_height / 5;
	visual_add_pile(context, s->visual, pile1);

	i->pile2 = pile_create(context, 13);
	pile2 = visual_pile_create(context, i->pile2);
	pile2->origin[0] = 0 - (settings->card_width / 2 + settings->card_spacing / 2);
	pile2->origin[1] = 70.0f;
	pile2->translateY = 0 - settings->card_height / 5;
	visual_add_pile(context, s->visual, pile2);

	i->pile3 = pile_create(context, 13);
	pile3 = visual_pile_create(context, i->pile3);
	pile3->origin[0] = settings->card_width / 2 + settings->card_spacing / 2;
	pile3->origin[1] = 70.0f;
	pile3->translateY = 0 - settings->card_height / 5;
	visual_add_pile(context, s->visual, pile3);

	i->pile4 = pile_create(context, 13);
	pile4 = visual_pile_create(context, i->pile4);
	pile4->origin[0] = settings->card_width / 2 + settings->card_spacing / 2 + settings->card_width + settings->card_spacing;
	pile4->origin[1] = 70.0f;
	pile4->translateY = 0 - settings->card_height / 5;
	visual_add_pile(context, s->visual, pile4);

	i->done = pile_create(context, 48);
	done = visual_pile_create(context, i->done);
	done->origin[0] = settings->card_width / 2 + settings->card_spacing / 2 + settings->card_width * 2 + settings->card_spacing * 2 + settings->card_width / 2;
	done->origin[1] = 40.0f;
	done->rotation = -45.0f;
	visual_add_pile(context, s->visual, done);

	card_create_deck(context, i->deck, 14);
	card_shuffle(i->deck);

	visual_sync(s->visual);

	s->ruleset = ruleset_create(context);

	/* Shared condition between several rules. */
	pile1_4_cond = condition_source_array(
		context, 4, i->pile1, i->pile2, i->pile3, i->pile4);

	/* Move card to done pile if source is pile1-pile4 and there is
	   a higher card in same suit in those piles. */
	rule1 = rule_create(context);
	rule_add_condition(context, rule1, pile1_4_cond);
	rule_add_condition(context, rule1, condition_destination(context, i->done));
	rule_add_condition(
		context,
		rule1,
		condition_or_array(
			context, 4,
			condition_top_card_compare(context, i->pile1,
									   e_dest_higher_value | e_follow_suit),
			condition_top_card_compare(context, i->pile2,
									   e_dest_higher_value | e_follow_suit),
			condition_top_card_compare(context, i->pile3,
									   e_dest_higher_value | e_follow_suit),
			condition_top_card_compare(context, i->pile4,
									   e_dest_higher_value | e_follow_suit)));
	rule_add_condition(context, rule1, condition_top_card(context));
	ruleset_add_rule(context, s->ruleset, rule1);

	/* Allow move to a top card to an empty pile. */
	rule2 = rule_create(context);
	rule_add_condition(context, rule2, pile1_4_cond);
	rule_add_condition(context, rule2, condition_top_card(context));
	rule_add_condition(context, rule2, condition_destination_empty(context));
	rule_add_condition(
		context, rule2,
		condition_destination_array(
			context, 4, i->pile1, i->pile2, i->pile3, i->pile4));
	ruleset_add_rule(context, s->ruleset, rule2);

	/* Solved rule */
	s->ruleset->solved = rule_create(context);
	rule_add_condition(
		context, s->ruleset->solved,
		condition_source_card_equal(
			context, e_suit_none, 14, e_equal_value, i->pile1));
	rule_add_condition(
		context, s->ruleset->solved,
		condition_source_card_equal(
			context, e_suit_none, 14, e_equal_value, i->pile2));
	rule_add_condition(
		context, s->ruleset->solved,
		condition_source_card_equal(
			context, e_suit_none, 14, e_equal_value, i->pile3));
	rule_add_condition(
		context, s->ruleset->solved,
		condition_source_card_equal(
			context, e_suit_none, 14, e_equal_value, i->pile4));
	rule_add_condition(
		context, s->ruleset->solved,
		condition_card_count_array(
			context, 1, 4, i->pile1, i->pile2, i->pile3, i->pile4));
	return s;
}
Example #21
0
void check_table_widths(struct table *t)
{
	int *w;
	int i, j;
	int s, ns;
	int m, mi = 0; /* go away, warning! */
	if ((unsigned)t->x > MAXINT / sizeof(int)) overalloc();
	w = mem_alloc(t->x * sizeof(int));
	memset(w, 0, t->x * sizeof(int));
	for (j = 0; j < t->y; j++) for (i = 0; i < t->x; i++) {
		struct table_cell *c = CELL(t, i, j);
		int k, p = 0;
		if (!c->start) continue;
		for (k = 1; k < c->colspan; k++) p += get_vline_width(t, i + k) >= 0;
		for (k = 0; k < c->colspan; k++) p += t->w_c[i + k];
		get_cell_width(c->start, c->end, t->cellpd, p, 1, &c->x_width, NULL, c->link_num, NULL);
		if (c->x_width > p) {
			/*int min, max;
			get_cell_width(c->start, c->end, t->cellpd, 0, 0, &min, &max, c->link_num, NULL);
			internal("cell is now wider (%d > %d) min = %d, max = %d, now_min = %d, now_max = %d", c->x_width, p, t->min_c[i], t->max_c[i], min, max);*/
			/* sbohem, internale. chytl jsi mi spoustu chyb v tabulkovaci, ale ted je proste cas jit ... ;-( */
			c->x_width = p;
		}
	}
	s = 1;
	do {
		ns = MAXINT;
		for (i = 0; i < t->x; i++) for (j = 0; j < t->y; j++) {
			struct table_cell *c = CELL(t, i, j);
			if (!c->start) continue;
			if (c->colspan + i > t->x) {
				/*internal("colspan out of table");*/
				mem_free(w);
				return;
			}
			if (c->colspan == s) {
				int k, p = 0;
				for (k = 1; k < s; k++) p += get_vline_width(t, i + k) >= 0;
				dst_width(w + i, s, c->x_width - p, t->max_c + i);
				/*for (k = i; k < i + s; k++) if (w[k] > t->w_c[k]) {
					int l;
					int c;
					ag:
					c = 0;
					for (l = i; l < i + s; l++) if (w[l] < t->w_c[k]) w[l]++, w[k]--, c = 1;
					if (w[k] > t->w_c[k]) {
						if (!c) internal("can't shrink cell");
						else goto ag;
					}
				}*/
			} else if (c->colspan > s && c->colspan < ns) ns = c->colspan;
		}
	} while ((s = ns) != MAXINT);

	s = 0; ns = 0;
	for (i = 0; i < t->x; i++) {
		s += t->w_c[i], ns += w[i];
		/*if (w[i] > t->w_c[i]) {
			int k;
			for (k = 0; k < t->x; k++) debug("%d, %d", t->w_c[k], w[k]);
			debug("column %d: new width(%d) is larger than previous(%d)", i, w[i], t->w_c[i]);
		}*/
	}
	if (ns > s) {
		/*internal("new width(%d) is larger than previous(%d)", ns, s);*/
		mem_free(w);
		return;
	}
	m = -1;
	for (i = 0; i < t->x; i++) {
		/*if (table_level == 1) debug("%d: %d %d %d %d", i, t->max_c[i], t->min_c[i], t->w_c[i], w[i]);*/
		if (t->max_c[i] > m) m = t->max_c[i], mi = i;
	}
	/*if (table_level == 1) debug("%d %d", mi, s - ns);*/
	if (m != -1) {
		w[mi] += s - ns;
		if (w[mi] <= t->max_c[mi]) {
			mem_free(t->w_c);
			t->w_c = w;
			return;
		}
	}
	mem_free(w);
}
Example #22
0
//int cip_encode_path(ab_tag_p tag, const char *path)
int cip_encode_path(const char *path, int needs_connection, int plc_type, uint8_t **conn_path, uint8_t *conn_path_size, uint16_t *dhp_dest)
{
    int ioi_size=0;
    int last_is_dhp=0;
    int has_dhp=0;
    int dhp_channel=0;
    int src_addr=0;
    int dest_addr=0;
    int tmp=0;
    char **links=NULL;
    char *link=NULL;
    uint8_t tmp_path[MAX_CONN_PATH+16];
    uint8_t *data = &tmp_path[0];

    /* split the path */
    if(path) {
        links = str_split(path,",");
    }

    if(links != NULL) {
        int link_index=0;

        /* work along each string. */
        link = links[link_index];

        while(link && ioi_size < MAX_CONN_PATH) {   /* MAGIC -2 to allow for padding */
            int rc = match_dhp_node(link,&dhp_channel,&src_addr,&dest_addr);
            if(rc > 0) {
                /* we matched a DH+ route node */
                pdebug(DEBUG_DETAIL,"Found DH+ routing, need connection. Conn path length=%d",ioi_size);
                last_is_dhp = 1;
                has_dhp = 1;
            } else if (rc < 0) {
                /* matched part of a DH+ node, but then failed.  Syntax error. */
                pdebug(DEBUG_WARN, "Syntax error in DH+ route path.");
                if(links) mem_free(links);
                return PLCTAG_ERR_BAD_PARAM;
            } else {
                /* did not match a DH+ route node, but no error. */
                last_is_dhp = 0;
                has_dhp = 0;

                if(str_to_int(link, &tmp) != 0) {
                    /* syntax error */
                    pdebug(DEBUG_WARN, "Syntax error in path, expected number!");
                    if(links) mem_free(links);
                    return PLCTAG_ERR_BAD_PARAM;
                }

                *data = (uint8_t)tmp;

                /*printf("convert_links() link(%d)=%s (%d)\n",i,*links,tmp);*/

                data++;
                ioi_size++;
                pdebug(DEBUG_DETAIL,"Found regular routing. Conn path length=%d",ioi_size);
            }
            /* FIXME - handle case where IP address is in path */

            link_index++;
            link = links[link_index];
        }

        /* we do not need the split string anymore. */
        if(links) {
            mem_free(links);
            links = NULL;
        }
    }

    /* Add to the path based on the protocol type and
      * whether the last part is DH+.  Only some combinations of
      * DH+ and PLC type work.
      */
    if(last_is_dhp && plc_type == AB_PROTOCOL_PLC) {
        /* We have to make the difference from the more
         * generic case.
         */

        /* try adding this onto the end of the routing path */
        *data = 0x20;
        data++;
        *data = 0xA6;
        data++;
        *data = 0x24;
        data++;
        *data = (uint8_t)dhp_channel;
        data++;
        *data = 0x2C;
        data++;
        *data = 0x01;
        data++;
        ioi_size += 6;

        *dhp_dest = (uint16_t)dest_addr;
    } else if(!has_dhp) {
        if(needs_connection) {
            /*
             * we do a generic path to the router
             * object in the PLC.  But only if the PLC is
             * one that needs a connection.  For instance a
             * Micro850 needs to work in connected mode.
             */
            *data = 0x20;   /* class */
            data++;
            *data = 0x02;   /* message router class */
            data++;
            *data = 0x24;   /* instance */
            data++;
            *data = 0x01;   /* message router class instance #1 */
            ioi_size += 4;
        }

        *dhp_dest = 0;
    } else {
        /* we had the special DH+ format and it was
         * either not last or not a PLC5/SLC.  That
         * is an error.
         */

        *dhp_dest = 0;

        return PLCTAG_ERR_BAD_PARAM;
    }

    /*
     * zero out the last byte if we need to.
     * This pads out the path to a multiple of 16-bit
     * words.
     */
    pdebug(DEBUG_DETAIL,"ioi_size before %d", ioi_size);
    if(ioi_size & 0x01) {
        *data = 0;
        ioi_size++;
    }

    /* allocate space for the connection path */
    *conn_path = mem_alloc(ioi_size);
    if(! *conn_path) {
        pdebug(DEBUG_WARN, "Unable to allocate connection path!");
        return PLCTAG_ERR_NO_MEM;
    }

    mem_copy(*conn_path, &tmp_path[0], ioi_size);

    *conn_path_size = (uint8_t)ioi_size;

    pdebug(DEBUG_INFO, "Done.");

    return PLCTAG_STATUS_OK;
}
Example #23
0
/**
 * Parses the provided line.
 *
 * This runs the first parser hook registered with `p` that matches `line`.
 */
enum parser_error parser_parse(struct parser *p, const char *line) {
	char *cline;
	char *tok;
	struct parser_hook *h;
	struct parser_spec *s;
	struct parser_value *v;
	char *sp = NULL;

	assert(p);
	assert(line);

	parser_freeold(p);

	p->lineno++;
	p->colno = 1;
	p->fhead = NULL;
	p->ftail = NULL;

	/* Ignore empty lines and comments. */
	while (*line && (isspace(*line)))
		line++;
	if (!*line || *line == '#')
		return PARSE_ERROR_NONE;

	cline = string_make(line);

	tok = strtok(cline, ":");
	if (!tok) {
		mem_free(cline);
		p->error = PARSE_ERROR_MISSING_FIELD;
		return PARSE_ERROR_MISSING_FIELD;
	}

	h = findhook(p, tok);
	if (!h) {
		my_strcpy(p->errmsg, tok, sizeof(p->errmsg));
		p->error = PARSE_ERROR_UNDEFINED_DIRECTIVE;
		mem_free(cline);
		return PARSE_ERROR_UNDEFINED_DIRECTIVE;
	}

	/* There's a little bit of trickiness here to account for optional
	 * types. The optional flag has a bit assigned to it in the spec's type
	 * tag; we compute a temporary type for the spec with that flag removed
	 * and use that instead. */
	for (s = h->fhead; s; s = s->next) {
		int t = s->type & ~PARSE_T_OPT;
		p->colno++;

		/* These types are tokenized on ':'; strings are not tokenized
		 * at all (i.e., they consume the remainder of the line) */
		if (t == PARSE_T_INT || t == PARSE_T_SYM || t == PARSE_T_RAND ||
			t == PARSE_T_UINT) {
			tok = strtok(sp, ":");
			sp = NULL;
		} else if (t == PARSE_T_CHAR) {
			tok = strtok(sp, "");
			if (tok)
				sp = tok + 2;
		} else {
			tok = strtok(sp, "");
			sp = NULL;
		}
		if (!tok) {
			if (!(s->type & PARSE_T_OPT)) {
				my_strcpy(p->errmsg, s->name, sizeof(p->errmsg));
				p->error = PARSE_ERROR_MISSING_FIELD;
				mem_free(cline);
				return PARSE_ERROR_MISSING_FIELD;
			}
			break;
		}

		/* Allocate a value node. */
		v = mem_alloc(sizeof *v);
		v->spec.next = NULL;
		v->spec.type = s->type;
		v->spec.name = s->name;

		/* Parse out its value. */
		if (t == PARSE_T_INT) {
			char *z = NULL;
			v->u.ival = strtol(tok, &z, 0);
			if (z == tok) {
				mem_free(v);
				mem_free(cline);
				my_strcpy(p->errmsg, s->name, sizeof(p->errmsg));
				p->error = PARSE_ERROR_NOT_NUMBER;
				return PARSE_ERROR_NOT_NUMBER;
			}
		} else if (t == PARSE_T_UINT) {
			char *z = NULL;
			v->u.uval = strtoul(tok, &z, 0);
			if (z == tok || *tok == '-') {
				mem_free(v);
				mem_free(cline);
				my_strcpy(p->errmsg, s->name, sizeof(p->errmsg));
				p->error = PARSE_ERROR_NOT_NUMBER;
				return PARSE_ERROR_NOT_NUMBER;
			}
		} else if (t == PARSE_T_CHAR) {
			text_mbstowcs(&v->u.cval, tok, 1);
		} else if (t == PARSE_T_SYM || t == PARSE_T_STR) {
			v->u.sval = string_make(tok);
		} else if (t == PARSE_T_RAND) {
			if (!parse_random(tok, &v->u.rval)) {
				mem_free(v);
				mem_free(cline);
				my_strcpy(p->errmsg, s->name, sizeof(p->errmsg));
				p->error = PARSE_ERROR_NOT_RANDOM;
				return PARSE_ERROR_NOT_RANDOM;
			}
		}

		/* Link it into the value list. */
		if (!p->fhead)
			p->fhead = v;
		else
			p->ftail->spec.next = &v->spec;
		p->ftail = v;
	}

	mem_free(cline);

	p->error = h->func(p);
	return p->error;
}
Example #24
0
static void *_cs_malloc(size_t size)
{
    return mem_alloc(size);
}
Example #25
0
void CServerBrowser::Filter()
{
	int i = 0, p = 0;
	m_NumSortedServers = 0;

	// allocate the sorted list
	if(m_NumSortedServersCapacity < m_NumServers)
	{
		if(m_pSortedServerlist)
			mem_free(m_pSortedServerlist);
		m_NumSortedServersCapacity = m_NumServers;
		m_pSortedServerlist = (int *)mem_alloc(m_NumSortedServersCapacity*sizeof(int), 1);
	}

	// filter the servers
	for(i = 0; i < m_NumServers; i++)
	{
		int Filtered = 0;

		if(g_Config.m_BrFilterEmpty && m_ppServerlist[i]->m_Info.m_NumPlayers == 0)
			Filtered = 1;
		else if(g_Config.m_BrFilterFull && m_ppServerlist[i]->m_Info.m_NumPlayers == m_ppServerlist[i]->m_Info.m_MaxPlayers)
			Filtered = 1;
		else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags&SERVER_FLAG_PASSWORD)
			Filtered = 1;
		else if(g_Config.m_BrFilterPure &&
			(str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "DM") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "TDM") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "CTF") != 0))
		{
			Filtered = 1;
		}
		else if(g_Config.m_BrFilterPureMap &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm1") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm2") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm6") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm7") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm8") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm9") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf1") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf2") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf3") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf4") == 0 ||
			str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf5") == 0)
		)
		{
			Filtered = 1;
		}
		else if(g_Config.m_BrFilterPing < m_ppServerlist[i]->m_Info.m_Latency)
			Filtered = 1;
		else if(g_Config.m_BrFilterCompatversion && str_comp_num(m_ppServerlist[i]->m_Info.m_aVersion, m_aNetVersion, 3) != 0)
			Filtered = 1;
		else
		{
			if(g_Config.m_BrFilterString[0] != 0)
			{
				int MatchFound = 0;

				m_ppServerlist[i]->m_Info.m_QuickSearchHit = 0;

				// match against server name
				if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrFilterString))
				{
					MatchFound = 1;
					m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME;
				}

				// match against players
				for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumPlayers; p++)
				{
					if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aPlayers[p].m_aName, g_Config.m_BrFilterString))
					{
						MatchFound = 1;
						m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYERNAME;
						break;
					}
				}

				// match against map
				if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrFilterString))
				{
					MatchFound = 1;
					m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME;
				}

				if(!MatchFound)
					Filtered = 1;
			}

			if(!Filtered && g_Config.m_BrFilterGametype[0] != 0)
			{
				// match against game type
				if(!str_find_nocase(m_ppServerlist[i]->m_Info.m_aGameType, g_Config.m_BrFilterGametype))
					Filtered = 1;
			}
		}

		if(Filtered == 0)
			m_pSortedServerlist[m_NumSortedServers++] = i;
	}
}
Example #26
0
static void *_cs_calloc(size_t nmemb, size_t size)
{
    return mem_alloc(nmemb * size);
}
Example #27
0
void CServerBrowser::Filter()
{
	int i = 0, p = 0;
	m_NumSortedServers = 0;

	// allocate the sorted list
	if(m_NumSortedServersCapacity < m_NumServers)
	{
		if(m_pSortedServerlist)
			mem_free(m_pSortedServerlist);
		m_NumSortedServersCapacity = m_NumServers;
		m_pSortedServerlist = (int *)mem_alloc(m_NumSortedServersCapacity*sizeof(int), 1);
	}

	// filter the servers
	for(i = 0; i < m_NumServers; i++)
	{
		int Filtered = 0;

		if(g_Config.m_BrFilterEmpty && ((g_Config.m_BrFilterSpectators && m_ppServerlist[i]->m_Info.m_NumPlayers == 0) || m_ppServerlist[i]->m_Info.m_NumClients == 0))
			Filtered = 1;
		else if(g_Config.m_BrFilterFull && ((g_Config.m_BrFilterSpectators && m_ppServerlist[i]->m_Info.m_NumPlayers == m_ppServerlist[i]->m_Info.m_MaxPlayers) ||
				m_ppServerlist[i]->m_Info.m_NumClients == m_ppServerlist[i]->m_Info.m_MaxClients))
			Filtered = 1;
		else if(g_Config.m_BrFilterPw && m_ppServerlist[i]->m_Info.m_Flags&SERVER_FLAG_PASSWORD)
			Filtered = 1;
		else if(g_Config.m_BrFilterPure &&
			(str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "DM") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "TDM") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "BALL") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "DEF") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "INF") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "INV") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "GUN") != 0 &&
			str_comp(m_ppServerlist[i]->m_Info.m_aGameType, "CTF") != 0))
		{
			Filtered = 1;
		}
		else if(g_Config.m_BrFilterPureMap &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm1") == 0) &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm2") == 0) &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "dm2") == 0) &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "grinder") == 0) &&
			!(str_comp(m_ppServerlist[i]->m_Info.m_aMap, "ctf1") == 0)
		)
		{
			// don't skip non-standard maps for a while, ever
			//Filtered = 1;
		}
		else if(g_Config.m_BrFilterPing < m_ppServerlist[i]->m_Info.m_Latency)
			Filtered = 1;
		else if(g_Config.m_BrFilterCompatversion && str_comp_num(m_ppServerlist[i]->m_Info.m_aVersion, m_aNetVersion, 3) != 0)
			Filtered = 1;
		else if(g_Config.m_BrFilterServerAddress[0] && !str_find_nocase(m_ppServerlist[i]->m_Info.m_aAddress, g_Config.m_BrFilterServerAddress))
			Filtered = 1;
		else if(g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && str_comp_nocase(m_ppServerlist[i]->m_Info.m_aGameType, g_Config.m_BrFilterGametype))
			Filtered = 1;
		else if(!g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && !str_find_nocase(m_ppServerlist[i]->m_Info.m_aGameType, g_Config.m_BrFilterGametype))
			Filtered = 1;
		else
		{
			if(g_Config.m_BrFilterCountry)
			{
				Filtered = 1;
				// match against player country
				for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++)
				{
					if(m_ppServerlist[i]->m_Info.m_aClients[p].m_Country == g_Config.m_BrFilterCountryIndex)
					{
						Filtered = 0;
						break;
					}
				}
			}

			if(!Filtered && g_Config.m_BrFilterString[0] != 0)
			{
				int MatchFound = 0;

				m_ppServerlist[i]->m_Info.m_QuickSearchHit = 0;

				// match against server name
				if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aName, g_Config.m_BrFilterString))
				{
					MatchFound = 1;
					m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME;
				}

				// match against players
				for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++)
				{
					if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aClients[p].m_aName, g_Config.m_BrFilterString) ||
						str_find_nocase(m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan, g_Config.m_BrFilterString))
					{
						MatchFound = 1;
						m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYER;
						break;
					}
				}

				// match against map
				if(str_find_nocase(m_ppServerlist[i]->m_Info.m_aMap, g_Config.m_BrFilterString))
				{
					MatchFound = 1;
					m_ppServerlist[i]->m_Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME;
				}

				if(!MatchFound)
					Filtered = 1;
			}
		}

		if(Filtered == 0)
		{
			// check for friend
			m_ppServerlist[i]->m_Info.m_FriendState = IFriends::FRIEND_NO;
			for(p = 0; p < m_ppServerlist[i]->m_Info.m_NumClients; p++)
			{
				m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState = m_pFriends->GetFriendState(m_ppServerlist[i]->m_Info.m_aClients[p].m_aName,
					m_ppServerlist[i]->m_Info.m_aClients[p].m_aClan);
				m_ppServerlist[i]->m_Info.m_FriendState = max(m_ppServerlist[i]->m_Info.m_FriendState, m_ppServerlist[i]->m_Info.m_aClients[p].m_FriendState);
			}

			if(!g_Config.m_BrFilterFriends || m_ppServerlist[i]->m_Info.m_FriendState != IFriends::FRIEND_NO)
				m_pSortedServerlist[m_NumSortedServers++] = i;
		}
	}
}
Example #28
0
T create_III_side_info() {
    T t;
    t = (T)mem_alloc((long) sizeof(*t), "side_info");
    
    return t;
}
isc_result_t
dst__openssl_init(const char *engine) {
	isc_result_t result;
#ifdef USE_ENGINE
	ENGINE *re;
#else

	UNUSED(engine);
#endif

#ifdef  DNS_CRYPTO_LEAKS
	CRYPTO_malloc_debug_init();
	CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif
	CRYPTO_set_mem_functions(mem_alloc, mem_realloc, mem_free);
	nlocks = CRYPTO_num_locks();
	locks = mem_alloc(sizeof(isc_mutex_t) * nlocks);
	if (locks == NULL)
		return (ISC_R_NOMEMORY);
	result = isc_mutexblock_init(locks, nlocks);
	if (result != ISC_R_SUCCESS)
		goto cleanup_mutexalloc;
	CRYPTO_set_locking_callback(lock_callback);
	CRYPTO_set_id_callback(id_callback);

	ERR_load_crypto_strings();

	rm = mem_alloc(sizeof(RAND_METHOD));
	if (rm == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup_mutexinit;
	}
	rm->seed = NULL;
	rm->bytes = entropy_get;
	rm->cleanup = NULL;
	rm->add = entropy_add;
	rm->pseudorand = entropy_getpseudo;
	rm->status = entropy_status;

#ifdef USE_ENGINE
	OPENSSL_config(NULL);

	if (engine != NULL && *engine == '\0')
		engine = NULL;

	if (engine != NULL) {
		e = ENGINE_by_id(engine);
		if (e == NULL) {
			result = DST_R_NOENGINE;
			goto cleanup_rm;
		}
		/* This will init the engine. */
		if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
			result = DST_R_NOENGINE;
			goto cleanup_rm;
		}
	}

	re = ENGINE_get_default_RAND();
	if (re == NULL) {
		re = ENGINE_new();
		if (re == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup_rm;
		}
		ENGINE_set_RAND(re, rm);
		ENGINE_set_default_RAND(re);
		ENGINE_free(re);
	} else
		ENGINE_finish(re);
#else
	RAND_set_rand_method(rm);
#endif /* USE_ENGINE */
	return (ISC_R_SUCCESS);

#ifdef USE_ENGINE
 cleanup_rm:
	if (e != NULL)
		ENGINE_free(e);
	e = NULL;
	mem_free(rm);
	rm = NULL;
#endif
 cleanup_mutexinit:
	CRYPTO_set_locking_callback(NULL);
	DESTROYMUTEXBLOCK(locks, nlocks);
 cleanup_mutexalloc:
	mem_free(locks);
	locks = NULL;
	return (result);
}
Example #30
0
File: lecs.c Project: ysleu/RTL8685
int main(int argc, char **argv)
{
  int i =0;
  char *config_file =NULL;
  char *listen_addr = NULL;
  int fd_arr[MAX_FD];
  int no_fds=1;
  int just_dump=0;
  fd_set fds;
  struct sockaddr_atmsvc client;
  int len;
  unsigned char buffer[P_SIZE];

  while(i!=-1) {
    i = getopt(argc, argv, "f:l:d");
    switch(i) {
    case 'd':
      printf("Dumping databasefile\n");
      just_dump=1;
      break;
    case 'f':
      if (config_file) {
	usage(argv[0]);
	exit(-1);
      }
      config_file = (char*)mem_alloc(COMP_NAME, strlen(optarg)+1);
      if (!config_file) {
	exit(-1);
      }
      memcpy(config_file, optarg, strlen(optarg)+1);
      break;
    case 'l':
      if (listen_addr) {
	usage(argv[0]);
	exit(-1);
      }
      listen_addr = (char*)mem_alloc(COMP_NAME, strlen(optarg)+1);
      if (!listen_addr)
	exit(-1);
      memcpy(listen_addr, optarg, strlen(optarg)+1);
      break;
    case -1:
      break;
    default:
      usage(argv[0]);
      exit(-1);
    }
  }
  if (argc != optind) {
    usage(argv[0]);
    exit(-1);
  }
  /* Following gets run in the beginning or when lecs is restarted */
  while (stay_alive) {

    /* Read configuration file */
    if (config_file) {
      if (load_db(config_file)<0)
	exit(-1);
    } else {
      if (load_db(DEFAULT_CONFIG)<0)
	exit(-1);
    }
    if (just_dump) {
      dump_db(NULL);
      exit(0);
    }

    /* Reserve signals */
    signal(SIGHUP, sig_reset);
    signal(SIGINT, sig_kill);
    signal(SIGQUIT, sig_kill);
    signal(SIGABRT, sig_kill);
    signal(SIGTERM, sig_kill);
    signal(SIGSEGV, sig_kill);
    
    /* CHANGE: First parameter, then configuration file! */
    fd_arr[0] = atm_create_socket(CONFIGURATION_DIRECT, 
				  get_lecs_addr());
    no_fds=1;
    if (fd_arr[0] <0) {
      stay_alive=0; /* No need to go on */
    }
    while(!reset && stay_alive) {
      FD_ZERO(&fds);
      for(i=0;i<no_fds;i++) {
	FD_SET(fd_arr[i],&fds);
      }
      
      if (select(MAX_FD, &fds, NULL, NULL, NULL)<0) {
	perror("select(MAX_FD,...)");
	stay_alive=0;
      } else {
	if (FD_ISSET(fd_arr[0],&fds)) { /* Incoming call */
	  if (no_fds == MAX_FD) {
	    close(fd_arr[1]); /* Oldest */
	    memmove(&fd_arr[1], &fd_arr[2], sizeof(int)*(MAX_FD-2));
	    no_fds--;
	  }
	  len = sizeof(client);
	  fd_arr[no_fds] = accept(fd_arr[0], (struct sockaddr*)&client,
				  &len);
	  if (fd_arr[no_fds]<0) {
	    if (errno==ENETRESET)
	      reset=1;
	    if (errno==EUNATCH)
	      stay_alive=1;
	  } else {
	    no_fds++;
	  }
	}
	for(i=1;i<no_fds;i++) {
	  if (FD_ISSET(fd_arr[i],&fds)) {
	    len = read(fd_arr[i], buffer, P_SIZE);
	    if (len <0 && (errno == ENETRESET || errno == EUNATCH)) {
	      reset=0;
	    }
	    if (len<=0) {
	      close(fd_arr[i]);
	      memmove(&fd_arr[i], &fd_arr[i+1], sizeof(int)*(--no_fds -i));
	      i--;
	    } else {
	      if(send_response(fd_arr[i], buffer, len)<0) {
		close(fd_arr[i]);
		memmove(&fd_arr[i], &fd_arr[i+1], sizeof(int)*(--no_fds -i));
	      }
	    }
	  }
	}
      }
    }
    /* This gets done if a signal has been caught, or if
       network resets/becomes unavailable */
    reset=0;
    for(i=0;i<no_fds;i++)
      close(fd_arr[i]);
    no_fds=0;
    reset_db();
  }
  return 0;
}