コード例 #1
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
//нужно учитывать выравнивание
UINT8_T sector_Create(UINT8_T count,UINT8_T aligment)
{
	sl=(SectorList*)local_malloc(sizeof(SectorList)); //размер структуры с описанием секторов
	if(sl==NULL)
		return ERR_LOCAL_MALLOC;

	memset((void*)sl,0x00,sizeof(SectorList));

	//с учетом выравнивания памяти сектора
	sl->sector=(SectorInfo*)local_malloc((sizeof(SectorInfo)*count+(aligment-1)) &  ~(aligment-1));
	if(sl->sector==NULL)
	{
		local_free((void*)sl);
		sl=NULL;
		return ERR_LOCAL_MALLOC;
	}

	memset((void*)sl->sector,0x00,sizeof(SectorInfo)*count);

	xStart=(BlockLink*)local_malloc(sizeof(BlockLink));
	if( (xStart==NULL) )
	{
		local_free((void*)sl->sector);
		local_free((void*)sl);
		sl=NULL;
		return ERR_LOCAL_MALLOC;
	}

	sl->sector_counter=count;

	ApplicationSectorPrepareHook();
	
	return ERR_OK;
}
コード例 #2
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/* parses a PTR record into a ptr_rdata structure */
struct ptr_rdata* dns_ptr_parser( unsigned char* msg, unsigned char* end,
									  unsigned char* rdata)
{
	struct ptr_rdata* pname;
	int len;
	char name[MAX_DNS_NAME];
	
	pname=0;
	if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)==-1)
		goto error;
	len=strlen(name);
	if (len>255)
		goto error;
	/* alloc sizeof struct + space for the null terminated name */
	pname=local_malloc(sizeof(struct ptr_rdata)-1+len+1);
	if(pname==0){
		LOG(L_ERR, "ERROR: dns_ptr_parser: out of memory\n");
		goto error;
	}
	pname->ptrdname_len=len;
	memcpy(pname->ptrdname, name, pname->ptrdname_len);
	pname->ptrdname[pname->ptrdname_len]=0;
	return pname;
error:
	if (pname) local_free(pname);
	return 0;
}
コード例 #3
0
ファイル: resolve.c プロジェクト: btriller/kamailio
/** parses a CNAME record into a cname_rdata structure */
struct cname_rdata* dns_cname_parser( unsigned char* msg, unsigned char* end,
									  unsigned char* rdata)
{
	struct cname_rdata* cname;
	int len;
	char name[MAX_DNS_NAME];
	
	cname=0;
	if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)==-1)
		goto error;
	len=strlen(name);
	if (len>255)
		goto error;
	/* alloc sizeof struct + space for the null terminated name */
	cname=local_malloc(sizeof(struct cname_rdata)-1+len+1);
	if(cname==0){
		LM_ERR("out of memory\n");
		goto error;
	}
	cname->name_len=len;
	memcpy(cname->name, name, cname->name_len);
	cname->name[cname->name_len]=0;
	return cname;
error:
	if (cname) local_free(cname);
	return 0;
}
コード例 #4
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T WriteBlockLink(UINT8_T index, BlockLink *bl)
{
	UINT16_T crc;
	UINT8_T	 *buf;
	UINT8_T	 i;

	buf=(UINT8_T*)local_malloc(sl->sector[index].bl_size);

	if(buf==NULL)
		return ERR_LOCAL_MALLOC;

	memset((void*)buf,0x00,sl->sector[index].bl_size);

	//сформировать пакет для записи и сгенерить crc16 если требуется
	//копируем заголовок сегмента в массив для записи
	i=0;
	memcpy((void*)buf,(void*)&bl->body.pxNextFreeBlock,sl->sector[index].StartAddrLen);
	i=sl->sector[index].StartAddrLen;
	memcpy((void*)(buf+i),(void*)&bl->body.xBlockSize,sl->sector[index].SectorSizeLen);
	i+=sl->sector[index].SectorSizeLen;

	if((sl->sector[index].Type & SECTOR_CRC)>0)
	{
		Crc16_Clear();
		crc=Crc16(buf,i);
		memcpy((void*)(buf+i),(void*)&crc,sizeof(UINT16_T));
	}

	i=ERR_OK;

	i=sector_write(index, bl->pxCurrentAddr, (void*)buf, sl->sector[index].bl_size);

	local_free(buf);
	return i;
}
コード例 #5
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T	sector_Free(UINT8_T index, UINT32_T pv )
{
	UINT32_T puc=pv;
	BlockLink *pxLink=NULL;
	UINT8_T err=ERR_OK;

	if(sl==NULL)
	{
		err=ERR_SL_NULL;
		goto exit;
	}

	pxLink=(BlockLink*)local_malloc(sizeof(BlockLink));

	if(pxLink==NULL)
	{
		err=ERR_LOCAL_MALLOC;
		goto exit;
	}

	memset((void*)pxLink,0x00,sizeof(BlockLink));

	if( pv != 0 )
	{
		/* The memory being freed will have an BlockLink_t structure immediately
		before it. */
		puc -= sl->sector[index].bl_size;

		/* This casting is to keep the compiler from issuing warnings. */
		pxLink->pxCurrentAddr=puc;
		err=ReadBlockLink(index,pxLink);
		if(err!=ERR_OK)
			goto exit;

		if( ( pxLink->body.xBlockSize & (UINT32_T)(0x01 << ((8*sl->sector[index].SectorSizeLen)-1)) ) != 0 )								//!!!!!!!!!!!!!!
		{
			if( pxLink->body.pxNextFreeBlock == 0 )
			{
				/* The block is being returned to the heap - it is no longer
				allocated. */
				pxLink->body.xBlockSize&=~(UINT32_T)(0x01 << ((8*sl->sector[index].SectorSizeLen)-1));

				/* Add this block to the list of free blocks. */
				sl->sector[index].FreeBytesRemaining+=pxLink->body.xBlockSize;
				prvInsertBlockIntoFreeList(index,pxLink);
			}
		}
	}

exit:
	local_free((void*)pxLink);

	return err;
}
コード例 #6
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/*  TXT rdata format:
 *
 * one or several character strings:
 *  01234567
 * +--------------------+
 * | len    | string   / ...
 * |------------------+
 */
static struct txt_rdata* dns_txt_parser(unsigned char* msg, unsigned char* end,
										unsigned char* rdata)
{
	struct txt_rdata* txt;
	int len, n, i;
	int str_size;
	unsigned char* p;
	unsigned char* st;
	
	txt=0;
	if (unlikely((rdata+1)>end)) goto error;
	n=0;
	str_size=0;
	/* count the number of strings */
	p=rdata;
	do{
		len=*p;
		p+=len+1;
		str_size+=len+1; /* 1 for the term. 0 */
		if (unlikely(p>end)) goto error;
		n++;
	}while(p<end);
	/* alloc sizeof struct + space for the dns_cstr array + space for
	   the strings */
	txt=local_malloc(sizeof(struct txt_rdata) +(n-1)*sizeof(struct dns_cstr)+
						str_size);
	if(unlikely(txt==0)){
		LOG(L_ERR, "ERROR: dns_txt_parser: out of memory\n");
		goto error;
	}
	/* string table */
	st=(unsigned char*)txt+sizeof(struct txt_rdata) +
		(n-1)*sizeof(struct dns_cstr);
	txt->cstr_no=n;
	txt->tslen=str_size;
	/* fill the structure */
	p=rdata;
	for (i=0; i<n; i++){
		len=*p;
		memcpy(st, p+1, len);
		st[len]=0;
		txt->txt[i].cstr_len=len;
		txt->txt[i].cstr=(char*)st;
		st+=len+1;
		p+=len+1;
	}
	return txt;
error:
	if (txt) local_free(txt);
	return 0;
}
コード例 #7
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/* parses an AAAA (ipv6) record rdata into an aaaa_rdata structure
 * returns 0 on error or a dyn. alloc'ed aaaa_rdata struct */
struct aaaa_rdata* dns_aaaa_parser(unsigned char* rdata, unsigned char* eor)
{
	struct aaaa_rdata* aaaa;
	
	if (rdata+16>eor) goto error;
	aaaa=(struct aaaa_rdata*)local_malloc(sizeof(struct aaaa_rdata));
	if (aaaa==0){
		LOG(L_ERR, "ERROR: dns_aaaa_parser: out of memory\n");
		goto error;
	}
	memcpy(aaaa->ip6, rdata, 16);
	return aaaa;
error:
	return 0;
}
コード例 #8
0
ファイル: resolve.c プロジェクト: btriller/kamailio
/** parses an A record rdata into an a_rdata structure
 * returns 0 on error or a dyn. alloc'ed a_rdata struct
 */
struct a_rdata* dns_a_parser(unsigned char* rdata, unsigned char* eor)
{
	struct a_rdata* a;
	
	if (rdata+4>eor) goto error;
	a=(struct a_rdata*)local_malloc(sizeof(struct a_rdata));
	if (a==0){
		LM_ERR("out of memory\n");
		goto error;
	}
	memcpy(a->ip, rdata, 4);
	return a;
error:
	return 0;
}
コード例 #9
0
ファイル: imp_1199.c プロジェクト: Cubiicle/lmms
static LADSPA_Handle instantiateImp(
 const LADSPA_Descriptor *descriptor,
 unsigned long s_rate) {
	Imp *plugin_data = (Imp *)malloc(sizeof(Imp));
	fftw_real *block_freq = NULL;
	fftw_real *block_time = NULL;
	unsigned int count;
	fftw_real **impulse_freq = NULL;
	unsigned long in_ptr;
	fftw_real *op = NULL;
	LADSPA_Data *opc = NULL;
	unsigned long out_ptr;
	LADSPA_Data *overlap = NULL;

#line 135 "imp_1199.xml"
	unsigned int i;

	impulse_freq = local_malloc(IMPULSES * sizeof(fftw_real *));
	for (i=0; i<IMPULSES; i++) {
	  impulse_freq[i] = local_malloc(MAX_FFT_LENGTH * sizeof(fftw_real));
	}

	block_time = local_malloc(MAX_FFT_LENGTH * sizeof(fftw_real));
	block_freq = local_malloc(MAX_FFT_LENGTH * sizeof(fftw_real));
	op = local_malloc(MAX_FFT_LENGTH * sizeof(fftw_real));
	overlap = local_malloc(MAX_FFT_LENGTH * sizeof(float));
	opc = local_malloc(SEG_LENGTH * sizeof(LADSPA_Data));

	/* transform the impulses */
	real_in = block_time;
	comp_out = block_freq;
	comp_in = block_freq;
	real_out = op;
	mk_imps(impulse_freq);

	in_ptr = 0;
	out_ptr = 0;
	count = 0;

	plugin_data->block_freq = block_freq;
	plugin_data->block_time = block_time;
	plugin_data->count = count;
	plugin_data->impulse_freq = impulse_freq;
	plugin_data->in_ptr = in_ptr;
	plugin_data->op = op;
	plugin_data->opc = opc;
	plugin_data->out_ptr = out_ptr;
	plugin_data->overlap = overlap;

	return (LADSPA_Handle)plugin_data;
}
コード例 #10
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T ReadBlockLink(UINT8_T index , BlockLink *bl)
{
	UINT16_T crc;
	UINT8_T	 *buf;
	UINT8_T	 i;
	UINT8_T	 err=ERR_OK;

	buf=(UINT8_T*)local_malloc(sl->sector[index].bl_size);

	if(buf==NULL)
		return ERR_LOCAL_MALLOC;

	err=sector_read(index, bl->pxCurrentAddr, (void*)buf, sl->sector[index].bl_size);

	if(err!=ERR_OK)
		goto exit;

	//проверка CRC если требуется
	if((sl->sector[index].Type & SECTOR_CRC)>0)
	{
		Crc16_Clear();
		i=sl->sector[index].StartAddrLen + sl->sector[index].SectorSizeLen; //размер структуры BlockLink
		crc=Crc16(buf,i);
		
		err=memcmp((void*)(buf+i),(void*)&crc,sizeof(UINT16_T));
		if(err!=0x00)
		{
			err=ERR_CRC;
			goto exit;
		}
	}

	//загружаем в структуру
	i=sl->sector[index].StartAddrLen;
	bl->body.pxNextFreeBlock=0;
	memcpy((void*)&bl->body.pxNextFreeBlock,(void*)buf,i);
	bl->body.xBlockSize=0;
	memcpy((void*)&bl->body.xBlockSize,(void*)(buf+i),sl->sector[index].SectorSizeLen);

exit:
	local_free(buf);

	return err;
}
コード例 #11
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/* SRV rdata format:
 *            111111
 *  0123456789012345
 * +----------------+
 * |     priority   |
 * |----------------|
 * |     weight     |
 * |----------------|
 * |   port number  |
 * |----------------|
 * |                |
 * ~      name      ~
 * |                |
 * +----------------+
 */
struct srv_rdata* dns_srv_parser( unsigned char* msg, unsigned char* end,
								  unsigned char* eor,
								  unsigned char* rdata)
{
	struct srv_rdata* srv;
	unsigned short priority;
	unsigned short weight;
	unsigned short port;
	int len;
	char name[MAX_DNS_NAME];
	
	srv=0;
	if ((rdata+6+1)>eor) goto error;
	
	memcpy((void*)&priority, rdata, 2);
	memcpy((void*)&weight,   rdata+2, 2);
	memcpy((void*)&port,     rdata+4, 2);
	rdata+=6;
	if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)<0)
		goto error;
	len=strlen(name);
	if (len>255)
		goto error;
	/* alloc enought space for the struct + null terminated name */
	srv=local_malloc(sizeof(struct srv_rdata)-1+len+1);
	if (srv==0){
		LOG(L_ERR, "ERROR: dns_srv_parser: out of memory\n");
		goto error;
	}
	srv->priority=ntohs(priority);
	srv->weight=ntohs(weight);
	srv->port=ntohs(port);
	srv->name_len=len;
	memcpy(srv->name, name, srv->name_len);
	srv->name[srv->name_len]=0;
	
	return srv;
error:
	if (srv) local_free(srv);
	return 0;
}
コード例 #12
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/*  EBL rdata format:
 *  (see http://tools.ietf.org/html/draft-ietf-enum-branch-location-record-03)
 * one or several character strings:
 *  01234567
 * +--------+
 * | postion|
 * +-----------+
 * / separator /
 * +-----------+
 * /   apex    /
 * +----------+
 *
 * where separator is a character string ( 8 bit len, followed by len chars)
 * and apex is a domain-name.
 */
static struct ebl_rdata* dns_ebl_parser(unsigned char* msg, unsigned char* end,
										unsigned char* eor,
										unsigned char* rdata)
{
	struct ebl_rdata* ebl;
	int sep_len;
	int apex_len;
	char apex[MAX_DNS_NAME];
	
	ebl=0;
	/* check if len is at least 4 chars (minimum possible):
	     pos (1 byte) +  sep. (min 1 byte) + apex (min. 2 bytes) 
	   and also check if rdata+1 (pos) + 1 (sep. len) + sep_len + 1 is ok*/
	if (unlikely(((rdata+4)>eor)||((rdata+1+1+rdata[1]+2)>eor))) goto error;
	sep_len=rdata[1];
	if (unlikely(dn_expand(msg, end, rdata+1+1+sep_len,
							apex, MAX_DNS_NAME-1)==-1))
		goto error;
	apex_len=strlen(apex);
	/* alloc sizeof struct + space for the 2 null-terminated strings */
	ebl=local_malloc(sizeof(struct ebl_rdata)-1+sep_len+1+apex_len+1);
	if (ebl==0){
		LOG(L_ERR, "ERROR: dns_ebl_parser: out of memory\n");
		goto error;
	}
	ebl->position=rdata[0];
	ebl->separator=&ebl->str_table[0];
	ebl->apex=ebl->separator+sep_len+1;
	ebl->separator_len=sep_len;
	ebl->apex_len=apex_len;
	memcpy(ebl->separator, rdata+2, sep_len);
	ebl->separator[sep_len]=0;
	memcpy(ebl->apex, apex, apex_len);
	ebl->apex[apex_len]=0;
	
	return ebl;
error:
	if (ebl) local_free(ebl);
	return 0;
}
コード例 #13
0
ファイル: io_wait.c プロジェクト: BeIP/opensips
/*!
 * \brief initializes the static vars/arrays
 * \param  h - pointer to the io_wait_h that will be initialized
 * \param  max_fd - maximum allowed fd number
 * \param  poll_method - poll method (0 for automatic best fit)
 */
int init_io_wait(io_wait_h* h, char *name, int max_fd,
								enum poll_types poll_method, int max_prio)
{
	char * poll_err;

	memset(h, 0, sizeof(*h));
	h->name = name;
	h->max_prio = max_prio;
	h->max_fd_no=max_fd;
#ifdef HAVE_EPOLL
	h->epfd=-1;
#endif
#ifdef HAVE_KQUEUE
	h->kq_fd=-1;
#endif
#ifdef HAVE_DEVPOLL
	h->dpoll_fd=-1;
#endif
	poll_err=check_poll_method(poll_method);

	/* set an appropiate poll method */
	if (poll_err || (poll_method==0)){
		poll_method=choose_poll_method();
		if (poll_err){
			LM_ERR("%s, using %s instead\n",
					poll_err, poll_method_str[poll_method]);
		}else{
			LM_INFO("using %s as the io watch method"
					" (auto detected)\n", poll_method_str[poll_method]);
		}
	}

	h->poll_method=poll_method;

	/* common stuff, everybody has fd_hash */
	h->fd_hash=local_malloc(sizeof(*(h->fd_hash))*h->max_fd_no);
	if (h->fd_hash==0){
		LM_CRIT("could not alloc fd hashtable (%ld bytes)\n",
					(long)sizeof(*(h->fd_hash))*h->max_fd_no );
		goto error;
	}
	memset((void*)h->fd_hash, 0, sizeof(*(h->fd_hash))*h->max_fd_no);

	/* init the fd array as needed for priority ordering */
	h->fd_array=local_malloc(sizeof(*(h->fd_array))*h->max_fd_no);
	if (h->fd_array==0){
		LM_CRIT("could not alloc fd array (%ld bytes)\n",
					(long)sizeof(*(h->fd_hash))*h->max_fd_no);
		goto error;
	}
	memset((void*)h->fd_array, 0, sizeof(*(h->fd_array))*h->max_fd_no);
	/* array with indexes in fd_array where the priority changes */
	h->prio_idx=local_malloc(sizeof(*(h->prio_idx))*h->max_prio);
	if (h->prio_idx==0){
		LM_CRIT("could not alloc fd array (%ld bytes)\n",
					(long)sizeof(*(h->prio_idx))*h->max_prio);
		goto error;
	}
	memset((void*)h->prio_idx, 0, sizeof(*(h->prio_idx))*h->max_prio);

	switch(poll_method){
		case POLL_POLL:
			break;
#ifdef HAVE_SELECT
		case POLL_SELECT:
			if ((poll_method==POLL_SELECT) && (init_select(h)<0)){
				LM_CRIT("select init failed\n");
				goto error;
			}
			break;
#endif
#ifdef HAVE_DEVPOLL
		case POLL_DEVPOLL:
			if ((poll_method==POLL_DEVPOLL) && (init_devpoll(h)<0)){
				LM_CRIT("/dev/poll init failed\n");
				goto error;
			}
			h->dp_changes=local_malloc(sizeof(*(h->dp_changes))*h->max_fd_no);
			if (h->dp_changes==0){
				LM_CRIT("could not alloc db changes array (%ld bytes)\n",
							(long)sizeof(*(h->dp_changes))*h->max_fd_no);
				goto error;
			}
			memset((void*)h->dp_changes, 0,
				sizeof(*(h->dp_changes))*h->max_fd_no);
			break;
#endif
#ifdef HAVE_SIGIO_RT
		case POLL_SIGIO_RT:
			if ((poll_method==POLL_SIGIO_RT) && (init_sigio(h, 0)<0)){
				LM_CRIT("sigio init failed\n");
				goto error;
			}
			break;
#endif
#ifdef HAVE_EPOLL
		case POLL_EPOLL_LT:
		case POLL_EPOLL_ET:
			h->ep_array=local_malloc(sizeof(*(h->ep_array))*h->max_fd_no);
			if (h->ep_array==0){
				LM_CRIT("could not alloc epoll array\n");
				goto error;
			}
			memset((void*)h->ep_array, 0, sizeof(*(h->ep_array))*h->max_fd_no);
			if (init_epoll(h)<0){
				LM_CRIT("epoll init failed\n");
				goto error;
			}
			break;
#endif
#ifdef HAVE_KQUEUE
		case POLL_KQUEUE:
			h->kq_array=local_malloc(sizeof(*(h->kq_array))*h->max_fd_no);
			if (h->kq_array==0){
				LM_CRIT("could not alloc kqueue event array\n");
				goto error;
			}
			h->kq_changes_size=KQ_CHANGES_ARRAY_SIZE;
			h->kq_changes=local_malloc(sizeof(*(h->kq_changes))*
										h->kq_changes_size);
			if (h->kq_changes==0){
				LM_CRIT("could not alloc kqueue changes array\n");
				goto error;
			}
			h->kq_nchanges=0;
			memset((void*)h->kq_array, 0, sizeof(*(h->kq_array))*h->max_fd_no);
			memset((void*)h->kq_changes, 0,
						sizeof(*(h->kq_changes))* h->kq_changes_size);
			if (init_kqueue(h)<0){
				LM_CRIT("kqueue init failed\n");
				goto error;
			}
			break;
#endif
		default:
			LM_CRIT("unknown/unsupported poll method %s (%d)\n",
						poll_method_str[poll_method], poll_method);
			goto error;
	}
	return 0;
error:
	return -1;
}
コード例 #14
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T prvInsertBlockIntoFreeList(UINT8_T index, BlockLink *pxBlockToInsert )
{
	BlockLink *pxIterator,*pxBlockToInsertBuf=NULL;
	UINT8_T err=ERR_OK;

	pxBlockToInsertBuf=(BlockLink*)local_malloc(sizeof(BlockLink));

	if(pxBlockToInsertBuf==NULL)
	{
		err=ERR_LOCAL_MALLOC;
		goto exit;
	}

	memset((void*)pxBlockToInsertBuf,0x00,sizeof(BlockLink));

	//чтение сектора xStart
	xStart->pxCurrentAddr=sl->sector[index].xStart_Addr;
	err=ReadBlockLink(index, xStart);
	if(err!=ERR_OK)
		goto exit;

	/* Iterate through the list until a block is found that has a higher address
	than the block being inserted. */
	pxIterator = xStart;

	while(pxIterator->body.pxNextFreeBlock < pxBlockToInsert->pxCurrentAddr)
	{
		pxIterator->pxCurrentAddr=pxIterator->body.pxNextFreeBlock;
		err=ReadBlockLink(index,pxIterator);
		if(err!=ERR_OK)
			goto exit;
	}

	/* Do the block being inserted, and the block it is being inserted after
	make a contiguous block of memory? */
	if( (pxIterator->pxCurrentAddr + pxIterator->body.xBlockSize ) == pxBlockToInsert->pxCurrentAddr )
	{
		pxIterator->body.xBlockSize+=pxBlockToInsert->body.xBlockSize;
		pxBlockToInsert = pxIterator;

		#if (configUSE_SegmentCounter==TRUE)
		sl->sector[index].xSegmentCounter--;
		#endif
	}

	/* Do the block being inserted, and the block it is being inserted before
	make a contiguous block of memory? */
	if((pxBlockToInsert->pxCurrentAddr+pxBlockToInsert->body.xBlockSize)==pxIterator->body.pxNextFreeBlock)
	{
		//if(pxIterator->body.pxNextFreeBlock!=pxEnd->pxCurrentAddr) //ошибка!
		if(pxIterator->body.pxNextFreeBlock!=sl->sector[index].pxEnd_Addr)
		{
			/* Form one big block from the two blocks. */
			pxBlockToInsertBuf->pxCurrentAddr=pxIterator->body.pxNextFreeBlock;
			err=ReadBlockLink(index,pxBlockToInsertBuf);
			if(err!=ERR_OK)
				goto exit;

			pxBlockToInsert->body.xBlockSize=pxBlockToInsertBuf->body.xBlockSize;
			pxBlockToInsert->body.pxNextFreeBlock=pxBlockToInsertBuf->body.pxNextFreeBlock;

			#if (configUSE_SegmentCounter==TRUE)
			sl->sector[index].xSegmentCounter--;
			#endif
		}
		else
		{
			pxBlockToInsert->body.pxNextFreeBlock=sl->sector[index].pxEnd_Addr;//pxEnd->pxCurrentAddr;
		}
	}
	else
	{
		pxBlockToInsert->body.pxNextFreeBlock=pxIterator->body.pxNextFreeBlock;
	}

	/* If the block being inserted plugged a gab, so was merged with the block
	before and the block after, then it's pxNextFreeBlock pointer will have
	already been set, and should not be set here as that would make it point
	to itself. */
	if( pxIterator->pxCurrentAddr != pxBlockToInsert->pxCurrentAddr )
	{
		pxIterator->body.pxNextFreeBlock = pxBlockToInsert->pxCurrentAddr;
		err=WriteBlockLink(index,pxIterator);
		if(err!=ERR_OK)
			goto exit;
	}

	err=WriteBlockLink(index,pxBlockToInsert);
	//if(err!=ERR_OK)
	//	goto exit;
exit:
	local_free((void*)pxBlockToInsertBuf);

	return ERR_OK;
}
コード例 #15
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/* NAPTR rdata format:
 *            111111
 *  0123456789012345
 * +----------------+
 * |      order     |
 * |----------------|
 * |   preference   |
 * |----------------|
 * ~     flags      ~
 * |   (string)     |
 * |----------------|
 * ~    services    ~
 * |   (string)     |
 * |----------------|
 * ~    regexp      ~
 * |   (string)     |
 * |----------------|
 * ~  replacement   ~
   |    (name)      |
 * +----------------+
 */
struct naptr_rdata* dns_naptr_parser( unsigned char* msg, unsigned char* end,
										unsigned char* eor,
										unsigned char* rdata)
{
	struct naptr_rdata* naptr;
	unsigned char* flags;
	unsigned char* services;
	unsigned char* regexp;
	unsigned short order;
	unsigned short pref;
	unsigned char flags_len;
	unsigned char services_len;
	unsigned char regexp_len;
	int len;
	char repl[MAX_DNS_NAME];
	
	naptr = 0;
	if ((rdata + 7 + 1)>eor) goto error;
	
	memcpy((void*)&order, rdata, 2);
	memcpy((void*)&pref, rdata + 2, 2);
	flags_len = rdata[4];
	if ((rdata + 7 + 1 +  flags_len) > eor)
		goto error;
	flags=rdata+5;
	services_len = rdata[5 + flags_len];
	if ((rdata + 7 + 1 + flags_len + services_len) > eor)
		goto error;
	services=rdata + 6 + flags_len;
	regexp_len = rdata[6 + flags_len + services_len];
	if ((rdata + 7 +1 + flags_len + services_len + regexp_len) > eor)
		goto error;
	regexp=rdata + 7 + flags_len + services_len;
	rdata = rdata + 7 + flags_len + services_len + regexp_len;
	if (dn_expand(msg, end, rdata, repl, MAX_DNS_NAME-1) == -1)
		goto error;
	len=strlen(repl);
	if (len>255)
		goto error;
	naptr=local_malloc(sizeof(struct naptr_rdata)+flags_len+services_len+
						regexp_len+len+1-1);
	if (naptr == 0){
		LOG(L_ERR, "ERROR: dns_naptr_parser: out of memory\n");
		goto error;
	}
	naptr->order=ntohs(order);
	naptr->pref=ntohs(pref);
	
	naptr->flags=&naptr->str_table[0];
	naptr->flags_len=flags_len;
	memcpy(naptr->flags, flags, naptr->flags_len);
	naptr->services=&naptr->str_table[flags_len];
	naptr->services_len=services_len;
	memcpy(naptr->services, services, naptr->services_len);
	naptr->regexp=&naptr->str_table[flags_len+services_len];
	naptr->regexp_len=regexp_len;
	memcpy(naptr->regexp, regexp, naptr->regexp_len);
	naptr->repl=&naptr->str_table[flags_len+services_len+regexp_len];
	naptr->repl_len=len;
	memcpy(naptr->repl, repl, len);
	naptr->repl[len]=0; /* null term. */
	
	return naptr;
error:
	if (naptr) local_free(naptr);
	return 0;
}
コード例 #16
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T sector_Init(UINT8_T index)
{
	BlockLink		*pxFirstFreeBlock=NULL;
	UINT32_T		pucAlignedHeap;
	UINT32_T		ulAddress;
	UINT32_T		xTotalHeapSize;
	UINT8_T			err;

	pxFirstFreeBlock=(BlockLink*)local_malloc(sizeof(BlockLink));

	if(pxFirstFreeBlock==NULL)
		return ERR_LOCAL_MALLOC;

	/* Ensure the heap starts on a correctly aligned boundary. */
	ulAddress =	sl->sector[index].xStart_Addr + sl->sector[index].bl_size;
	xTotalHeapSize = sl->sector[index].FreeBytesRemaining - sl->sector[index].bl_size;

	if( ( ulAddress & (sl->sector[index].ByteAligment-1) ) != 0 )
	{
		ulAddress += sl->sector[index].ByteAligment-1 ;
		ulAddress &=  ~( ( UINT32_T ) (sl->sector[index].ByteAligment-1) );
		xTotalHeapSize -= ulAddress - sl->sector[index].xStart_Addr;
	}

	pucAlignedHeap = ulAddress;

	/* xStart is used to hold a pointer to the first item in the list of free
	blocks.  The void cast is used to prevent compiler warnings. */
	sl->sector[index].xStart_Addr= ulAddress - sl->sector[index].bl_size;
	xStart->pxCurrentAddr=sl->sector[index].xStart_Addr;
	xStart->body.pxNextFreeBlock=pucAlignedHeap;
	xStart->body.xBlockSize=0;

	err=WriteBlockLink(index,xStart);

	if(err==ERR_OK)
	{
		/* pxEnd is used to mark the end of the list of free blocks and is inserted
		at the end of the heap space. */
		ulAddress = ( ( UINT32_T ) pucAlignedHeap ) + xTotalHeapSize;
		ulAddress -= sl->sector[index].bl_size;
		ulAddress &= ~( (UINT32_T)(sl->sector[index].ByteAligment-1));

		//записать pxEnd используя буффер pxFirstFreeBlock
		pxFirstFreeBlock->body.pxNextFreeBlock=0;
		pxFirstFreeBlock->body.xBlockSize=0;
		sl->sector[index].pxEnd_Addr=ulAddress;
		pxFirstFreeBlock->pxCurrentAddr=sl->sector[index].pxEnd_Addr;
		err=WriteBlockLink(index,pxFirstFreeBlock);

		if(err==ERR_OK)
		{
			/* To start with there is a single free block that is sized to take up the
			entire heap space, minus the space taken by pxEnd. */
			pxFirstFreeBlock->pxCurrentAddr=pucAlignedHeap;
			pxFirstFreeBlock->body.xBlockSize= ulAddress - pucAlignedHeap;
			pxFirstFreeBlock->body.pxNextFreeBlock=sl->sector[index].pxEnd_Addr;

			err=WriteBlockLink(index,pxFirstFreeBlock);

			if(err==ERR_OK)
			{
				/* Only one block exists - and it covers the entire usable heap space. */
				sl->sector[index].FreeBytesRemaining = pxFirstFreeBlock->body.xBlockSize;

				#if (configUSE_SegmentCounter==TRUE)
				sl->sector[index].xSegmentCounter=3;
				#endif
			}
		}
	}

	local_free((void*)pxFirstFreeBlock);

	return err;
}
コード例 #17
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T	sector_Malloc(UINT8_T index,UINT32_T *addr, UINT32_T xWantedSize )
{
	BlockLink *pxBlock=NULL, *pxNewBlockLink=NULL, *pxPreviousBlock=NULL;
	UINT8_T err=ERR_OK;

	if(sl==NULL)
	{
		err=ERR_SL_NULL;
		goto exit;
	}

	pxBlock=(BlockLink*)local_malloc(sizeof(BlockLink));
	pxNewBlockLink=(BlockLink*)local_malloc(sizeof(BlockLink));

	if( (pxBlock==NULL) || (pxNewBlockLink==NULL))
	{
		err=ERR_LOCAL_MALLOC;
		goto exit;
	}

	memset((void*)pxBlock,0x00,sizeof(BlockLink));
	memset((void*)pxNewBlockLink,0x00,sizeof(BlockLink));

	/* The wanted size is increased so it can contain a BlockLink_t
	structure in addition to the requested amount of bytes. */
	if(xWantedSize==0)
	{
		err=ERR_WRONG_SIZE;
		goto exit;
	}

	xWantedSize += sl->sector[index].bl_size;

	/* Ensure that blocks are always aligned to the required number
	of bytes. */
	if((xWantedSize & (sl->sector[index].ByteAligment-1)) !=0x00)
	{
		/* Byte alignment required. */
		xWantedSize += (sl->sector[index].ByteAligment - (xWantedSize & (sl->sector[index].ByteAligment-1)));
	}

	if(xWantedSize > sl->sector[index].FreeBytesRemaining)
	{
		err=ERR_NO_FREE_SPACE;
		goto exit;
	}

	/* Traverse the list from the start	(lowest address) block until
	one	of adequate size is found. */
	//чтение сектора xStart
	xStart->pxCurrentAddr=sl->sector[index].xStart_Addr;
	err=ReadBlockLink(index, xStart);

	if(err!=ERR_OK)
		goto exit;

	pxPreviousBlock = xStart;

	pxBlock->pxCurrentAddr=xStart->body.pxNextFreeBlock;
	err=ReadBlockLink(index,pxBlock);

	if(err!=ERR_OK)
		goto exit;

	while( (pxBlock->body.xBlockSize < xWantedSize) && (pxBlock->body.pxNextFreeBlock !=0) )
	{
		pxPreviousBlock=pxBlock; //скопировать а не ссылка!

		pxBlock->pxCurrentAddr=pxBlock->body.pxNextFreeBlock;
		err=ReadBlockLink(index,pxBlock);

		if(err!=ERR_OK)
			goto exit;
	}

	/* If the end marker was reached then a block of adequate size
	was	not found. */
	if(pxBlock->pxCurrentAddr != sl->sector[index].pxEnd_Addr)
	{
		/* Return the memory space pointed to - jumping over the
		BlockLink_t structure at its start. */
		*addr=pxPreviousBlock->body.pxNextFreeBlock + sl->sector[index].bl_size;

		/* This block is being returned for use so must be taken out
		of the list of free blocks. */
		if(pxPreviousBlock->pxCurrentAddr != pxBlock->pxCurrentAddr)
		{
			pxPreviousBlock->body.pxNextFreeBlock=pxBlock->body.pxNextFreeBlock;

			err=WriteBlockLink(index,pxPreviousBlock);
			if(err!=ERR_OK)
				goto exit;
		}

		/* If the block is larger than required it can be split into
		two. */
		if( (pxBlock->body.xBlockSize - xWantedSize) > (UINT32_T)(sl->sector[index].bl_size<<1) )
		{
			/* This block is to be split into two.  Create a new
			block following the number of bytes requested. The void
			cast is used to prevent byte alignment warnings from the
			compiler. */
			pxNewBlockLink->pxCurrentAddr = pxBlock->pxCurrentAddr + xWantedSize;

			/* Calculate the sizes of two blocks split from the
			single block. */
			pxNewBlockLink->body.xBlockSize=pxBlock->body.xBlockSize - xWantedSize;
			pxNewBlockLink->body.pxNextFreeBlock=0;

			pxBlock->body.xBlockSize=xWantedSize;

			/* Insert the new block into the list of free blocks. */
			err=prvInsertBlockIntoFreeList(index , pxNewBlockLink);

			if(err!=ERR_OK)
				goto exit;

			#if (configUSE_SegmentCounter==TRUE)
			sl->sector[index].xSegmentCounter++;
			#endif
		}

		sl->sector[index].FreeBytesRemaining -= pxBlock->body.xBlockSize;

		/* The block is being returned - it is allocated and owned
		by the application and has no "next" block. */
		pxBlock->body.xBlockSize |= (UINT32_T)(0x01 << ((8*sl->sector[index].SectorSizeLen)-1));
		pxBlock->body.pxNextFreeBlock = 0;
		err=WriteBlockLink(index,pxBlock);
		//if(err!=ERR_OK)
		//	goto exit;
	}

exit:

	local_free((void*)pxBlock);
	local_free((void*)pxNewBlockLink);

	return err;
}
コード例 #18
0
ファイル: MeshKernel.cpp プロジェクト: 00liujj/trilinos
KernelSet::iterator
BulkData::declare_kernel( const EntityType arg_entity_type ,
                              const unsigned part_size ,
                              const unsigned part_ord[] )
{
  enum { KEY_TMP_BUFFER_SIZE = 32 };

  static const char method[] = "phdmesh::Kernel" ;

  const unsigned max = ~((unsigned) 0);

  KernelSet & kernel_set = m_kernels[ arg_entity_type ];

  const std::vector< FieldBase * > & field_set = m_mesh_meta_data.get_fields();

  const unsigned num_fields = field_set.size();

  //----------------------------------
  // For performance try not to allocate a temporary.

  unsigned key_tmp_buffer[ KEY_TMP_BUFFER_SIZE ];

  std::vector<unsigned> key_tmp_vector ;

  const unsigned key_size = 2 + part_size ;

  unsigned * const key =
    ( key_size <= KEY_TMP_BUFFER_SIZE )
    ? key_tmp_buffer
    : ( key_tmp_vector.resize( key_size ) , & key_tmp_vector[0] );

  //----------------------------------
  // Key layout:
  // { part_size + 1 , { part_ordinals } , family_count }
  // Thus family_count = key[ key[0] ]
  //
  // for upper bound search use the maximum key.

  key[ key[0] = part_size + 1 ] = max ;

  {
    unsigned * const k = key + 1 ;
    for ( unsigned i = 0 ; i < part_size ; ++i ) { k[i] = part_ord[i] ; }
  }

  //----------------------------------
  // Look for the last kernel in this family:

  const unsigned * const key_const = key ;

  KernelSet::iterator ik = kernel_set.upper_bound( key_const );

  Kernel * const last_kernel =
    ( ik != kernel_set.begin() ) && kernel_part_equal( (--ik)->key() , key )
    ? ( & * ik ) : NULL ;

  Kernel          * kernel    = NULL ;
  Kernel::DataMap * field_map = NULL ;

  if ( last_kernel == NULL ) { // First kernel in this family
    key[ key[0] ] = 0 ; // Set the key's family count to zero
  }
  else { // Last kernel present, can it hold one more entity?

    field_map = last_kernel->m_field_map ;

    const unsigned last_count = last_kernel->key()[ key[0] ];

    const unsigned cap = last_kernel->capacity();

    if ( last_kernel->size() < cap ) {
      kernel = last_kernel ;
    }
    else if ( last_count < max ) {
      key[ key[0] ] = 1 + last_count ; // Increment the key's family count.
    }
    else {
      // ERROR insane number of kernels!
      std::string msg ;
      msg.append( method );
      msg.append( " FAILED due to impossibly large number of kernels" );
      throw std::logic_error( msg );
    }
  }

  //----------------------------------
  // Family's field map does not exist, create it:

  if ( NULL == field_map ) {

    field_map = reinterpret_cast<Kernel::DataMap*>(
                local_malloc( sizeof(Kernel::DataMap) * ( num_fields + 1 )));

    unsigned value_offset = 0 ;

    value_offset += align( sizeof(Entity*) * m_kernel_capacity );

    for ( unsigned i = 0 ; i < num_fields ; ++i ) {
      const FieldBase  & field = * field_set[i] ;

      unsigned value_size = 0 ;

      const FieldBase::Restriction & dim =
        dimension( field, arg_entity_type, key[0] - 1, key + 1, method);

      if ( dim.stride[0] ) { // Exists

        const unsigned scalar_size =
          NumericEnum<void>::size( field.numeric_type_ordinal() );

        const unsigned field_num_dim = field.rank();

        value_size = scalar_size *
          ( field_num_dim ? dim.stride[ field_num_dim - 1 ] : 1 );
      }

      field_map[i].m_base = value_offset ;
      field_map[i].m_size = value_size ;
      field_map[i].m_stride = dim.stride ;

      value_offset += align( value_size * m_kernel_capacity );
    }
    field_map[ num_fields ].m_base  = value_offset ;
    field_map[ num_fields ].m_size = 0 ;
    field_map[ num_fields ].m_stride = NULL ;
  }

  //----------------------------------

  if ( NULL == kernel ) {

    // Required kernel does not exist, must allocate and insert
    //
    // Allocation size:
    //   sizeof(Kernel) +
    //   key_size * sizeof(unsigned) +
    //   sizeof(Entity*) * capacity() +
    //   sum[number_of_fields]( fieldsize * capacity )

    const unsigned size = align( sizeof(Kernel) ) +
                          align( sizeof(unsigned) * key_size ) +
                          field_map[ num_fields ].m_base ;

    // All fields checked and sized, Ready to allocate

    unsigned char * ptr = (unsigned char *) local_malloc( size );

    kernel = (Kernel *) ptr ; ptr += align( sizeof(Kernel) );

    {
      unsigned * new_key = (unsigned *) ptr ;

      ptr += align( sizeof(unsigned) * key_size );

      for ( unsigned i = 0 ; i < key_size ; ++i ) { new_key[i] = key[i] ; }

      new(kernel) Kernel( *this , arg_entity_type , new_key );
    }

    kernel->m_size       = 0 ;
    kernel->m_capacity   = m_kernel_capacity ;
    kernel->m_alloc_size = size ;
    kernel->m_field_map  = field_map ;
    kernel->m_entities   = (Entity **) ptr ;

    std::pair<KernelSet::iterator,bool> result = kernel_set.insert( kernel );

    if ( ! result.second ) {
      std::string msg ;
      msg.append( method );
      msg.append( " FAILED INSERTION" );
      throw std::logic_error( msg );
    }

    ik = result.first ;

    KernelSet::iterator
      first_kernel = last_kernel ? last_kernel->m_kernel : ik ;

    first_kernel->m_kernel = ik ; // New last kernel

    ik->m_kernel = first_kernel ;
  }

  //----------------------------------

  return ik ;
}
コード例 #19
0
ファイル: io_wait.c プロジェクト: Distrotech/opensips
/*!
 * \brief initializes the static vars/arrays
 * \param  h - pointer to the io_wait_h that will be initialized
 * \param  max_fd - maximum allowed fd number
 * \param  poll_method - poll method (0 for automatic best fit)
 */
int init_io_wait(io_wait_h* h, char *name, int max_fd,
									enum poll_types poll_method, int async)
{
	char * poll_err;

	memset(h, 0, sizeof(*h));
	h->name = name;
	h->max_fd_no=max_fd;
#ifdef HAVE_EPOLL
	h->epfd=-1;
#endif
#ifdef HAVE_KQUEUE
	h->kq_fd=-1;
#endif
#ifdef HAVE_DEVPOLL
	h->dpoll_fd=-1;
#endif
	poll_err=check_poll_method(poll_method);

	/* set an appropiate poll method */
	if (poll_err || (poll_method==0)){
		poll_method=choose_poll_method();
		if (poll_err){
			LM_ERR("%s, using %s instead\n",
					poll_err, poll_method_str[poll_method]);
		}else{
			LM_INFO("using %s as the io watch method"
					" (auto detected)\n", poll_method_str[poll_method]);
		}
	}

	h->poll_method=poll_method;

	if (h->poll_method != POLL_POLL && h->poll_method != POLL_EPOLL_LT &&
		h->poll_method != POLL_EPOLL_ET) {
		if (async)
			LM_WARN("Tried to enable async polling but current poll method is %d."
				" Currently we only support POLL and EPOLL \n",h->poll_method);
		async=0;
	}

	/* common stuff, everybody has fd_hash */
	h->fd_hash=local_malloc(sizeof(*(h->fd_hash))*h->max_fd_no);
	if (h->fd_hash==0){
		LM_CRIT("could not alloc fd hashtable (%ld bytes)\n",
					(long)sizeof(*(h->fd_hash))*h->max_fd_no );
		goto error;
	}
	memset((void*)h->fd_hash, 0, sizeof(*(h->fd_hash))*h->max_fd_no);

	switch(poll_method){
		case POLL_POLL:
#ifdef HAVE_SELECT
		case POLL_SELECT:
#endif
#ifdef HAVE_SIGIO_RT
		case POLL_SIGIO_RT:
#endif
#ifdef HAVE_DEVPOLL
		case POLL_DEVPOLL:
#endif
			h->fd_array=local_malloc(sizeof(*(h->fd_array))*h->max_fd_no);
			if (h->fd_array==0){
				LM_CRIT("could not alloc fd array (%ld bytes)\n",
							(long)sizeof(*(h->fd_hash))*h->max_fd_no);
				goto error;
			}
			memset((void*)h->fd_array, 0, sizeof(*(h->fd_array))*h->max_fd_no);
#ifdef HAVE_SIGIO_RT
			if ((poll_method==POLL_SIGIO_RT) && (init_sigio(h, 0)<0)){
				LM_CRIT("sigio init failed\n");
				goto error;
			}
#endif
#ifdef HAVE_DEVPOLL
			if ((poll_method==POLL_DEVPOLL) && (init_devpoll(h)<0)){
				LM_CRIT("/dev/poll init failed\n");
				goto error;
			}
#endif
#ifdef HAVE_SELECT
			if ((poll_method==POLL_SELECT) && (init_select(h)<0)){
				LM_CRIT("select init failed\n");
				goto error;
			}
#endif

			break;
#ifdef HAVE_EPOLL
		case POLL_EPOLL_LT:
		case POLL_EPOLL_ET:
			h->ep_array=local_malloc(sizeof(*(h->ep_array))*h->max_fd_no);
			if (h->ep_array==0){
				LM_CRIT("could not alloc epoll array\n");
				goto error;
			}
			memset((void*)h->ep_array, 0, sizeof(*(h->ep_array))*h->max_fd_no);
			if (init_epoll(h)<0){
				LM_CRIT("epoll init failed\n");
				goto error;
			}
			break;
#endif
#ifdef HAVE_KQUEUE
		case POLL_KQUEUE:
			h->kq_array=local_malloc(sizeof(*(h->kq_array))*h->max_fd_no);
			if (h->kq_array==0){
				LM_CRIT("could not alloc kqueue event array\n");
				goto error;
			}
			h->kq_changes_size=KQ_CHANGES_ARRAY_SIZE;
			h->kq_changes=local_malloc(sizeof(*(h->kq_changes))*
										h->kq_changes_size);
			if (h->kq_changes==0){
				LM_CRIT("could not alloc kqueue changes array\n");
				goto error;
			}
			h->kq_nchanges=0;
			memset((void*)h->kq_array, 0, sizeof(*(h->kq_array))*h->max_fd_no);
			memset((void*)h->kq_changes, 0,
						sizeof(*(h->kq_changes))* h->kq_changes_size);
			if (init_kqueue(h)<0){
				LM_CRIT("kqueue init failed\n");
				goto error;
			}
			break;
#endif
		default:
			LM_CRIT("unknown/unsupported poll method %s (%d)\n",
						poll_method_str[poll_method], poll_method);
			goto error;
	}
	return 0;
error:
	return -1;
}
コード例 #20
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T sector_Open(UINT8_T index, UINT8_T aligment ,UINT32_T addr)
{
	UINT16_T size;
	UINT8_T	err=ERR_OK;
	SectorList *header=NULL;
	UINT8_T i;

	//подготовить
	if(aligment==0)
		return ERR_WRONG_ALIGMENT;

	size=(sizeof(SectorList)+(aligment-1)) & ~(aligment-1);
	header=(SectorList*)local_malloc( size );

	if(header==NULL)
		return ERR_LOCAL_MALLOC;

	//чтение заголовка. Учитываем выравнивание
	size=(sizeof(SectorList)-sizeof(SectorInfo*)+(aligment-1)) & ~(aligment-1);
	err=sector_read(index, addr, (void*)header, size);

	if(err==ERR_OK)
	{
		i=~header->sector_counter;
		if(i == header->crc)
		{
			//создание структур
			err=sector_Create(header->sector_counter,aligment);

			if(err==ERR_OK)
			{
				err=sector_read(index, (addr+size), (void*)sl->sector, (sizeof(SectorInfo)*sl->sector_counter + (aligment-1)) & ~(aligment-1) );

				if(err!=ERR_OK)
				{
					sector_ResourceFree();
				}
				else
				{
					sl->crc=header->crc;
					//проверка CRC16
					Crc16_Clear();
					Crc16((UINT8_T*)&sl->sector_counter,sizeof(UINT8_T));
					Crc16((UINT8_T*)&sl->crc,sizeof(UINT8_T));
					sl->crc16=Crc16((UINT8_T*)sl->sector,sizeof(SectorInfo)*sl->sector_counter);

					if(header->crc16!=sl->crc16)
					{
						sector_ResourceFree();
						err=ERR_CRC;
					}
					else
					{
						for(i=0;i<sl->sector_counter;i++)
						{
							if(sl->sector[i].Type!=SECTOR_FREE)
							{
								size=(sl->sector[index].pxEnd_Addr+sl->sector[index].bl_size)-sl->sector[index].StartAddr;
								ApplicationSectorOpenHook(i, sl->sector[i].StartAddr,size);
							}
						}
					}
				}
			}
		}
		else
		{
			err=ERR_CRC;
		}
	}

	local_free(header);
	return err;
}
コード例 #21
0
ファイル: heap.c プロジェクト: a9d/tSQL_alfa
/*-----------------------------------------------------------*/
UINT8_T sector_AddNewSector(SectorConfig* config)
{
	UINT8_T i;
	SectorInfo *si=NULL;
	UINT16_T size,total_size,prev_total_size;

	if(sl==NULL)
		return ERR_SL_NULL;

	//если есть свободное место
	for(i=0; i<(sl->sector_counter) ;i++)
	{
		if(sl->sector[i].Type==SECTOR_FREE)
		{
			config->index=i;
			return sector_Insert(config);
		}
	}

	//если нет, то remalloc
	for(i=0;i<(sl->sector_counter);i++)
	{
		//если только main
		if((sl->sector[i].Type & SECTOR_MAIN)>0)
		{
			if((sl->sector[i].Type & SECTOR_START) == 0)
			{
				//старый размер списка
				size=(sizeof(SectorInfo)*(sl->sector_counter) + (sl->sector[i].ByteAligment-1)) & ~(sl->sector[i].ByteAligment-1);
				prev_total_size= size + ((sizeof(SectorList)-sizeof(SectorInfo*))+( sl->sector[i].ByteAligment - 1)) & ~(sl->sector[i].ByteAligment-1);

				//новый размер списка с описанием секторов
				size=(sizeof(SectorInfo)*(sl->sector_counter+1) + (sl->sector[i].ByteAligment-1)) & ~(sl->sector[i].ByteAligment-1);
				total_size= size + ((sizeof(SectorList)-sizeof(SectorInfo*))+( sl->sector[i].ByteAligment - 1)) & ~(sl->sector[i].ByteAligment-1);

				if(sl->sector[i].FreeBytesRemaining < (total_size-prev_total_size))
					return ERR_NO_FREE_SPACE;
				
				si=(SectorInfo*)local_malloc( size );

				if(si==NULL)
					return ERR_LOCAL_MALLOC;

				memset((void*)si,0x00,size);
				memcpy((void*)si, (void*)sl->sector, (sizeof(SectorInfo) * sl->sector_counter));

				config->index=sl->sector_counter;

				sl->sector_counter++;
				local_free((void*)sl->sector);
				sl->sector=si;

				//скорректировать размер main сектора
				sl->sector[i].FreeBytesRemaining-=(total_size-prev_total_size);

				return sector_Insert(config);
			}
			else
			{
				return ERR_NO_FREE_SPACE;
			}
		}
	}

	return ERR_NO_MAIN;
}
コード例 #22
0
ファイル: resolve.c プロジェクト: miao606/kamailio
/* gets the DNS records for name:type
 * returns a dyn. alloc'ed struct rdata linked list with the parsed responses
 * or 0 on error
 * see rfc1035 for the query/response format */
struct rdata* get_record(char* name, int type, int flags)
{
	int size;
	int skip;
	int qno, answers_no;
	int i, r;
	static union dns_query buff;
	unsigned char* p;
	unsigned char* end;
	unsigned char* rd_end;
	static char rec_name[MAX_DNS_NAME]; /* placeholder for the record name */
	int rec_name_len;
	unsigned short rtype, class, rdlength;
	unsigned int ttl;
	struct rdata* head;
	struct rdata** crt;
	struct rdata** last;
	struct rdata* rd;
	struct srv_rdata* srv_rd;
	struct srv_rdata* crt_srv;
	int search_list_used;
	int name_len;
	struct rdata* fullname_rd;
	char c;
	
#ifdef USE_DNSSEC
	val_status_t val_status;
#endif

	name_len=strlen(name);

	for (i = 0; i < name_len; i++) {
	    c = name[i];
	    if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
		((c >= '0') && (c <= '9')) || (name[i] == '.') ||
		(name[i] == '-') || (name[i] == '_'))
			continue;
	    LM_DBG("'%s' is not domain name\n", name);
	    return 0;
	}

	if (cfg_get(core, core_cfg, dns_search_list)==0) {
		search_list_used=0;
		name_len=0;
	} else {
		search_list_used=1;
	}
	fullname_rd=0;

#ifndef USE_DNSSEC
	size=res_search(name, C_IN, type, buff.buff, sizeof(buff));
#else
	size=val_res_query((val_context_t *) NULL,
                      (char *) name, 
                      (int) C_IN,
		      (int) type, 
                      (unsigned char *) buff.buff, 
		      (int) sizeof(buff),
                      &val_status);	
	if(!val_istrusted(val_status)){
		LOG(L_INFO, "INFO: got not trusted record when resolving %s\n",name);
	}
#endif

	if (unlikely(size<0)) {
		DBG("get_record: lookup(%s, %d) failed\n", name, type);
		goto not_found;
	}
	else if (unlikely(size > sizeof(buff))) size=sizeof(buff);
	head=rd=0;
	last=crt=&head;
	
	p=buff.buff+DNS_HDR_SIZE;
	end=buff.buff+size;
	if (unlikely(p>=end)) goto error_boundary;
	qno=ntohs((unsigned short)buff.hdr.qdcount);

	for (r=0; r<qno; r++){
		/* skip the name of the question */
		if (unlikely((p=dns_skipname(p, end))==0)) {
			LOG(L_ERR, "ERROR: get_record: skipname==0\n");
			goto error;
		}
		p+=2+2; /* skip QCODE & QCLASS */
	#if 0
		for (;(p<end && (*p)); p++);
		p+=1+2+2; /* skip the ending  '\0, QCODE and QCLASS */
	#endif
		if (unlikely(p>end)) {
			LOG(L_ERR, "ERROR: get_record: p>=end\n");
			goto error;
		}
	};
	answers_no=ntohs((unsigned short)buff.hdr.ancount);
again:
	for (r=0; (r<answers_no) && (p<end); r++){
#if 0
		/*  ignore it the default domain name */
		if ((p=dns_skipname(p, end))==0) {
			LOG(L_ERR, "ERROR: get_record: skip_name=0 (#2)\n");
			goto error;
		}
#else
		if (unlikely((skip=dn_expand(buff.buff, end, p, rec_name,
							MAX_DNS_NAME-1))==-1)){
			LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name) failed\n");
			goto error;
		}
#endif
		p+=skip;
		rec_name_len=strlen(rec_name);
		if (unlikely(rec_name_len>255)){
			LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name): name too"
					" long  (%d)\n", rec_name_len);
			goto error;
		}
		/* check if enough space is left for type, class, ttl & size */
		if (unlikely((p+2+2+4+2)>end)) goto error_boundary;
		/* get type */
		memcpy((void*) &rtype, (void*)p, 2);
		rtype=ntohs(rtype);
		p+=2;
		/* get  class */
		memcpy((void*) &class, (void*)p, 2);
		class=ntohs(class);
		p+=2;
		/* get ttl*/
		memcpy((void*) &ttl, (void*)p, 4);
		ttl=ntohl(ttl);
		p+=4;
		/* get size */
		memcpy((void*)&rdlength, (void*)p, 2);
		rdlength=ntohs(rdlength);
		p+=2;
		rd_end=p+rdlength;
		if (unlikely((rd_end)>end)) goto error_boundary;
		if ((flags & RES_ONLY_TYPE) && (rtype!=type)){
			/* skip */
			p=rd_end;
			continue;
		}
		/* expand the "type" record  (rdata)*/
		
		rd=(struct rdata*) local_malloc(sizeof(struct rdata)+rec_name_len+
										1-1);
		if (rd==0){
			LOG(L_ERR, "ERROR: get_record: out of memory\n");
			goto error;
		}
		rd->type=rtype;
		rd->pclass=class;
		rd->ttl=ttl;
		rd->next=0;
		memcpy(rd->name, rec_name, rec_name_len);
		rd->name[rec_name_len]=0;
		rd->name_len=rec_name_len;
		/* check if full name matches */
		if ((search_list_used==1)&&(fullname_rd==0)&&
				(rec_name_len>=name_len)&&
				(strncasecmp(rec_name, name, name_len)==0)) {
			/* now we have record whose name is the same (up-to the
			 * name_len with the searched one):
			 * if the length is the same - we found full match, no fake
			 *  cname needed, just clear the flag
			 * if the length of the name differs - it has matched using
			 *  search list remember the rd, so we can create fake CNAME
			 *  record when all answers are used and no better match found
			 */
			if (rec_name_len==name_len)
				search_list_used=0;
			/* this is safe.... here was rec_name_len > name_len */
			else if (rec_name[name_len]=='.') {
#ifdef HAVE_RESOLV_RES
				if ((cfg_get(core, core_cfg, dns_search_fmatch)==0) ||
						(match_search_list(&_res, rec_name+name_len+1)!=0))
#endif
					fullname_rd=rd;
			}
		}
		switch(rtype){
			case T_SRV:
				srv_rd= dns_srv_parser(buff.buff, end, rd_end, p);
				rd->rdata=(void*)srv_rd;
				if (unlikely(srv_rd==0)) goto error_parse;
				
				/* insert sorted into the list */
				for (crt=&head; *crt; crt= &((*crt)->next)){
					if ((*crt)->type!=T_SRV)
						continue;
					crt_srv=(struct srv_rdata*)(*crt)->rdata;
					if ((srv_rd->priority <  crt_srv->priority) ||
					   ( (srv_rd->priority == crt_srv->priority) && 
							 (srv_rd->weight > crt_srv->weight) ) ){
						/* insert here */
						goto skip;
					}
				}
				last=&(rd->next); /*end of for => this will be the last
									element*/
			skip:
				/* insert here */
				rd->next=*crt;
				*crt=rd;
				break;
			case T_A:
				rd->rdata=(void*) dns_a_parser(p, rd_end);
				if (unlikely(rd->rdata==0)) goto error_parse;
				*last=rd; /* last points to the last "next" or the list
							 	head*/
				last=&(rd->next);
				break;
			case T_AAAA:
				rd->rdata=(void*) dns_aaaa_parser(p, rd_end);
				if (unlikely(rd->rdata==0)) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			case T_CNAME:
				rd->rdata=(void*) dns_cname_parser(buff.buff, end, p);
				if(unlikely(rd->rdata==0)) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			case T_NAPTR:
				rd->rdata=(void*)dns_naptr_parser(buff.buff, end, rd_end, p);
				if(unlikely(rd->rdata==0)) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			case T_TXT:
				rd->rdata= dns_txt_parser(buff.buff, rd_end, p);
				if (rd->rdata==0) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			case T_EBL:
				rd->rdata= dns_ebl_parser(buff.buff, end, rd_end, p);
				if (rd->rdata==0) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			case T_PTR:
				rd->rdata=(void*) dns_ptr_parser(buff.buff, end, p);
				if(unlikely(rd->rdata==0)) goto error_parse;
				*last=rd;
				last=&(rd->next);
				break;
			default:
				LOG(L_ERR, "WARNING: get_record: unknown type %d\n", rtype);
				rd->rdata=0;
				*last=rd;
				last=&(rd->next);
		}
		
		p+=rdlength;
		
	}
	if (flags & RES_AR){
		flags&=~RES_AR;
		answers_no=ntohs((unsigned short)buff.hdr.nscount);
#ifdef RESOLVE_DBG
		DBG("get_record: skipping %d NS (p=%p, end=%p)\n", answers_no, p,
				end);
#endif
		for (r=0; (r<answers_no) && (p<end); r++){
			/* skip over the ns records */
			if ((p=dns_skipname(p, end))==0) {
				LOG(L_ERR, "ERROR: get_record: skip_name=0 (#3)\n");
				goto error;
			}
			/* check if enough space is left for type, class, ttl & size */
			if (unlikely((p+2+2+4+2)>end)) goto error_boundary;
			memcpy((void*)&rdlength, (void*)p+2+2+4, 2);
			p+=2+2+4+2+ntohs(rdlength);
		}
		answers_no=ntohs((unsigned short)buff.hdr.arcount);
#ifdef RESOLVE_DBG
		DBG("get_record: parsing %d ARs (p=%p, end=%p)\n", answers_no, p,
				end);
#endif
		goto again; /* add also the additional records */
	}

	/* if the name was expanded using DNS search list
	 * create fake CNAME record to convert the short name
	 * (queried) to long name (answered)
	 */
	if ((search_list_used==1)&&(fullname_rd!=0)) {
		rd=(struct rdata*) local_malloc(sizeof(struct rdata)+name_len+1-1);
		if (unlikely(rd==0)){
			LOG(L_ERR, "ERROR: get_record: out of memory\n");
			goto error;
		}
		rd->type=T_CNAME;
		rd->pclass=fullname_rd->pclass;
		rd->ttl=fullname_rd->ttl;
		rd->next=head;
		memcpy(rd->name, name, name_len);
		rd->name[name_len]=0;
		rd->name_len=name_len;
		/* alloc sizeof struct + space for the null terminated name */
		rd->rdata=(void*)local_malloc(sizeof(struct cname_rdata)-1+
										head->name_len+1);
		if(unlikely(rd->rdata==0)){
			LOG(L_ERR, "ERROR: get_record: out of memory\n");
			goto error_rd;
		}
		((struct cname_rdata*)(rd->rdata))->name_len=fullname_rd->name_len;
		memcpy(((struct cname_rdata*)(rd->rdata))->name, fullname_rd->name,
				fullname_rd->name_len);
		((struct cname_rdata*)(rd->rdata))->name[head->name_len]=0;
		head=rd;
	}

	return head;
error_boundary:
		LOG(L_ERR, "ERROR: get_record: end of query buff reached\n");
		if (head) free_rdata_list(head);
		return 0;
error_parse:
		LOG(L_ERR, "ERROR: get_record: rdata parse error (%s, %d), %p-%p"
						" rtype=%d, class=%d, ttl=%d, rdlength=%d \n",
				name, type,
				p, end, rtype, class, ttl, rdlength);
error_rd:
		if (rd) local_free(rd); /* rd->rdata=0 & rd is not linked yet into
								   the list */
error:
		LOG(L_ERR, "ERROR: get_record \n");
		if (head) free_rdata_list(head);
not_found:
	/* increment error counter */
	counter_inc(dns_cnts_h.failed_dns_req);
	return 0;
}
コード例 #23
0
ファイル: io_wait.c プロジェクト: Gaoithe/openimscore_ims
/* initializes the static vars/arrays
 * params:      h - pointer to the io_wait_h that will be initialized
 *         max_fd - maximum allowed fd number
 *         poll_m - poll method (0 for automatic best fit)
 */
int init_io_wait(io_wait_h* h, int max_fd, enum poll_types poll_method)
{
	char * poll_err;
	
	if (_os_ver==0) _os_ver=get_sys_version(0,0,0);
	memset(h, 0, sizeof(*h));
	h->max_fd_no=max_fd;
#ifdef HAVE_EPOLL
	h->epfd=-1;
#endif
#ifdef HAVE_KQUEUE
	h->kq_fd=-1;
#endif
#ifdef HAVE_DEVPOLL
	h->dpoll_fd=-1;
#endif
	poll_err=check_poll_method(poll_method);
	
	/* set an appropiate poll method */
	if (poll_err || (poll_method==0)){
		poll_method=choose_poll_method();
		if (poll_err){
			LOG(L_ERR, "ERROR: init_io_wait: %s, using %s instead\n",
					poll_err, poll_method_str[poll_method]);
		}else{
			LOG(L_INFO, "init_io_wait: using %s as the io watch method"
					" (auto detected)\n", poll_method_str[poll_method]);
		}
	}
	
	h->poll_method=poll_method;
	
	/* common stuff, everybody has fd_hash */
	h->fd_hash=local_malloc(sizeof(*(h->fd_hash))*h->max_fd_no);
	if (h->fd_hash==0){
		LOG(L_CRIT, "ERROR: init_io_wait: could not alloc"
					" fd hashtable (%ld bytes)\n",
					(long)sizeof(*(h->fd_hash))*h->max_fd_no );
		goto error;
	}
	memset((void*)h->fd_hash, 0, sizeof(*(h->fd_hash))*h->max_fd_no);
	
	switch(poll_method){
		case POLL_POLL:
#ifdef HAVE_SELECT
		case POLL_SELECT:
#endif
#ifdef HAVE_SIGIO_RT
		case POLL_SIGIO_RT:
#endif
#ifdef HAVE_DEVPOLL
		case POLL_DEVPOLL:
#endif
			h->fd_array=local_malloc(sizeof(*(h->fd_array))*h->max_fd_no);
			if (h->fd_array==0){
				LOG(L_CRIT, "ERROR: init_io_wait: could not"
							" alloc fd array (%ld bytes)\n",
							(long)sizeof(*(h->fd_hash))*h->max_fd_no);
				goto error;
			}
			memset((void*)h->fd_array, 0, sizeof(*(h->fd_array))*h->max_fd_no);
#ifdef HAVE_SIGIO_RT
			if ((poll_method==POLL_SIGIO_RT) && (init_sigio(h, 0)<0)){
				LOG(L_CRIT, "ERROR: init_io_wait: sigio init failed\n");
				goto error;
			}
#endif
#ifdef HAVE_DEVPOLL
			if ((poll_method==POLL_DEVPOLL) && (init_devpoll(h)<0)){
				LOG(L_CRIT, "ERROR: init_io_wait: /dev/poll init failed\n");
				goto error;
			}
#endif
#ifdef HAVE_SELECT
			if ((poll_method==POLL_SELECT) && (init_select(h)<0)){
				LOG(L_CRIT, "ERROR: init_io_wait: select init failed\n");
				goto error;
			}
#endif
			
			break;
#ifdef HAVE_EPOLL
		case POLL_EPOLL_LT:
		case POLL_EPOLL_ET:
			h->ep_array=local_malloc(sizeof(*(h->ep_array))*h->max_fd_no);
			if (h->ep_array==0){
				LOG(L_CRIT, "ERROR: init_io_wait: could not alloc"
							" epoll array\n");
				goto error;
			}
			memset((void*)h->ep_array, 0, sizeof(*(h->ep_array))*h->max_fd_no);
			if (init_epoll(h)<0){
				LOG(L_CRIT, "ERROR: init_io_wait: epoll init failed\n");
				goto error;
			}
			break;
#endif
#ifdef HAVE_KQUEUE
		case POLL_KQUEUE:
			h->kq_array=local_malloc(sizeof(*(h->kq_array))*h->max_fd_no);
			if (h->kq_array==0){
				LOG(L_CRIT, "ERROR: init_io_wait: could not alloc"
							" kqueue event array\n");
				goto error;
			}
			h->kq_changes_size=KQ_CHANGES_ARRAY_SIZE;
			h->kq_changes=local_malloc(sizeof(*(h->kq_changes))*
										h->kq_changes_size);
			if (h->kq_changes==0){
				LOG(L_CRIT, "ERROR: init_io_wait: could not alloc"
							" kqueue changes array\n");
				goto error;
			}
			h->kq_nchanges=0;
			memset((void*)h->kq_array, 0, sizeof(*(h->kq_array))*h->max_fd_no);
			memset((void*)h->kq_changes, 0,
						sizeof(*(h->kq_changes))* h->kq_changes_size);
			if (init_kqueue(h)<0){
				LOG(L_CRIT, "ERROR: init_io_wait: kqueue init failed\n");
				goto error;
			}
			break;
#endif
		default:
			LOG(L_CRIT, "BUG: init_io_wait: unknown/unsupported poll"
						" method %s (%d)\n",
						poll_method_str[poll_method], poll_method);
			goto error;
	}
	return 0;
error:
	return -1;
}