예제 #1
0
static int idt77105_start(struct atm_dev *dev)
{
    unsigned long flags;

    if (!(dev->dev_data = kmalloc(sizeof(struct idt77105_priv),GFP_KERNEL)))
        return -ENOMEM;
    PRIV(dev)->dev = dev;
    spin_lock_irqsave(&idt77105_priv_lock, flags);
    PRIV(dev)->next = idt77105_all;
    idt77105_all = PRIV(dev);
    spin_unlock_irqrestore(&idt77105_priv_lock, flags);
    memset(&PRIV(dev)->stats,0,sizeof(struct idt77105_stats));

    /* initialise dev->signal from Good Signal Bit */
    atm_dev_signal_change(dev,
                          GET(ISTAT) & IDT77105_ISTAT_GOODSIG ?
                          ATM_PHY_SIG_FOUND : ATM_PHY_SIG_LOST);
    if (dev->signal == ATM_PHY_SIG_LOST)
#ifdef CONFIG_DEBUG_PRINTK
        printk(KERN_WARNING "%s(itf %d): no signal\n",dev->type,
               dev->number);
#else
        ;
#endif

    /* initialise loop mode from hardware */
    switch ( GET(DIAG) & IDT77105_DIAG_LCMASK ) {
    case IDT77105_DIAG_LC_NORMAL:
        PRIV(dev)->loop_mode = ATM_LM_NONE;
        break;
    case IDT77105_DIAG_LC_PHY_LOOPBACK:
        PRIV(dev)->loop_mode = ATM_LM_LOC_ATM;
        break;
    case IDT77105_DIAG_LC_LINE_LOOPBACK:
        PRIV(dev)->loop_mode = ATM_LM_RMT_ATM;
        break;
    }

    /* enable interrupts, e.g. on loss of signal */
    PRIV(dev)->old_mcr = GET(MCR);
    if (dev->signal == ATM_PHY_SIG_FOUND) {
        PRIV(dev)->old_mcr |= IDT77105_MCR_EIP;
        PUT(PRIV(dev)->old_mcr, MCR);
    }


    idt77105_stats_timer_func(0); /* clear 77105 counters */
    (void) fetch_stats(dev,NULL,1); /* clear kernel counters */

    spin_lock_irqsave(&idt77105_priv_lock, flags);
    if (start_timer) {
        start_timer = 0;

        init_timer(&stats_timer);
        stats_timer.expires = jiffies+IDT77105_STATS_TIMER_PERIOD;
        stats_timer.function = idt77105_stats_timer_func;
        add_timer(&stats_timer);

        init_timer(&restart_timer);
        restart_timer.expires = jiffies+IDT77105_RESTART_TIMER_PERIOD;
        restart_timer.function = idt77105_restart_timer_func;
        add_timer(&restart_timer);
    }
    spin_unlock_irqrestore(&idt77105_priv_lock, flags);
    return 0;
}
예제 #2
0
파일: mm.c 프로젝트: gigi13164269/blog-1
void mm_free(void *bp) {
  size_t size = GET_SIZE(HDRP(bp));
  PUT(HDRP(bp), PACK(size, 0));
  PUT(FTRP(bp), PACK(size, 0));
  coalesce(bp);
}
예제 #3
0
파일: mm.c 프로젝트: Jarvishappy/malloc_lab
/*
 * mm_realloc - Implemented simply in terms of mm_malloc and mm_free
 * 重新调整之前malloc分配的block的大小
 * TODO: 改用next_fid策略后,好像这里就死循环了
 */
void *mm_realloc(void *bp, size_t size)
{
    if (bp == NULL)
        return mm_malloc(size);
    else if (0 == size) {
        mm_free(bp);
        return NULL;
    }

    /* check if bp is aliged */
    if ((uint32_t)bp % ALIGNMENT != 0)
        return NULL;

    void *new_bp = NULL;
    size_t old_size = GET_SIZE(HDRP(bp));
    size_t new_size = ALIGN(size + DSIZE); /* 别忘了header和footer的size! */
    size_t frag_size;
    if (new_size > old_size) {
        /*
         * 这个IF中的逻辑感觉多余了,只需要通过malloc()找到一个更大的空闲块就行了.
         *
         * 2015-9-18
         * 通过malloc()重新给找一个更大的block是可以,但是我这implicit的实现,每次
         * 都要遍历所有的block寻找free block,效率非常低
         * */

        /**
         * 判断相邻的下一块是否是一个足以容纳(new_size - old_size)的空闲块,
         * 如果是,那么就把当前块扩展到下一块就好了
         */
        if (!GET_ALLOC(HDRP(NEXT_BLKP(bp))) &&
                GET_SIZE(HDRP(NEXT_BLKP(bp))) >= (new_size - old_size)) {
             /* next block is large enough, bp not need to change */

            frag_size = GET_SIZE(HDRP(NEXT_BLKP(bp))) - (new_size - old_size);

            if (frag_size >= MIN_BLK) {
                PUT(HDRP(bp), PACK(new_size, 1));
                PUT(FTRP(bp), PACK(new_size, 1));

                PUT(HDRP(NEXT_BLKP(bp)), PACK(frag_size, 0));
                PUT(FTRP(NEXT_BLKP(bp)), PACK(frag_size, 0));
            } else {
                new_size = old_size + GET_SIZE(HDRP(NEXT_BLKP(bp)));
                PUT(HDRP(bp), PACK(new_size, 1));
                PUT(FTRP(bp), PACK(new_size, 1));
            }

            new_bp = bp;

        } else {
            /* next block isn't large enough, bp need to be pointed to a large region */
            if ((new_bp = find_fit(last_found, new_size)) == NULL)
                new_bp = extend_heap(MAX(new_size, CHUNKSIZE) / WSIZE);

            place(new_bp, new_size);
            /* copy payload from old block to new block */
            memcpy(new_bp, bp, old_size - DSIZE);
            /* free old block */
            mm_free(bp);
        }
    } else if (new_size < old_size) {
        /* if new_size < old_size, check if need to split */
        if (old_size - new_size >= MIN_BLK) {
            PUT(HDRP(bp), PACK(new_size, 1));
            PUT(FTRP(bp), PACK(new_size, 1));
            /* split a new free block */
            PUT(HDRP(NEXT_BLKP(bp)), PACK(old_size - new_size, 0));
            PUT(FTRP(NEXT_BLKP(bp)), PACK(old_size - new_size, 0));
        }

        new_bp = bp;
    }

    /* mm_check(); */

    return new_bp;
}
예제 #4
0
void *place(void *bp,size_t asize)
	
{
//	dbg_printf("place\n");
	void *p = GET(FLPB(bp));		//preview free_block
	void *n = GET(FLSB(bp));		//next free_block
	void *return_bp = bp;
//	dbg_printf(" p : %d\tbp : %d\tn : %d\n",p,bp,n);
	size_t size = GET_SIZE(HDRP(bp));
	PUT(HDRP(bp),PACK(asize,1));
	PUT(FTRP(bp),PACK(asize,1));
	size -=asize;
	bp = NEXT_BLKP(bp);				//split block
	if ( size == 0 )
	{
		if ( free_count >=2 )
		{
			PUT(FLSB(p),n);
			if ( n != NULL )
				PUT(FLPB(n),p);
	//		dbg_printf("true\n");
		}
		else
			init = NULL;
		free_count--;
	}
	else
	{
		PUT(HDRP(bp),PACK(size,0));
		PUT(FTRP(bp),PACK(size,0));
//		dbg_printf("p : %d\tbp : %d\tn : %d\n",p,bp,n);
		if ( p == &init)
		{
			PUT(FLPB(bp),&init);
			PUT(FLSB(bp),n);
			init = bp;
		}
		else
		{
			PUT(FLSB(bp),n);
			PUT(FLPB(bp),p);
			PUT(FLSB(p),bp);
		}
		if ( n != NULL )
			PUT(FLPB(n),bp);
	}
	return return_bp;
	
}
예제 #5
0
/* 
 * mm_init - initialize the malloc package.
 */
int mm_init(void)
{
	int i;
	
	dbg1("[IN ] : mm_init()\n");

	/* create the initial empty heap */
//	if ((heap_listp = mem_sbrk(18*DSIZE + 4 * WSIZE)) == NULL)
	if ((heap_listp = mem_sbrk((MAXCLASS+1)*2*DSIZE + 4 * WSIZE)) == NULL)
		return -1;

	
	/* free_list_ptrs points to starting point of free list pointers */
	free_list_ptrs = heap_listp;
	
	for (i=0; i<= MAXCLASS; i++) {
		PUT8(heap_listp+DSIZE*(i*2), NULL);
		PUT8(heap_listp+DSIZE*(i*2+1), NULL);
	}
	
	/* heap starting point is set right after the free list pointers */
	heap_listp = heap_listp+DSIZE*2*(MAXCLASS+1);
	
#if 0
	/* set up segregated free list pointers */
	PUT8(heap_listp, NULL);           /* free list 0 head */
	PUT8(heap_listp+DSIZE, NULL);     /* free list 0 tail */
	PUT8(heap_listp+DSIZE*2, NULL);   /* free list 1 head */
	PUT8(heap_listp+DSIZE*3, NULL);   /* free list 1 tail */
	PUT8(heap_listp+DSIZE*4, NULL);   /* free list 2 head */
	PUT8(heap_listp+DSIZE*5, NULL);   /* free list 2 tail */
	PUT8(heap_listp+DSIZE*6, NULL);   /* free list 3 head */
	PUT8(heap_listp+DSIZE*7, NULL);   /* free list 3 tail */
	PUT8(heap_listp+DSIZE*8, NULL);   /* free list 4 head */
	PUT8(heap_listp+DSIZE*9, NULL);   /* free list 4 tail */
	PUT8(heap_listp+DSIZE*10, NULL);  /* free list 5 head */
	PUT8(heap_listp+DSIZE*11, NULL);  /* free list 5 tail */
	PUT8(heap_listp+DSIZE*12, NULL);  /* free list 6 head */
	PUT8(heap_listp+DSIZE*13, NULL);  /* free list 6 tail */
	PUT8(heap_listp+DSIZE*14, NULL);  /* free list 7 head */
	PUT8(heap_listp+DSIZE*15, NULL);  /* free list 7 tail */
	PUT8(heap_listp+DSIZE*16, NULL);  /* free list 8 head */
	PUT8(heap_listp+DSIZE*17, NULL);  /* free list 8 tail */
	
	/* free_list_ptrs points to starting point of free list pointers */
	free_list_ptrs = heap_listp;

	/* heap starting point is set right after the free list pointers */
	heap_listp = heap_listp+DSIZE*18;
#endif
	
	PUT(heap_listp, 0);															/* alignment padding */
	PUT(heap_listp+WSIZE, PACK(OVERHEAD, 3));				/* prologue header */
	PUT(heap_listp+2*WSIZE, PACK(OVERHEAD, 3));			/* prologue footer */
	PUT(heap_listp+3*WSIZE, PACK(0, 3));						/* epilogue header */

	epilogue = (unsigned *)(heap_listp+3*WSIZE);		/* update epilogue pointer */

	heap_listp += 2*WSIZE;

	/* extends heap only on demand */

	mm_initialized = 1;
	
	dbg1("[OUT] : mm_init()\n");

	return 0;
}
예제 #6
0
/*
* mm_realloc : This routine is a kind of a wrapper routine for the already implimented
* mm_malloc and mm_free routines. It also takes care of the reallocation of a new 
* pointer or memory space.
*/
void *
mm_realloc(void *ptr, size_t size)
{
	size_t oldsize= GET_SIZE(HDRP(ptr)),total_size;// Gets the present size of the allocated block which has to be reallocated
	void *newptr;

    // If size == 0 It means it's a free block. We return NULL 
	if (size == 0) {
		mm_free(ptr);// frees the block 
		return (NULL);
	}

	/* If ptr is NULL, It means we have freshly allocate ablock with the mentioned size*/
	if (ptr == NULL)
		return (mm_malloc(size));// allaoctes the block of the mentioned size.
	if (size <= DSIZE)
		total_size = 2 * DSIZE;
			else
		total_size = DSIZE * ((size + DSIZE + (DSIZE - 1)) / DSIZE);// calcuates the total_size required for the new block to be allocated
	if(oldsize == total_size) return ptr;
	if (oldsize >= total_size) 
	{
		
		if((oldsize - total_size) != (DSIZE))
		{
			if((oldsize - total_size) != 0)
			{
				PUT(HDRP(ptr), PACK(total_size, 1));//packs the size of the block and the allocation(1) status in the header
				PUT(FTRP(ptr), PACK(total_size, 1));//packs the size of the block and the allocation(1) status in the footer
				void *bp = NEXT_BLKP(ptr);//Gets the pointer of the next block in the heap
				PUT(HDRP(bp), PACK(oldsize - total_size, 0));//packs the size of the block and the allocation(0) status in the header
				PUT(FTRP(bp), PACK(oldsize - total_size, 0));//packs the size of the block and the allocation(1) status in the footer
				coalesce(bp);// coaleseces the block 
			}
			return ptr;
		}
		
		
	}	
	size_t next_blkp_size = (size_t)GET_SIZE(HDRP(NEXT_BLKP(ptr)));
	if((size_t)GET_ALLOC(HDRP(NEXT_BLKP(ptr)))==0   &&   next_blkp_size + oldsize - total_size > DSIZE)
	{
		Delete_Free_Block(NEXT_BLKP(ptr),next_blkp_size);//Deletes the block  from the explicictly maintained free list
		PUT(HDRP(ptr), PACK(total_size, 1));//packs the size of the block and the allocation(1) status in the header
		PUT(FTRP(ptr), PACK(total_size, 1));//packs the size of the block and the allocation(1) status in the footer
		void *bp = NEXT_BLKP(ptr);
		PUT(HDRP(bp), PACK(next_blkp_size + oldsize - total_size, 0));//packs the size of the block and the allocation(0) status in the header
		PUT(FTRP(bp), PACK(next_blkp_size + oldsize - total_size, 0));//packs the size of the block and the allocation(0) status in the footer
		Add_Free_Block(bp,next_blkp_size + oldsize - total_size);//Adds the block to the explicictly maintained free list
		//checkheap(1);
		return ptr;
	}
	
	
	newptr = mm_malloc(size);// allocates the new block at the new pointer

	//If realloc() fails the original block is left untouched  
	if (newptr == NULL)
		return (NULL);
	

	// Copy the old data. 
	oldsize = GET_SIZE(HDRP(ptr));
	if (size < oldsize)
		oldsize = size;
	memcpy(newptr, ptr, oldsize);

	// Free the old block. 
	mm_free(ptr);

	return (newptr);
}
예제 #7
0
파일: Cpp.c 프로젝트: gsliu/emacs_C
/*
 * Cpp: read C++ file and pickup tag entries.
 */
void
Cpp(const struct parser_param *param)
{
	int c, cc;
	int savelevel;
	int startclass, startthrow, startmacro, startsharp, startequal;
	char classname[MAXTOKEN];
	char completename[MAXCOMPLETENAME];
	int classlevel;
	struct {
		char *classname;
		char *terminate;
		int level;
	} stack[MAXCLASSSTACK];
	const char *interested = "{}=;~";
	STRBUF *sb = strbuf_open(0);

	*classname = *completename = 0;
	stack[0].classname = completename;
	stack[0].terminate = completename;
	stack[0].level = 0;
	level = classlevel = piflevel = namespacelevel = 0;
	savelevel = -1;
	startclass = startthrow = startmacro = startsharp = startequal = 0;

	if (!opentoken(param->file))
		die("'%s' cannot open.", param->file);
	cmode = 1;			/* allow token like '#xxx' */
	crflag = 1;			/* require '\n' as a token */
	cppmode = 1;			/* treat '::' as a token */

	while ((cc = nexttoken(interested, cpp_reserved_word)) != EOF) {
		if (cc == '~' && level == stack[classlevel].level)
			continue;
		switch (cc) {
		case SYMBOL:		/* symbol	*/
			if (startclass || startthrow) {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			} else if (peekc(0) == '('/* ) */) {
				if (param->isnotfunction(token)) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				} else if (level > stack[classlevel].level || startequal || startmacro) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				} else if (level == stack[classlevel].level && !startmacro && !startsharp && !startequal) {
					char savetok[MAXTOKEN], *saveline;
					int savelineno = lineno;

					strlimcpy(savetok, token, sizeof(savetok));
					strbuf_reset(sb);
					strbuf_puts(sb, sp);
					saveline = strbuf_value(sb);
					if (function_definition(param)) {
						/* ignore constructor */
						if (strcmp(stack[classlevel].classname, savetok))
							PUT(PARSER_DEF, savetok, savelineno, saveline);
					} else {
						PUT(PARSER_REF_SYM, savetok, savelineno, saveline);
					}
				}
			} else {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			}
			break;
		case CPP_USING:
			/*
			 * using namespace name;
			 * using ...;
			 */
			if ((c = nexttoken(interested, cpp_reserved_word)) == CPP_NAMESPACE) {
				if ((c = nexttoken(interested, cpp_reserved_word)) == SYMBOL) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				} else {
					if (param->flags & PARSER_WARNING)
						warning("missing namespace name. [+%d %s].", lineno, curfile);
					pushbacktoken();
				}
			} else
				pushbacktoken();
			break;
		case CPP_NAMESPACE:
			crflag = 0;
			/*
			 * namespace name = ...;
			 * namespace [name] { ... }
			 */
			if ((c = nexttoken(interested, cpp_reserved_word)) == SYMBOL) {
				PUT(PARSER_DEF, token, lineno, sp);
				if ((c = nexttoken(interested, cpp_reserved_word)) == '=') {
					crflag = 1;
					break;
				}
			}
			/*
			 * Namespace block doesn't have any influence on level.
			 */
			if (c == '{') /* } */ {
				namespacelevel++;
			} else {
				if (param->flags & PARSER_WARNING)
					warning("missing namespace block. [+%d %s](0x%x).", lineno, curfile, c);
			}
			crflag = 1;
			break;
		case CPP_EXTERN: /* for 'extern "C"/"C++"' */
			if (peekc(0) != '"') /* " */
				continue; /* If does not start with '"', continue. */
			while ((c = nexttoken(interested, cpp_reserved_word)) == '\n')
				;
			/*
			 * 'extern "C"/"C++"' block is a kind of namespace block.
			 * (It doesn't have any influence on level.)
			 */
			if (c == '{') /* } */
				namespacelevel++;
			else
				pushbacktoken();
			break;
		case CPP_CLASS:
			DBG_PRINT(level, "class");
			if ((c = nexttoken(interested, cpp_reserved_word)) == SYMBOL) {
				strlimcpy(classname, token, sizeof(classname));
				/*
				 * Ignore forward definitions.
				 * "class name;"
				 */
				if (peekc(0) != ';') {
					startclass = 1;
					PUT(PARSER_DEF, token, lineno, sp);
				}
			}
			break;
		case '{':  /* } */
			DBG_PRINT(level, "{"); /* } */
			++level;
			if ((param->flags & PARSER_BEGIN_BLOCK) && atfirst) {
				if ((param->flags & PARSER_WARNING) && level != 1)
					warning("forced level 1 block start by '{' at column 0 [+%d %s].", lineno, curfile); /* } */
				level = 1;
			}
			if (startclass) {
				char *p = stack[classlevel].terminate;
				char *q = classname;

				if (++classlevel >= MAXCLASSSTACK)
					die("class stack over flow.[%s]", curfile);
				if (classlevel > 1)
					*p++ = '.';
				stack[classlevel].classname = p;
				while (*q)
					*p++ = *q++;
				stack[classlevel].terminate = p;
				stack[classlevel].level = level;
				*p++ = 0;
			}
			startclass = startthrow = 0;
			break;
			/* { */
		case '}':
			if (--level < 0) {
				if (namespacelevel > 0)
					namespacelevel--;
				else if (param->flags & PARSER_WARNING)
					warning("missing left '{' [+%d %s].", lineno, curfile); /* } */
				level = 0;
			}
			if ((param->flags & PARSER_END_BLOCK) && atfirst) {
				if ((param->flags & PARSER_WARNING) && level != 0)
					/* { */
					warning("forced level 0 block end by '}' at column 0 [+%d %s].", lineno, curfile);
				level = 0;
			}
			if (level < stack[classlevel].level)
				*(stack[--classlevel].terminate) = 0;
			/* { */
			DBG_PRINT(level, "}");
			break;
		case '=':
			/* dirty hack. Don't mimic this. */
			if (peekc(0) == '=') {
				throwaway_nextchar();
			} else {
				startequal = 1;
			}
			break;
		case ';':
			startthrow = startequal = 0;
			break;
		case '\n':
			if (startmacro && level != savelevel) {
				if (param->flags & PARSER_WARNING)
					warning("different level before and after #define macro. reseted. [+%d %s].", lineno, curfile);
				level = savelevel;
			}
			startmacro = startsharp = 0;
			break;
		/*
		 * #xxx
		 */
		case SHARP_DEFINE:
		case SHARP_UNDEF:
			startmacro = 1;
			savelevel = level;
			if ((c = nexttoken(interested, cpp_reserved_word)) != SYMBOL) {
				pushbacktoken();
				break;
			}
			if (peekc(1) == '('/* ) */) {
				PUT(PARSER_DEF, token, lineno, sp);
				while ((c = nexttoken("()", cpp_reserved_word)) != EOF && c != '\n' && c != /* ( */ ')')
					if (c == SYMBOL)
						PUT(PARSER_REF_SYM, token, lineno, sp);
				if (c == '\n')
					pushbacktoken();
			}  else {
				PUT(PARSER_DEF, token, lineno, sp);
			}
			break;
		case SHARP_IMPORT:
		case SHARP_INCLUDE:
		case SHARP_INCLUDE_NEXT:
		case SHARP_ERROR:
		case SHARP_LINE:
		case SHARP_PRAGMA:
		case SHARP_WARNING:
		case SHARP_IDENT:
		case SHARP_SCCS:
			while ((c = nexttoken(interested, cpp_reserved_word)) != EOF && c != '\n')
				;
			break;
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, cc);
			break;
		case SHARP_SHARP:		/* ## */
			(void)nexttoken(interested, cpp_reserved_word);
			break;
		case CPP_NEW:
			if ((c = nexttoken(interested, cpp_reserved_word)) == SYMBOL)
				PUT(PARSER_REF_SYM, token, lineno, sp);
			break;
		case CPP_STRUCT:
		case CPP_ENUM:
		case CPP_UNION:
			c = nexttoken(interested, cpp_reserved_word);
			if (c == SYMBOL) {
				if (peekc(0) == '{') /* } */ {
					PUT(PARSER_DEF, token, lineno, sp);
				} else {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				}
				c = nexttoken(interested, cpp_reserved_word);
			}
			if (c == '{' /* } */ && cc == CPP_ENUM) {
				enumerator_list(param);
			} else {
				pushbacktoken();
			}
			break;
		case CPP_TEMPLATE:
			{
				int level = 0;

				while ((c = nexttoken("<>", cpp_reserved_word)) != EOF) {
					if (c == '<')
						++level;
					else if (c == '>') {
						if (--level == 0)
							break;
					} else if (c == SYMBOL) {
						PUT(PARSER_REF_SYM, token, lineno, sp);
					}
				}
				if (c == EOF && (param->flags & PARSER_WARNING))
					warning("template <...> isn't closed. [+%d %s].", lineno, curfile);
			}
			break;
		case CPP_OPERATOR:
			while ((c = nexttoken(";{", /* } */ cpp_reserved_word)) != EOF) {
				if (c == '{') /* } */ {
					pushbacktoken();
					break;
				} else if (c == ';') {
					break;
				} else if (c == SYMBOL) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				}
			}
			if (c == EOF && (param->flags & PARSER_WARNING))
				warning("'{' doesn't exist after 'operator'. [+%d %s].", lineno, curfile); /* } */
			break;
		/* control statement check */
		case CPP_THROW:
			startthrow = 1;
		case CPP_BREAK:
		case CPP_CASE:
		case CPP_CATCH:
		case CPP_CONTINUE:
		case CPP_DEFAULT:
		case CPP_DELETE:
		case CPP_DO:
		case CPP_ELSE:
		case CPP_FOR:
		case CPP_GOTO:
		case CPP_IF:
		case CPP_RETURN:
		case CPP_SWITCH:
		case CPP_TRY:
		case CPP_WHILE:
			if ((param->flags & PARSER_WARNING) && !startmacro && level == 0)
				warning("Out of function. %8s [+%d %s]", token, lineno, curfile);
			break;
		case CPP_TYPEDEF:
			{
				/*
				 * This parser is too complex to maintain.
				 * We should rewrite the whole.
				 */
				char savetok[MAXTOKEN];
				int savelineno = 0;
				int typedef_savelevel = level;

				savetok[0] = 0;

				/* skip CV qualifiers */
				do {
					c = nexttoken("{}(),;", cpp_reserved_word);
				} while (IS_CV_QUALIFIER(c) || c == '\n');

				if ((param->flags & PARSER_WARNING) && c == EOF) {
					warning("unexpected eof. [+%d %s]", lineno, curfile);
					break;
				} else if (c == CPP_ENUM || c == CPP_STRUCT || c == CPP_UNION) {
					char *interest_enum = "{},;";
					int c_ = c;

					c = nexttoken(interest_enum, cpp_reserved_word);
					/* read tag name if exist */
					if (c == SYMBOL) {
						if (peekc(0) == '{') /* } */ {
							PUT(PARSER_DEF, token, lineno, sp);
						} else {
							PUT(PARSER_REF_SYM, token, lineno, sp);
						}
						c = nexttoken(interest_enum, cpp_reserved_word);
					}
					if (c_ == CPP_ENUM) {
						if (c == '{') /* } */
							c = enumerator_list(param);
						else
							pushbacktoken();
					} else {
						for (; c != EOF; c = nexttoken(interest_enum, cpp_reserved_word)) {
							switch (c) {
							case SHARP_IFDEF:
							case SHARP_IFNDEF:
							case SHARP_IF:
							case SHARP_ELIF:
							case SHARP_ELSE:
							case SHARP_ENDIF:
								condition_macro(param, c);
								continue;
							default:
								break;
							}
							if (c == ';' && level == typedef_savelevel) {
								if (savetok[0])
									PUT(PARSER_DEF, savetok, savelineno, sp);
								break;
							} else if (c == '{')
								level++;
							else if (c == '}') {
								if (--level == typedef_savelevel)
									break;
							} else if (c == SYMBOL) {
								PUT(PARSER_REF_SYM, token, lineno, sp);
								/* save lastest token */
								strlimcpy(savetok, token, sizeof(savetok));
								savelineno = lineno;
							}
						}
						if (c == ';')
							break;
					}
					if ((param->flags & PARSER_WARNING) && c == EOF) {
						warning("unexpected eof. [+%d %s]", lineno, curfile);
						break;
					}
				} else if (c == SYMBOL) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				}
				savetok[0] = 0;
				while ((c = nexttoken("(),;", cpp_reserved_word)) != EOF) {
					switch (c) {
					case SHARP_IFDEF:
					case SHARP_IFNDEF:
					case SHARP_IF:
					case SHARP_ELIF:
					case SHARP_ELSE:
					case SHARP_ENDIF:
						condition_macro(param, c);
						continue;
					default:
						break;
					}
					if (c == '(')
						level++;
					else if (c == ')')
						level--;
					else if (c == SYMBOL) {
						if (level > typedef_savelevel) {
							PUT(PARSER_REF_SYM, token, lineno, sp);
						} else {
							/* put latest token if any */
							if (savetok[0]) {
								PUT(PARSER_REF_SYM, savetok, savelineno, sp);
							}
							/* save lastest token */
							strlimcpy(savetok, token, sizeof(savetok));
							savelineno = lineno;
						}
					} else if (c == ',' || c == ';') {
						if (savetok[0]) {
							PUT(PARSER_DEF, savetok, lineno, sp);
							savetok[0] = 0;
						}
					}
					if (level == typedef_savelevel && c == ';')
						break;
				}
				if (param->flags & PARSER_WARNING) {
					if (c == EOF)
						warning("unexpected eof. [+%d %s]", lineno, curfile);
					else if (level != typedef_savelevel)
						warning("unmatched () block. (last at level %d.)[+%d %s]", level, lineno, curfile);
				}
			}
			break;
		case CPP___ATTRIBUTE__:
			process_attribute(param);
			break;
		default:
			break;
		}
	}
	strbuf_close(sb);
	if (param->flags & PARSER_WARNING) {
		if (level != 0)
			warning("unmatched {} block. (last at level %d.)[+%d %s]", level, lineno, curfile);
		if (piflevel != 0)
			warning("unmatched #if block. (last at level %d.)[+%d %s]", piflevel, lineno, curfile);
	}
	closetoken();
}
예제 #8
0
파일: mm.c 프로젝트: olikari/malloclab
/*
 * mm_realloc - naive implementation of mm_realloc. The realloc() function shall change the 
 * size of the memory object pointed to by ptr to the size specified by size. The contents 
 * of the object shall remain unchanged up to the lesser of the new and old sizes. If the 
 * new size of the memory object would require movement of the object, the space for the 
 * previous instantiation of the object is freed. If the new size is larger, the contents 
 * of the newly allocated portion of the object are unspecified.
 */
void *mm_realloc(void *ptr, size_t size)
{
    void *newp;
	void *oldp = ptr;
    size_t oldSize = GET_SIZE(HDRP(oldp));
	//size_t newSize = ALIGN(size);
	size_t asize;
	//size_t isPrevFree = GET_ALLOC(FTRP(PREV_BLKP(oldp)));
	size_t isNextFree = GET_ALLOC(HDRP(NEXT_BLKP(oldp)));
	//size_t prevSize = GET_SIZE(FTRP(PREV_BLKP(oldp)));
	size_t nextSize = GET_SIZE(HDRP(NEXT_BLKP(oldp)));

	//mm_checkheap(0);

	if(ptr == NULL)
		return mm_malloc(size);
	else if(size == 0){
		mm_free(ptr);
		return NULL;
	} 
	else if(size == GET_SIZE(HDRP(ptr)))
		return ptr;		
	
    if (size <= DSIZE)
        asize = DSIZE + OVERHEAD;
    else 
       asize = DSIZE * ((size + (OVERHEAD) + (DSIZE-1)) / DSIZE);
	
	if(asize <= oldSize){
	  //printf("OldSize: %zu , asize: %zu\n", oldSize, asize); 
		
	  if(oldSize - asize < OVERHEAD){
			//printf("FER HINGAÐ\n");
			return oldp;
		}
		PUT(HDRP(oldp), PACK(asize, 1));
		PUT(FTRP(oldp), PACK(asize, 1));
		//printf("alloc minnkar og nýtir rest í fría blokk\n");
		PUT(HDRP(NEXT_BLKP(oldp)), PACK(oldSize - asize, 0));
		PUT(FTRP(NEXT_BLKP(oldp)), PACK(oldSize - asize, 0));
		insert_block(NEXT_BLKP(oldp));
	}
	/*else if(!isNextFree && (oldSize + nextSize) >= asize){
		if((oldSize + nextSize) - asize < OVERHEAD){
			PUT(HDRP(oldp), PACK(oldSize + nextSize, 1));
			PUT(FTRP(oldp), PACK(oldSize + nextSize, 1));
		}
		else{
			PUT(HDRP(oldp), PACK(asize, 1));
			PUT(FTRP(oldp), PACK(asize, 1));
			PUT(HDRP(NEXT_BLKP(oldp)), PACK((oldSize+nextSize)-asize, 0));
			PUT(FTRP(NEXT_BLKP(oldp)), PACK((oldSize+nextSize)-asize, 0));
			void *freeBlock = NEXT_BLKP(oldp);
			insert_block(freeBlock);
			return oldp;
		}
	}*/	

	// calculate the adjusted size of the request ????
	// ef adjustedSize <= oldsize, return ptr
	
	if ((newp = mm_malloc(size)) == NULL) {
        printf("ERROR: mm_malloc failed in mm_realloc\n");
        exit(1);
    }
    if (size < oldSize) {
        oldSize = size;
    }
    memcpy(newp, ptr, oldSize);
    mm_free(ptr);
    return newp;
}
예제 #9
0
void GaussBin_Elimination(char * inputname, char * outputname)
{ FILE * in=fopen(inputname,"rb");
  
  long m, n, i, j, k, l, cols, sum, old, rem=0;
  fscanf(in,"%ld %ld", &n, &m);
  cols=1+(n>>5);
  
  unsigned long ** mas=new unsigned long*[m];
  for(i=0; i<m; ++i) mas[i]=new unsigned long[cols];
  for(i=0; i<m; ++i) memset(mas[i],0,sizeof(unsigned long)*cols);

// #define GET(i,j) ((mas[i][j>>5]>>(j&31))&1)
// #define PUT(i,j,k) mas[i][j>>5]=(k)?(mas[i][j>>5]|(1<<(j&31))):(mas[i][j>>5]&((1<<(j&31))^-1))

  // Read the input matrix m*n
  for(i=0; i<n; i++)
	  for(j=0; j<m; j++)
	  { fscanf(in, "%ld", &k);
        k%=2;
		if(k) PUT(mas, j,i,k);
	  }

  // Gaussian elimination here
  long * vert=new long[m], *horz=new long[n], *uncl=new long[n], *solv=new long[n];
  memset(vert,0,sizeof(long)*m);
  memset(horz,0,sizeof(long)*n);
  memset(uncl,0,sizeof(long)*n);

  // Here I include removal of columns, which are equal.
  for(i=0; i<n; ++i)
	  for(j=i+1; j<n; ++j)
	  { for(k=0; k<m; k++)
	      if(GET(mas, k,i)!=GET(mas, k,j)) break;
        if(k==m) horz[j]=-1, ++rem; // delete the column j in this case
	  }
  printf("Rejected rows: %ld\n", rem);

  for(i=0; i<n; ++i)
  if(!horz[i])
  { for(j=0; j<m; ++j)
      if(vert[j]==0 && GET(mas, j,i)) break;
    if(j==m) continue;
	vert[j]=1;
	horz[i]=j+1; // horizontal references
	l=j;
	for(j=0; j<m; ++j)
	  if(GET(mas,j,i) && j!=l)
		  for(k=0; k<cols; ++k)
			  mas[j][k]^=mas[l][k];
  }
  
  for(i=sum=0; i<n; ++i)
	if(--horz[i]==-1) uncl[sum++]=i; // unresolved columns

  FILE * out=fopen(outputname,"wb");
  // Generate resulting vectors
  old=sum;
  if(sum>12) 
  { printf("The number of solutions is too many (2^%ld) ... trancated to 2^12!\n", sum);
	sum=12; // too many solutions!!!
  }

  fprintf(out,"%d\n", (1<<sum)-1);

  for(i=1; i<(1<<sum); ++i)
  { memset(solv,0,sizeof(long)*n);
    for(j=sum; j<old; ++j) solv[uncl[j]]=rand()%2;
    for(j=0; j<sum; ++j) // fill unknown variables first
		solv[uncl[j]]=(i>>j)&1;
	// calculate the rest variables here
	for(j=0; j<n; ++j)
		if(horz[j]>=0)
		{ for(l=k=0; l<old; ++l)
			if(GET(mas, horz[j], uncl[l]))  k^=solv[uncl[l]];
		  solv[j]=k;
		}
	// output one solution here
	for(j=0; j<n; j++)
		fprintf(out,"%ld ", solv[j]);
	fprintf(out,"\n");
  }

  fclose(out);

  for(i=0; i<m; ++i) delete []mas[i];
  delete []mas;
  delete []vert;
  delete []horz;
  delete []uncl;
  fclose(in);  
}
예제 #10
0
파일: C.c 프로젝트: qbai/.emacs.d
/**
 *	@param[in]	param	source file
 *	@param[in]	type	#TYPE_C, #TYPE_YACC, #TYPE_LEX
 */
static void
C_family(const struct parser_param *param, int type)
{
	int c, cc;
	int savelevel;
	int startmacro, startsharp;
	const char *interested = "{}=;";
	STRBUF *sb = strbuf_open(0);
	/*
	 * yacc file format is like the following.
	 *
	 * declarations
	 * %%
	 * rules
	 * %%
	 * programs
	 *
	 */
	int yaccstatus = (type == TYPE_YACC) ? DECLARATIONS : PROGRAMS;
	int inC = (type == TYPE_YACC) ? 0 : 1;	/* 1 while C source */

	level = piflevel = externclevel = 0;
	savelevel = -1;
	startmacro = startsharp = 0;

	if (!opentoken(param->file))
		die("'%s' cannot open.", param->file);
	cmode = 1;			/* allow token like '#xxx' */
	crflag = 1;			/* require '\n' as a token */
	if (type == TYPE_YACC)
		ymode = 1;		/* allow token like '%xxx' */

	while ((cc = nexttoken(interested, c_reserved_word)) != EOF) {
		switch (cc) {
		case SYMBOL:		/* symbol	*/
			if (inC && peekc(0) == '('/* ) */) {
				if (param->isnotfunction(token)) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				} else if (level > 0 || startmacro) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				} else if (level == 0 && !startmacro && !startsharp) {
					char arg1[MAXTOKEN], savetok[MAXTOKEN], *saveline;
					int savelineno = lineno;

					strlimcpy(savetok, token, sizeof(savetok));
					strbuf_reset(sb);
					strbuf_puts(sb, sp);
					saveline = strbuf_value(sb);
					arg1[0] = '\0';
					/*
					 * Guile function entry using guile-snarf is like follows:
					 *
					 * SCM_DEFINE (scm_list, "list", 0, 0, 1, 
					 *           (SCM objs),
					 *            "Return a list containing OBJS, the arguments to `list'.")
					 * #define FUNC_NAME s_scm_list
					 * {
					 *   return objs;
					 * }
					 * #undef FUNC_NAME
					 *
					 * We should assume the first argument as a function name instead of 'SCM_DEFINE'.
					 */
					if (function_definition(param, arg1)) {
						if (!strcmp(savetok, "SCM_DEFINE") && *arg1)
							strlimcpy(savetok, arg1, sizeof(savetok));
						PUT(PARSER_DEF, savetok, savelineno, saveline);
					} else {
						PUT(PARSER_REF_SYM, savetok, savelineno, saveline);
					}
				}
			} else {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			}
			break;
		case '{':  /* } */
			DBG_PRINT(level, "{"); /* } */
			if (yaccstatus == RULES && level == 0)
				inC = 1;
			++level;
			if ((param->flags & PARSER_BEGIN_BLOCK) && atfirst) {
				if ((param->flags & PARSER_WARNING) && level != 1)
					warning("forced level 1 block start by '{' at column 0 [+%d %s].", lineno, curfile); /* } */
				level = 1;
			}
			break;
			/* { */
		case '}':
			if (--level < 0) {
				if (externclevel > 0)
					externclevel--;
				else if (param->flags & PARSER_WARNING)
					warning("missing left '{' [+%d %s].", lineno, curfile); /* } */
				level = 0;
			}
			if ((param->flags & PARSER_END_BLOCK) && atfirst) {
				if ((param->flags & PARSER_WARNING) && level != 0) /* { */
					warning("forced level 0 block end by '}' at column 0 [+%d %s].", lineno, curfile);
				level = 0;
			}
			if (yaccstatus == RULES && level == 0)
				inC = 0;
			/* { */
			DBG_PRINT(level, "}");
			break;
		case '\n':
			if (startmacro && level != savelevel) {
				if (param->flags & PARSER_WARNING)
					warning("different level before and after #define macro. reseted. [+%d %s].", lineno, curfile);
				level = savelevel;
			}
			startmacro = startsharp = 0;
			break;
		case YACC_SEP:		/* %% */
			if (level != 0) {
				if (param->flags & PARSER_WARNING)
					warning("forced level 0 block end by '%%' [+%d %s].", lineno, curfile);
				level = 0;
			}
			if (yaccstatus == DECLARATIONS) {
				PUT(PARSER_DEF, "yyparse", lineno, sp);
				yaccstatus = RULES;
			} else if (yaccstatus == RULES)
				yaccstatus = PROGRAMS;
			inC = (yaccstatus == PROGRAMS) ? 1 : 0;
			break;
		case YACC_BEGIN:	/* %{ */
			if (level != 0) {
				if (param->flags & PARSER_WARNING)
					warning("forced level 0 block end by '%%{' [+%d %s].", lineno, curfile);
				level = 0;
			}
			if (inC == 1 && (param->flags & PARSER_WARNING))
				warning("'%%{' appeared in C mode. [+%d %s].", lineno, curfile);
			inC = 1;
			break;
		case YACC_END:		/* %} */
			if (level != 0) {
				if (param->flags & PARSER_WARNING)
					warning("forced level 0 block end by '%%}' [+%d %s].", lineno, curfile);
				level = 0;
			}
			if (inC == 0 && (param->flags & PARSER_WARNING))
				warning("'%%}' appeared in Yacc mode. [+%d %s].", lineno, curfile);
			inC = 0;
			break;
		case YACC_UNION:	/* %union {...} */
			if (yaccstatus == DECLARATIONS)
				PUT(PARSER_DEF, "YYSTYPE", lineno, sp);
			break;
		/*
		 * #xxx
		 */
		case SHARP_DEFINE:
		case SHARP_UNDEF:
			startmacro = 1;
			savelevel = level;
			if ((c = nexttoken(interested, c_reserved_word)) != SYMBOL) {
				pushbacktoken();
				break;
			}
			if (peekc(1) == '('/* ) */) {
				PUT(PARSER_DEF, token, lineno, sp);
				while ((c = nexttoken("()", c_reserved_word)) != EOF && c != '\n' && c != /* ( */ ')')
					if (c == SYMBOL)
						PUT(PARSER_REF_SYM, token, lineno, sp);
				if (c == '\n')
					pushbacktoken();
			} else {
				PUT(PARSER_DEF, token, lineno, sp);
			}
			break;
		case SHARP_IMPORT:
		case SHARP_INCLUDE:
		case SHARP_INCLUDE_NEXT:
		case SHARP_ERROR:
		case SHARP_LINE:
		case SHARP_PRAGMA:
		case SHARP_WARNING:
		case SHARP_IDENT:
		case SHARP_SCCS:
			while ((c = nexttoken(interested, c_reserved_word)) != EOF && c != '\n')
				;
			break;
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, cc);
			break;
		case SHARP_SHARP:		/* ## */
			(void)nexttoken(interested, c_reserved_word);
			break;
		case C_EXTERN: /* for 'extern "C"/"C++"' */
			if (peekc(0) != '"') /* " */
				continue; /* If does not start with '"', continue. */
			while ((c = nexttoken(interested, c_reserved_word)) == '\n')
				;
			/*
			 * 'extern "C"/"C++"' block is a kind of namespace block.
			 * (It doesn't have any influence on level.)
			 */
			if (c == '{') /* } */
				externclevel++;
			else
				pushbacktoken();
			break;
		case C_STRUCT:
		case C_ENUM:
		case C_UNION:
			while ((c = nexttoken(interested, c_reserved_word)) == C___ATTRIBUTE__)
				process_attribute(param);
			if (c == SYMBOL) {
				if (peekc(0) == '{') /* } */ {
					PUT(PARSER_DEF, token, lineno, sp);
					do {
						c = nexttoken(interested, c_reserved_word);
					} while (c == '\n');
				} else {
					PUT(PARSER_REF_SYM, token, lineno, sp);
					c = nexttoken(interested, c_reserved_word);
				}
			}
			if (c == '{' /* } */ && cc == C_ENUM) {
				enumerator_list(param);
			} else {
				pushbacktoken();
			}
			break;
		/* control statement check */
		case C_BREAK:
		case C_CASE:
		case C_CONTINUE:
		case C_DEFAULT:
		case C_DO:
		case C_ELSE:
		case C_FOR:
		case C_GOTO:
		case C_IF:
		case C_RETURN:
		case C_SWITCH:
		case C_WHILE:
			if ((param->flags & PARSER_WARNING) && !startmacro && level == 0)
				warning("Out of function. %8s [+%d %s]", token, lineno, curfile);
			break;
		case C_TYPEDEF:
			{
				/*
				 * This parser is too complex to maintain.
				 * We should rewrite the whole.
				 */
				char savetok[MAXTOKEN];
				int savelineno = 0;
				int typedef_savelevel = level;

				savetok[0] = 0;

				/* skip type qualifiers */
				do {
					c = nexttoken("{}(),;", c_reserved_word);
				} while (IS_TYPE_QUALIFIER(c) || c == '\n');

				if ((param->flags & PARSER_WARNING) && c == EOF) {
					warning("unexpected eof. [+%d %s]", lineno, curfile);
					break;
				} else if (c == C_ENUM || c == C_STRUCT || c == C_UNION) {
					char *interest_enum = "{},;";
					int c_ = c;

					while ((c = nexttoken(interest_enum, c_reserved_word)) == C___ATTRIBUTE__)
						process_attribute(param);
					/* read tag name if exist */
					if (c == SYMBOL) {
						if (peekc(0) == '{') /* } */ {
							PUT(PARSER_DEF, token, lineno, sp);
							do {
								c = nexttoken(interest_enum, c_reserved_word);
							} while (c == '\n');
						} else {
							PUT(PARSER_REF_SYM, token, lineno, sp);
							c = nexttoken(interest_enum, c_reserved_word);
						}
					}
					if (c_ == C_ENUM) {
						if (c == '{') /* } */
							c = enumerator_list(param);
						else
							pushbacktoken();
					} else {
						for (; c != EOF; c = nexttoken(interest_enum, c_reserved_word)) {
							switch (c) {
							case SHARP_IFDEF:
							case SHARP_IFNDEF:
							case SHARP_IF:
							case SHARP_ELIF:
							case SHARP_ELSE:
							case SHARP_ENDIF:
								condition_macro(param, c);
								continue;
							default:
								break;
							}
							if (c == ';' && level == typedef_savelevel) {
								if (savetok[0])
									PUT(PARSER_DEF, savetok, savelineno, sp);
								break;
							} else if (c == '{')
								level++;
							else if (c == '}') {
								if (--level == typedef_savelevel)
									break;
							} else if (c == SYMBOL) {
								PUT(PARSER_REF_SYM, token, lineno, sp);
								/* save lastest token */
								strlimcpy(savetok, token, sizeof(savetok));
								savelineno = lineno;
							}
						}
						if (c == ';')
							break;
					}
					if ((param->flags & PARSER_WARNING) && c == EOF) {
						warning("unexpected eof. [+%d %s]", lineno, curfile);
						break;
					}
				} else if (c == SYMBOL) {
					PUT(PARSER_REF_SYM, token, lineno, sp);
				}
				savetok[0] = 0;
				while ((c = nexttoken("(),;", c_reserved_word)) != EOF) {
					switch (c) {
					case SHARP_IFDEF:
					case SHARP_IFNDEF:
					case SHARP_IF:
					case SHARP_ELIF:
					case SHARP_ELSE:
					case SHARP_ENDIF:
						condition_macro(param, c);
						continue;
					default:
						break;
					}
					if (c == '(')
						level++;
					else if (c == ')')
						level--;
					else if (c == SYMBOL) {
						if (level > typedef_savelevel) {
							PUT(PARSER_REF_SYM, token, lineno, sp);
						} else {
							/* put latest token if any */
							if (savetok[0]) {
								PUT(PARSER_REF_SYM, savetok, savelineno, sp);
							}
							/* save lastest token */
							strlimcpy(savetok, token, sizeof(savetok));
							savelineno = lineno;
						}
					} else if (c == ',' || c == ';') {
						if (savetok[0]) {
							PUT(PARSER_DEF, savetok, lineno, sp);
							savetok[0] = 0;
						}
					}
					if (level == typedef_savelevel && c == ';')
						break;
				}
				if (param->flags & PARSER_WARNING) {
					if (c == EOF)
						warning("unexpected eof. [+%d %s]", lineno, curfile);
					else if (level != typedef_savelevel)
						warning("unmatched () block. (last at level %d.)[+%d %s]", level, lineno, curfile);
				}
			}
			break;
		case C___ATTRIBUTE__:
			process_attribute(param);
			break;
		default:
			break;
		}
	}
	strbuf_close(sb);
	if (param->flags & PARSER_WARNING) {
		if (level != 0)
			warning("unmatched {} block. (last at level %d.)[+%d %s]", level, lineno, curfile);
		if (piflevel != 0)
			warning("unmatched #if block. (last at level %d.)[+%d %s]", piflevel, lineno, curfile);
	}
	closetoken();
}
예제 #11
0
/*
 * Requires:
 *   "ptr" is either the address of an allocated block or NULL.
 *
 * Effects:
 *   Reallocates the block "ptr" to a block with at least "size" bytes of
 *   payload, unless "size" is zero.  If "size" is zero, frees the block
 *   "ptr" and returns NULL.  If the block "ptr" is already a block with at
 *   least "size" bytes of payload, then "ptr" may optionally be returned.
 *   Otherwise, a new block is allocated and the contents of the old block
 *   "ptr" are copied to that new block.  Returns the address of this new
 *   block if the allocation was successful and NULL otherwise.
 */
void *mm_realloc(void *ptr, size_t size)
{
	size_t oldsize;
	void *newptr;

	/* If size == 0 then this is just free, and we return NULL. */
	if (size == 0) {
		mm_free(ptr);
		return (NULL);
	}

	/* If oldptr is NULL, then this is just malloc. */
	if (ptr == NULL)
		return (mm_malloc(size));
	oldsize = GET_SIZE(HDRP(ptr));
	size_t asize;
	if((size+WSIZE)%DSIZE==0)
			asize = size+WSIZE;
	else
		asize = (((size+WSIZE)/DSIZE+1)*DSIZE);
	if(oldsize == asize)
		return ptr;
	if(oldsize > asize) {
		if(oldsize-asize<=MINIMUM)
			return ptr;
		bool prev_alloc = GET_PREV_ALLOC(HDRP(ptr));
		if(!prev_alloc) {
				PUT(HDRP(ptr),PACK(asize,1));
		} else {
				PUT(HDRP(ptr),PACK(asize,3));		
		}
		PUT(HDRP(ptr),PACK(oldsize-asize,2));
		PUT(FTRP(ptr),PACK(oldsize-asize,2));		
		int *next = NEXT_BLKP(ptr);
		bool next_alloc = GET_ALLOC(HDRP(next));
		size_t size_next = GET_SIZE(HDRP(next));
		if(!next_alloc) {
			PUT(HDRP(ptr),PACK(size_next,0));		
			PUT(FTRP(ptr),PACK(size_next,0));
		} else {
			PUT(HDRP(ptr),PACK(size_next,1));		
		}
	}
	int *next = NEXT_BLKP(ptr);
	bool next_alloc = GET_ALLOC(HDRP(next));
	if(!next_alloc) {
		size_t size_next = GET_SIZE(HDRP(next));
		if((size_next+oldsize)>=asize) {
			oldsize += size_next;
			if((oldsize-asize)>=(2*WSIZE)){
				bool prev_alloc = GET_PREV_ALLOC(HDRP(ptr));
				if(!prev_alloc) {
					PUT(HDRP(ptr),PACK(asize,1));
				} else {
					PUT(HDRP(ptr),PACK(asize,3));
				}
				int *next = NEXT_BLKP(ptr);
				PUT(HDRP(next),PACK(oldsize-asize,2));
				PUT(FTRP(next),PACK(oldsize-asize,2));				
			} else {
				bool prev_alloc = GET_PREV_ALLOC(HDRP(ptr));
				if(!prev_alloc) {
					PUT(HDRP(ptr),PACK(oldsize,1));
				} else {
					PUT(HDRP(ptr),PACK(oldsize,3));
				}
				int *next = NEXT_BLKP(ptr);
				size_t size_next = GET_SIZE(HDRP(next));
				bool next_alloc = GET_ALLOC(HDRP(next));
				if(!next_alloc) {
					PUT(HDRP(next),PACK(size_next,2));
					PUT(FTRP(next),PACK(size_next,2));
				} else {
					PUT(HDRP(next),PACK(size_next,3));
				}
			}
			return ptr;
		}
	}
	newptr = mm_malloc(size);

	/* If realloc() fails the original block is left untouched  */
	if (newptr == NULL)
		return (NULL);

	/* Copy the old data. */
	if (size < oldsize)
		oldsize = size;
	memcpy(newptr, ptr, oldsize);

	/* Free the old block. */
	mm_free(ptr);

	return (newptr);
}
예제 #12
0
파일: C.c 프로젝트: qbai/.emacs.d
/**
 * function_definition: return if function definition or not.
 *
 *	@param	param	
 *	@param[out]	arg1	the first argument
 *	@return	target type
 */
static int
function_definition(const struct parser_param *param, char arg1[MAXTOKEN])
{
	int c;
	int brace_level, isdefine;
	int accept_arg1 = 0;

	brace_level = isdefine = 0;
	while ((c = nexttoken("()", c_reserved_word)) != EOF) {
		switch (c) {
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, c);
			continue;
		default:
			break;
		}
		if (c == '('/* ) */)
			brace_level++;
		else if (c == /* ( */')') {
			if (--brace_level == 0)
				break;
		}
		/* pick up symbol */
		if (c == SYMBOL) {
			if (accept_arg1 == 0) {
				accept_arg1 = 1;
				strlimcpy(arg1, token, MAXTOKEN);
			}
			PUT(PARSER_REF_SYM, token, lineno, sp);
		}
	}
	if (c == EOF)
		return 0;
	brace_level = 0;
	while ((c = nexttoken(",;[](){}=", c_reserved_word)) != EOF) {
		switch (c) {
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, c);
			continue;
		case C___ATTRIBUTE__:
			process_attribute(param);
			continue;
		default:
			break;
		}
		if (c == '('/* ) */ || c == '[')
			brace_level++;
		else if (c == /* ( */')' || c == ']')
			brace_level--;
		else if (brace_level == 0
		    && ((c == SYMBOL && strcmp(token, "__THROW")) || IS_RESERVED_WORD(c)))
			isdefine = 1;
		else if (c == ';' || c == ',') {
			if (!isdefine)
				break;
		} else if (c == '{' /* } */) {
			pushbacktoken();
			return 1;
		} else if (c == /* { */'}')
			break;
		else if (c == '=')
			break;

		/* pick up symbol */
		if (c == SYMBOL)
			PUT(PARSER_REF_SYM, token, lineno, sp);
	}
	return 0;
}
예제 #13
0
/*
 * Actual conversion; called from iconv()
 */
size_t
_icv_iconv(struct _icv_state *st, char **inbuf, size_t *inbytesleft,
				char **outbuf, size_t *outbytesleft)
{
	int				cset, stat;
	unsigned char	*op, ic, offset;
	char			*ip;
	size_t			ileft, oleft;
	size_t			retval;

	cset = st->_st_cset;
	stat = st->_st_stat;

	/*
	 * If (inbuf == 0 || *inbuf == 0) then this conversion is
	 * placed into initial state.
	 */
	if ((inbuf == 0) || (*inbuf == 0)) {
		cset = CS_0;
		stat = ST_INIT;
		op = (unsigned char *)*outbuf;
		oleft = *outbytesleft;
		retval = 0;
		goto ret2;
	}

	ip = *inbuf;
	op = (unsigned char *)*outbuf;
	ileft = *inbytesleft;
	oleft = *outbytesleft;
	offset = 0;
	/* Everything down to here was taken unchanged from  @(#)ISO-2022-JP%SJIS. 
	   =======================================================================
	
	 *
	 * Main loop; basically 1 loop per 1 input byte
	 */

	while (ileft > 0) 
	{
		GET(ic);
	/*
		If the char is one of the following [ / ] { | } then convert 
		it to its corresponding value. In all other cases if the char 
		is greater than octal \178 ( ie a high bit char) convert it 
		to an underscore (_), as it has no mapping to 7 bit ASCII.
		Otrherwise the char is the same in both cose sets. 
	*/
		
	/* The following was changed from the switch statement for
	   64-bit building
	*/

		if (ic == '\100')
			ic = '\247';
		else if (ic == '[')
			ic = '\304';
		else if (ic == ']')
			ic = '\334';
		else if (ic == '{')
			ic = '\344';
		else if (ic == '|')
			ic = '\366';
		else if (ic == '}')
			ic = '\374';
		else if (ic == '\134')
			ic = '\326';
		else if (ic == '~')
			ic = '\337';
		else if (ic > '\177')
			ic = '_';





/*		switch ( ic )
		{
			case '\100' :
				ic = '\247';
				break;
			case '[' :
				ic = '\304';
				break;
			case ']' :
				ic = '\334';
				break;
			case '{' :
				ic = '\344';
				break;
			case '|' :
				ic = '\366';
				break;
			case '}' :
				ic = '\374';
				break;
			case '\134' :
				ic = '\326';
				break;
			case '~' :
				ic = '\337';
				break;
			default :
				if (ic > '\177')
					ic = '_'; 
				break;
		} */
			
		PUT(ic);	
	/* 
		Put the converted character into the output buffer, and decrement 
		the count of chars left in both the in and out buffers.
		If we have no space left in the out buffer, but we have no reached
		the end of the input buffer. We return what we have, and set the
		errno (Error) to E2BIG.
	*/
		if ((oleft < 1)	 && (ileft > 0))
		{
			errno = E2BIG;
			retval = ERR_RETURN;
			goto ret;
		}		


	}
/* 
We only get here if the end of the in buffer has been reached, we therefore return the
value 0 to denote that we have sucesfully converted the inbuffer.
*/
	retval = ileft;

/*  Taken unchanged from   @(#)ISO-2022-JP%SJIS.  */

ret:
	st->_st_cset = cset;
	st->_st_stat = stat;
	*inbuf = ip;
	*inbytesleft = ileft;
ret2:
	*outbuf = (char *)op;
	*outbytesleft = oleft;

	return (retval);
}
예제 #14
0
파일: mm.c 프로젝트: divd/ece454
/**********************************************************
 * coalesce
 * Covers the 4 cases discussed in the text:
 * - both neighbours are allocated
 * - the next block is available for coalescing
 * - the previous block is available for coalescing
 * - both neighbours are available for coalescing
 **********************************************************/
void *coalesce(void *bp)
{
    size_t prev_alloc = GET_ALLOC(FTRP(PREV_BLKP(bp)));
    size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
    size_t size = GET_SIZE(HDRP(bp));

    // MACRO for PREV_BLKP does not work for this case
    if (bp == heap_listp) {
    	prev_alloc = 1;
    }
    // printf("Coalesce: size1: %u\n",(unsigned int) size);
    void *coalesced_bp = NULL;

    if (prev_alloc && next_alloc) {       /* Case 1 */
        coalesced_bp = bp;
    }

    else if (prev_alloc && !next_alloc) { /* Case 2 */
		//account for size 16 external fragmentation which isn't
		//in the free list
		if (GET_SIZE(HDRP(NEXT_BLKP(bp))) != DSIZE) {
			assert(remove_from_free_list(NEXT_BLKP(bp)));
		}
        size += GET_SIZE(HDRP(NEXT_BLKP(bp)));
        PUT(HDRP(bp), PACK(size, 0));
        PUT(FTRP(bp), PACK(size, 0));
        coalesced_bp = bp;
    }

    else if (!prev_alloc && next_alloc){
		//account for size 16 external fragmentation which isn't
		//in the free list
		if (GET_SIZE(HDRP(PREV_BLKP(bp))) != DSIZE) {
			void * if_free = remove_from_free_list(PREV_BLKP(bp));
			assert(if_free);
		}
    	  /* Case 3 */
         size += GET_SIZE(HDRP(PREV_BLKP(bp)));
		 PUT(FTRP(bp), PACK(size, 0));
		 PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0));
		 coalesced_bp = PREV_BLKP(bp);
    }

	else { /* Case 4 */
		//account for size 16 external fragmentation which isn't
		//in the free list
		int size_prev = GET_SIZE(HDRP(PREV_BLKP(bp)));
		int size_next = GET_SIZE(FTRP(NEXT_BLKP(bp)));
		if (size_prev != DSIZE)
			assert(remove_from_free_list(PREV_BLKP(bp)));
		if (size_next != DSIZE)
			assert(remove_from_free_list(NEXT_BLKP(bp)));

		size += size_prev + size_next;
        // printf("Coalesce: size_p: %u\n",(unsigned int) size_prev);
        // printf("Coalesce: size_n: %u\n",(unsigned int) size_next);
		PUT(HDRP(PREV_BLKP(bp)), PACK(size,0));
		PUT(FTRP(NEXT_BLKP(bp)), PACK(size,0));
		coalesced_bp = PREV_BLKP(bp);
	}

	// printf("Coalesced into size: %u, addr: %p\n",(unsigned int) size, (int*)coalesced_bp);
	return coalesced_bp;
}
예제 #15
0
파일: conv.c 프로젝트: nawhizz/KAIT
void main(int argc, char *argv[])
{
    char val[512], *p;
    char rbuf[512+1];
    char svcname[17];
    int timeout;
    long revent, rcvlen;
    FLDKEY key;
    FBUF *transf;
    FILE *fp;
    int cd, n, fflag=0, i, idx=0;
    int ret;

/*
    if (argc != 2) {
        fprintf(stderr, "Usage:%s input-file\n", argv[0]);
        exit(1);
    }
*/

    if(parseArg(argc, argv)<0){
	printf("parseArg error!!\n");
	exit(1);
    }

    if( (fp=fopen(filename, "r")) == (FILE *)0 ){
        printf( "file open error [%d:%s]\n", errno, strerror(errno) );
        exit( 1 );
    }

    memset( svcname, 0x00, sizeof(svcname) );

    if( get_svcname(fp, svcname) < 0 ){
        printf( "get_svcname() failed!! -- (input-file=%s)\n", argv[1] );
        exit(1);
    }


    timeout = 5;

    n = tpstart((TPSTART_T *)NULL);
    if (n < 0) {
       fprintf(stderr, "tpstart fail tperrno = %s\n", tperrno);
       exit(1);
    }
    printf("tpstart ok!\n");


    transf = fballoc(100, 100);

    if( transf == NULL) {
        fprintf(stderr, "fballoc fail: rcvbuf tperrno = %d\n", tperrno);
        tpend();
        exit(1);
    }

    Finit(transf, Fsizeof(transf));

    while( 1 ){
       memset( rbuf, 0x00, sizeof(rbuf) );
       if( fgets(rbuf, sizeof(rbuf)-1, fp)==(char *) 0 ){
           break;
       }

       p = strchr(rbuf, '\n');
       if( p == (char *)0 && strlen(rbuf) >= sizeof(rbuf)-1 ){
           printf( "한 라인의 길이가 너무 길어 무시합니다..\n" );
           printf( "=>[%s]\n", rbuf );
           continue;
       }
       *p = 0x00;

       memset( val, 0x00, sizeof(val) );
       key = 0;

       if( line_proc(rbuf, &key, &idx, val)<0 ) continue;
       PUT(key, idx, val);
printf( "key=%d, idx=%d, val=%s\n", key, idx, val );
       fflag = 1;
    }

    if( !fflag ){
        printf( "not exist send data .....\n" );
        fbfree( transf );
        tpend();
        exit(1);
    }

printf( ">>service[%s], send data->\n", svcname );
fbprint( transf );
printf( "\t----------------------------------------------------\n\n\n" );
fflush( stdout );

/* original
    cd = tpconnect(svcname, (char *)transf, fbget_fbsize(transf), TPRECVONLY);
*/
    if(flag==1){
	ret = tx_begin();
	printf("tx_begin() [%s] \n", ret==TX_OK ? "success" : "fail");
	if(ret!=TX_OK) exit(1);
    }
    cd = tpcall(svcname, (char *)transf, fbget_fbsize(transf), (char **)&transf, (long *)&rcvlen, 0);
    if (cd < 0) {
    if(flag==1){
	ret = tx_rollback();
	printf("tx_rollback() [%s] \n", ret==TX_OK ? "success" : "fail");
	if(ret!=TX_OK) exit(1);
    }
        fprintf(stderr, "tpcall fail tperrno = %d\n", tperrno);
        fbfree( transf );
        tpend();
        exit(1);
    }
    fprintf(stdout, "TPCALL SUCCESS!!\n");
    if(flag==1){
	ret = tx_commit();
	printf("tx_commit() [%s] \n", ret==TX_OK ? "success" : "fail");
	if(ret!=TX_OK) exit(1);
    }
/*
    i = 0;
    while( 1 ){

       Finit(transf, Fsizeof(transf));

       n = tprecv(cd, (char **)&transf, (long *)&rcvlen, 0, &revent);

       if (n < 0 && tperrno == TPEEVENT ){
           if(revent == TPEV_SVCSUCC )
                  printf( "service completed(TPSUCC) !\n" );
           else if(revent == TPEV_SVCFAIL )
                  printf( "service completed(TPFAIL) !\n" );
           else{
                  printf( "tprecv error : event[0x%08X], tperrno[%d]\n", revent, tperrno );
                  break;
           }
       }
       else if( n < 0 ){
           printf( "tprecv error(no event) : tperrno[%d]\n", tperrno );
           break;
       }

       fbprint( transf );
       printf( "\t------------------------------------------------------[%3d th]\n\n", i++ );
       fflush( stdout );
       if (n < 0 ) break;
    }
*/

    fbfree(transf);

    tpend();
}
예제 #16
0
int main()
{
	SystemInit();
	const Ec1 g1(-1, 1);
	const Ec2 g2(
		Fp2(Fp(g2c.aa), Fp(g2c.ab)),
		Fp2(Fp(g2c.ba), Fp(g2c.bb))
	);
	// assertBool g2 and g1 on curve
	assertBool("g1 is on EC", g1.isValid());
	assertBool("g2 is on twist EC", g2.isValid());
	puts("order of group");
	const Mpz& r = GetParamR();
	PUT(r);
	{
		Ec1 t = g1;
		t.mul(r);
		assertBool("orgder of g1 == r", t.isZero());
	}
	{
		Ec2 t = g2;
		t.mul(r);
		assertBool("order of g2 == r", t.isZero());
	}
	const Mpz a("123456789012345");
	const Mpz b("998752342342342342424242421");

	// scalar-multiplication sample
	{
		Mpz c = a;
		c.add(b);
		Ec1 Pa = g1; Pa.mul(a);
		Ec1 Pb = g1; Pb.mul(b);
		Ec1 Pc = g1; Pc.mul(c);
		Ec1 out = Pa;
		out.add(Pb);

		assertEqual("check g1 * c = g1 * a + g1 * b", Pc, out);
	}

	Fp12 e;
	// calc e : G2 x G1 -> G3 pairing
	e.pairing(g2, g1); // e = e(g2, g1)
	PUT(e);
	{
		Fp12 t = e;
		t.power(r);
		assertEqual("order of e == r", t, Fp12(1));
	}
	Ec2 g2a = g2;
	g2a.mul(a);
	Fp12 ea1;
	ea1.pairing(g2a, g1);
	Fp12 ea2 = e;
	ea2.power(a); // ea2 = e^a
	assertEqual("e(g2 * a, g1) = e(g2, g1)^a", ea1, ea2);

	Ec1 g1b = g1;
	g1b.mul(b);
	Fp12 eb1;
	eb1.pairing(g2, g1b); // eb1 = e(g2, g1b)
	Fp12 eb2 = e;
	eb2.power(b); // eb2 = e^b
	assertEqual("e(g2a, g1 * b) = e(g2, g1)^b", eb1, eb2);

	Ec1 q1 = g1;
	q1.mul(12345);
	assertBool("q1 is on EC", q1.isValid());
	Fp12 e1, e2;
	e1.pairing(g2, g1); // e1 = e(g2, g1)
	e2.pairing(g2, q1); // e2 = e(g2, q1)
	Ec1 q2 = g1;
	q2.add(q1);
	e.pairing(g2, q2); // e = e(g2, q2)
	e1.mul(e2);
	assertEqual("e = e1 * e2", e, e1);
	/*
		reduce one copy as the following
	*/
	g2a = g2;
	g2a.mul(a);
	g1b = g1;
	g1b.mul(b);
	Ec2 g2at = g2; g2at.mul(a);
	Ec1 g1bt = g1; g1bt.mul(b);
	assertEqual("g2a == g2 * a", g2a, g2at);
	assertEqual("g1b == g1 * b", g1b, g1bt);
	printf("errNum = %d\n", errNum);
}
예제 #17
0
int main(int argc, char **argv) {
   // We don't check bounds here: we'd end up essentially duplicating the logic
   // from load_string, and there's little point in that.
   tap_n(2*4 + 2*2 + 2);

   if (argc > 1) {
      long s = atol(argv[1]);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   } else {
      time_t s = time(NULL);
      init_by_array((uint32_t*)&s, sizeof s / sizeof(uint32_t));
   }

   void *data = malloc(DATA_LEN);
   random_fill(data, DATA_LEN);

   const size_t codepoints = DATA_LEN * CHAR_BIT / 21;

   mushcoords beg = MUSHCOORDS(MUSHCELL_MAX-WRAP_AFTER,
                               MUSHCELL_MAX-WRAP_AFTER,
                               MUSHCELL_MAX-WRAP_AFTER),
              end;

   void *space_buf = malloc(mushspace_sizeof);
   mushspace *space;

   bool ok;

   codepoint_reader cp_reader;

   mushcoords pos, pos_next;
   bool cr;

#define POS_INIT \
   pos_next = beg; \
   cr = false;

#define CP_POS(cp) \
   pos = pos_next; \
   switch (cp) { \
   default: \
      if (MUSHSPACE_DIM > 1 && cr) { \
         cr = false; \
         pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      pos_next = MUSHCOORDS(pos.x + 1, pos.y, pos.z); \
      break; \
   case '\r': \
      if (MUSHSPACE_DIM > 1) { \
         if (cr) \
            pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
         cr = true; \
      } \
      continue; \
   case '\n': \
      if (MUSHSPACE_DIM > 1) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      continue; \
   case '\f': \
      if (MUSHSPACE_DIM > 2) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, beg.y, pos.z + 1); \
      } else if (cr) { \
         cr = false; \
         pos_next = pos = MUSHCOORDS(beg.x, pos.y + 1, pos.z); \
      } \
      continue; \
   }

#define LOAD_STRING(suf, T, ENCODER, BLOWUP, FOREACH_CP) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   \
   T *encoded_data##suf = (T*)data; \
   size_t encoded_len##suf = DATA_LEN / sizeof *encoded_data##suf; \
   if (BLOWUP) { \
      encoded_data##suf = \
         malloc((codepoints * BLOWUP) * sizeof *encoded_data##suf); \
      encoded_len##suf = ENCODER(data, encoded_data##suf, codepoints); \
   } \
   \
   mushspace_load_string##suf( \
      space, encoded_data##suf, encoded_len##suf, &end, beg, false); \
   \
   if (BLOWUP) \
      free(encoded_data##suf); \
   \
   ok = true; \
   POS_INIT; \
   FOREACH_CP(suf) { \
      CP_POS(cp##suf); \
      mushcell gc = mushspace_get(space, pos); \
      if (gc == cp##suf) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match data given to load_string" #suf); \
      printf("  ---\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n" \
             "  failed index: %zu\n", \
             cp##suf, gc, ii##suf); \
      printf("  failed pos relative to min: ("); \
      for (uint8_t i = 0; i < MUSHSPACE_DIM; ++i) \
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[i], MUSHCELL_MIN)); \
      printf(" )\n" \
             "  ...\n"); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches data given to load_string" #suf); \
   \
   mushspace_free(space);

#define DIRECT_FOREACH_CP(s) \
   mushcell cp##s; \
   size_t ii##s = 0; \
   for (; ii##s < encoded_len##s && (cp##s = encoded_data##s[ii##s], true); \
        ++ii##s)

#define READER_FOREACH_CP(s) \
   cp_reader = make_codepoint_reader(data, codepoints); \
   size_t ii##s = 0; \
   for (mushcell cp##s; (cp##s = next_codepoint(&cp_reader)) != UINT32_MAX; \
        ++ii##s)

   LOAD_STRING(, unsigned char,  dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_cell,  mushcell, dummy, 0,        DIRECT_FOREACH_CP);
   LOAD_STRING(_utf8,  uint8_t,  encode_utf8,  4, READER_FOREACH_CP);
   LOAD_STRING(_utf16, uint16_t, encode_utf16, 2, READER_FOREACH_CP);

   const mushcell *data_cell       = (const mushcell*)data;
   const size_t    data_cell_count = DATA_LEN / sizeof *data_cell;

   mushcoords *saved_pos = malloc(data_cell_count * sizeof *saved_pos);

#define PUT(FOREACH_CELL, S, GET_POS, SAVE_POS) \
   space = mushspace_init(space_buf, NULL); \
   if (!space) { \
      tap_not_ok("init returned null"); \
      tap_skip_remaining("init failed"); \
      free(saved_pos); \
      return 1; \
   } \
   tap_ok("init succeeded"); \
   POS_INIT; \
   FOREACH_CELL { \
      GET_POS(data_cell[i]); \
      if (SAVE_POS) \
         saved_pos[i] = pos; \
      mushspace_put(space, pos, data_cell[i]); \
   } \
   \
   ok = true; \
   POS_INIT; \
   for (size_t i = 0; i < data_cell_count; ++i) { \
      mushcell dc = data_cell[i]; \
      GET_POS(dc); \
      mushcell gc = mushspace_get(space, pos); \
      if (gc == dc) \
         continue; \
      ok = false; \
      tap_not_ok("get doesn't match what was put" S); \
      printf("  ---\n" \
             "  failed index: %zu\n" \
             "  expected: %" MUSHCELL_PRIx "\n" \
             "  got: %" MUSHCELL_PRIx "\n", \
             i, dc, gc); \
      printf("  failed pos relative to min: ("); \
      for (uint8_t j = 0; j < MUSHSPACE_DIM; ++j) \
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[j], MUSHCELL_MIN)); \
      printf(" )\n" \
             "  ...\n"); \
      break; \
   } \
   if (ok) \
      tap_ok("get matches what was put" S);

#define FORWARD for (size_t i = 0; i < data_cell_count; ++i)
#define REVERSE for (size_t i = data_cell_count; i--;)

#define SAVED_POS(_) pos = saved_pos[i];

   PUT(FORWARD, " (forward order)", CP_POS, true);
   mushspace_free(space);
   PUT(REVERSE, " (reverse order)", SAVED_POS, false);
   free(saved_pos);

   if (!ok) {
      tap_skip_remaining("won't copy bad space");
      return 1;
   }

   void *space_buf2 = malloc(mushspace_sizeof);

   mushspace *space2 = mushspace_copy(space_buf2, space, NULL);
   mushspace_free(space);
   free(space_buf);

   space = space2;

   if (!space) {
      tap_not_ok("copy returned null");
      tap_skip_remaining("copy failed");
      return 1;
   }
   tap_ok("copy succeeded");

   ok = true;
   POS_INIT;
   for (size_t i = 0; i < DATA_LEN / sizeof *data_cell; ++i) {
      mushcell dc = data_cell[i];
      CP_POS(dc);
      mushcell gc = mushspace_get(space, pos);
      if (gc == dc)
         continue;
      ok = false;
      tap_not_ok("get in copy doesn't match data");
      printf("  ---\n"
             "  failed index: %zu\n"
             "  expected: %" MUSHCELL_PRIx "\n"
             "  got: %" MUSHCELL_PRIx "\n",
             i, dc, gc);
      printf("  failed pos relative to min: (");
      for (uint8_t j = 0; j < MUSHSPACE_DIM; ++j)
         printf(" %" MUSHCELL_PRId, mushcell_sub(pos.v[j], MUSHCELL_MIN)); \
      printf(" )\n"
             "  ...\n");
      break;
   }
   if (ok)
      tap_ok("get in copy matched data");

   free(data);
   mushspace_free(space);
   free(space_buf2);
}
예제 #18
0
파일: ui.c 프로젝트: roxma/neovim
static void remote_ui_inspect(UI *ui, Dictionary *info)
{
  UIData *data = ui->data;
  PUT(*info, "chan", INTEGER_OBJ((Integer)data->channel_id));
}
예제 #19
0
파일: Cpp.c 프로젝트: gsliu/emacs_C
/*
 * function_definition: return if function definition or not.
 *
 *	r)	target type
 */
static int
function_definition(const struct parser_param *param)
{
	int c;
	int brace_level;

	brace_level = 0;
	while ((c = nexttoken("()", cpp_reserved_word)) != EOF) {
		switch (c) {
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, c);
			continue;
		default:
			break;
		}
		if (c == '('/* ) */)
			brace_level++;
		else if (c == /* ( */')') {
			if (--brace_level == 0)
				break;
		}
		/* pick up symbol */
		if (c == SYMBOL)
			PUT(PARSER_REF_SYM, token, lineno, sp);
	}
	if (c == EOF)
		return 0;
	if (peekc(0) == ';') {
		(void)nexttoken(";", NULL);
		return 0;
	}
	brace_level = 0;
	while ((c = nexttoken(",;[](){}=", cpp_reserved_word)) != EOF) {
		switch (c) {
		case SHARP_IFDEF:
		case SHARP_IFNDEF:
		case SHARP_IF:
		case SHARP_ELIF:
		case SHARP_ELSE:
		case SHARP_ENDIF:
			condition_macro(param, c);
			continue;
		case CPP___ATTRIBUTE__:
			process_attribute(param);
			continue;
		default:
			break;
		}
		if (c == '('/* ) */ || c == '[')
			brace_level++;
		else if (c == /* ( */')' || c == ']')
			brace_level--;
		else if (brace_level == 0 && (c == ';' || c == ','))
			break;
		else if (c == '{' /* } */) {
			pushbacktoken();
			return 1;
		} else if (c == /* { */'}')
			break;
		else if (c == '=')
			break;
		/* pick up symbol */
		if (c == SYMBOL)
			PUT(PARSER_REF_SYM, token, lineno, sp);
	}
	return 0;
}
static int l3_proto2text(char **pos,char **end,int *length,
  const struct atm_blli *blli)
{
    if (!blli->l3_proto) return 0;
    PUT("l3=");
    switch (blli->l3_proto) {
#define X(u,l) case ATM_L3_##u: PUT(#l); break
	X(X25,x25);
	X(ISO8208,iso8208);
	X(X223,x223);
#undef X
	case ATM_L3_TR9577:
	    PUT("tr9577,ipi=");
	    if (blli->l3.tr9577.ipi != NLPID_IEEE802_1_SNAP) {
		PUT("0x%x",blli->l3.tr9577.ipi);
	    }
	    else {
		PUT("snap,oui=");
		DUMP(blli->l3.tr9577.snap,3);
		PUT(",pid=");
		DUMP(blli->l3.tr9577.snap+3,2);
	    }
	    MAYBE(",");
	    return 0;
	case ATM_L3_USER:
	    PUT("user,info=%d",blli->l3.user);
	    MAYBE(",");
	    return 0;
#define X(u,l) case ATM_L3_##u: PUT(#l); MAYBE(","); return 0
	X(ISO8473,iso8473);
	X(T70,t70);
	X(H321,h321);
#undef X
	case ATM_L3_H310:
	    PUT("h310");
	    MAYBE(",");
	    switch (blli->l3.h310.term_type) {
		case ATM_TT_NONE:
		    return 0;
		case ATM_TT_RX:
		    PUT("term=rx");
		    break;
		case ATM_TT_TX:
		    PUT("term=tx");
		    break;
		case ATM_TT_RXTX:
		    PUT("term=rxtx");
		    break;
		default:
		    return -1;
	    }
	    MAYBE(",");
	    mpx_cap(pos,end,length,"fw_mpx",blli->l3.h310.fw_mpx_cap);
	    mpx_cap(pos,end,length,"bw_mpx",blli->l3.h310.bw_mpx_cap);
	    return 0;
	default:
	    return -1;
    }
    MAYBE(",");
    if (blli->l3.itu.mode) {
	PUT("mode=");
	switch (blli->l3.itu.mode) {
	    case ATM_IMD_NORMAL:
		PUT("norm");
		break;
	    case ATM_IMD_EXTENDED:
		PUT("ext");
		break;
	    default:
		return -1;
	}
	MAYBE(",");
    }
    if (blli->l3.itu.def_size) {
	PUT("size=%d",blli->l3.itu.def_size);
	MAYBE(",");
    }
    if (blli->l3.itu.window) {
	PUT("window=%d",blli->l3.itu.window);
	MAYBE(",");
    }
    return 0;
}
예제 #21
0
size_t
do_scrub_chars (size_t (*get) (char *, size_t), char *tostart, size_t tolen)
{
  char *to = tostart;
  char *toend = tostart + tolen;
  char *from;
  char *fromend;
  size_t fromlen;
  register int ch, ch2 = 0;
  /* Character that started the string we're working on.  */
  static char quotechar;

  /*State 0: beginning of normal line
	  1: After first whitespace on line (flush more white)
	  2: After first non-white (opcode) on line (keep 1white)
	  3: after second white on line (into operands) (flush white)
	  4: after putting out a .linefile, put out digits
	  5: parsing a string, then go to old-state
	  6: putting out \ escape in a "d string.
	  7: no longer used
	  8: no longer used
	  9: After seeing symbol char in state 3 (keep 1white after symchar)
	 10: After seeing whitespace in state 9 (keep white before symchar)
	 11: After seeing a symbol character in state 0 (eg a label definition)
	 -1: output string in out_string and go to the state in old_state
	 -2: flush text until a '*' '/' is seen, then go to state old_state
#ifdef TC_V850
	 12: After seeing a dash, looking for a second dash as a start
	     of comment.
#endif
#ifdef DOUBLEBAR_PARALLEL
	 13: After seeing a vertical bar, looking for a second
	     vertical bar as a parallel expression separator.
#endif
#ifdef TC_PREDICATE_START_CHAR
	 14: After seeing a predicate start character at state 0, looking
	     for a predicate end character as predicate.
	 15: After seeing a predicate start character at state 1, looking
	     for a predicate end character as predicate.
#endif
#ifdef TC_Z80
	 16: After seeing an 'a' or an 'A' at the start of a symbol
	 17: After seeing an 'f' or an 'F' in state 16
#endif
	  */

  /* I added states 9 and 10 because the MIPS ECOFF assembler uses
     constructs like ``.loc 1 20''.  This was turning into ``.loc
     120''.  States 9 and 10 ensure that a space is never dropped in
     between characters which could appear in an identifier.  Ian
     Taylor, [email protected].

     I added state 11 so that something like "Lfoo add %r25,%r26,%r27" works
     correctly on the PA (and any other target where colons are optional).
     Jeff Law, [email protected].

     I added state 13 so that something like "cmp r1, r2 || trap #1" does not
     get squashed into "cmp r1,r2||trap#1", with the all important space
     between the 'trap' and the '#1' being eliminated.  [email protected]  */

  /* This macro gets the next input character.  */

#define GET()							\
  (from < fromend						\
   ? * (unsigned char *) (from++)				\
   : (saved_input = NULL,					\
      fromlen = (*get) (input_buffer, sizeof input_buffer),	\
      from = input_buffer,					\
      fromend = from + fromlen,					\
      (fromlen == 0						\
       ? EOF							\
       : * (unsigned char *) (from++))))

  /* This macro pushes a character back on the input stream.  */

#define UNGET(uch) (*--from = (uch))

  /* This macro puts a character into the output buffer.  If this
     character fills the output buffer, this macro jumps to the label
     TOFULL.  We use this rather ugly approach because we need to
     handle two different termination conditions: EOF on the input
     stream, and a full output buffer.  It would be simpler if we
     always read in the entire input stream before processing it, but
     I don't want to make such a significant change to the assembler's
     memory usage.  */

#define PUT(pch)				\
  do						\
    {						\
      *to++ = (pch);				\
      if (to >= toend)				\
	goto tofull;				\
    }						\
  while (0)

  if (saved_input != NULL)
    {
      from = saved_input;
      fromend = from + saved_input_len;
    }
  else
    {
      fromlen = (*get) (input_buffer, sizeof input_buffer);
      if (fromlen == 0)
	return 0;
      from = input_buffer;
      fromend = from + fromlen;
    }

  while (1)
    {
      /* The cases in this switch end with continue, in order to
	 branch back to the top of this while loop and generate the
	 next output character in the appropriate state.  */
      switch (state)
	{
	case -1:
	  ch = *out_string++;
	  if (*out_string == '\0')
	    {
	      state = old_state;
	      old_state = 3;
	    }
	  PUT (ch);
	  continue;

	case -2:
	  for (;;)
	    {
	      do
		{
		  ch = GET ();

		  if (ch == EOF)
		    {
		      as_warn (_("end of file in comment"));
		      goto fromeof;
		    }

		  if (ch == '\n')
		    PUT ('\n');
		}
	      while (ch != '*');

	      while ((ch = GET ()) == '*')
		;

	      if (ch == EOF)
		{
		  as_warn (_("end of file in comment"));
		  goto fromeof;
		}

	      if (ch == '/')
		break;

	      UNGET (ch);
	    }

	  state = old_state;
	  UNGET (' ');
	  continue;

	case 4:
	  ch = GET ();
	  if (ch == EOF)
	    goto fromeof;
	  else if (ch >= '0' && ch <= '9')
	    PUT (ch);
	  else
	    {
	      while (ch != EOF && IS_WHITESPACE (ch))
		ch = GET ();
	      if (ch == '"')
		{
		  quotechar = ch;
		  state = 5;
		  old_state = 3;
		  PUT (ch);
		}
	      else
		{
		  while (ch != EOF && ch != '\n')
		    ch = GET ();
		  state = 0;
		  PUT (ch);
		}
	    }
	  continue;

	case 5:
	  /* We are going to copy everything up to a quote character,
	     with special handling for a backslash.  We try to
	     optimize the copying in the simple case without using the
	     GET and PUT macros.  */
	  {
	    char *s;
	    ptrdiff_t len;

	    for (s = from; s < fromend; s++)
	      {
		ch = *s;
		if (ch == '\\'
		    || ch == quotechar
		    || ch == '\n')
		  break;
	      }
	    len = s - from;
	    if (len > toend - to)
	      len = toend - to;
	    if (len > 0)
	      {
		memcpy (to, from, len);
		to += len;
		from += len;
		if (to >= toend)
		  goto tofull;
	      }
	  }

	  ch = GET ();
	  if (ch == EOF)
	    {
	      /* This buffer is here specifically so
		 that the UNGET below will work.  */
	      static char one_char_buf[1];

	      as_warn (_("end of file in string; '%c' inserted"), quotechar);
	      state = old_state;
	      from = fromend = one_char_buf + 1;
	      fromlen = 1;
	      UNGET ('\n');
	      PUT (quotechar);
	    }
	  else if (ch == quotechar)
	    {
	      state = old_state;
	      PUT (ch);
	    }
#ifndef NO_STRING_ESCAPES
	  else if (ch == '\\')
	    {
	      state = 6;
	      PUT (ch);
	    }
#endif
	  else if (scrub_m68k_mri && ch == '\n')
	    {
	      /* Just quietly terminate the string.  This permits lines like
		   bne	label	loop if we haven't reach end yet.  */
	      state = old_state;
	      UNGET (ch);
	      PUT ('\'');
	    }
	  else
	    {
	      PUT (ch);
	    }
	  continue;

	case 6:
	  state = 5;
	  ch = GET ();
	  switch (ch)
	    {
	      /* Handle strings broken across lines, by turning '\n' into
		 '\\' and 'n'.  */
	    case '\n':
	      UNGET ('n');
	      add_newlines++;
	      PUT ('\\');
	      continue;

	    case EOF:
	      as_warn (_("end of file in string; '%c' inserted"), quotechar);
	      PUT (quotechar);
	      continue;

	    case '"':
	    case '\\':
	    case 'b':
	    case 'f':
	    case 'n':
	    case 'r':
	    case 't':
	    case 'v':
	    case 'x':
	    case 'X':
	    case '0':
	    case '1':
	    case '2':
	    case '3':
	    case '4':
	    case '5':
	    case '6':
	    case '7':
	      break;

	    default:
#ifdef ONLY_STANDARD_ESCAPES
	      as_warn (_("unknown escape '\\%c' in string; ignored"), ch);
#endif
	      break;
	    }
	  PUT (ch);
	  continue;

#ifdef DOUBLEBAR_PARALLEL
	case 13:
	  ch = GET ();
	  if (ch != '|')
	    abort ();

	  /* Reset back to state 1 and pretend that we are parsing a
	     line from just after the first white space.  */
	  state = 1;
	  PUT ('|');
#ifdef TC_TIC6X
	  /* "||^" is used for SPMASKed instructions.  */
	  ch = GET ();
	  if (ch == EOF)
	    goto fromeof;
	  else if (ch == '^')
	    PUT ('^');
	  else
	    UNGET (ch);
#endif
	  continue;
#endif
#ifdef TC_Z80
	case 16:
	  /* We have seen an 'a' at the start of a symbol, look for an 'f'.  */
	  ch = GET ();
	  if (ch == 'f' || ch == 'F')
	    {
	      state = 17;
	      PUT (ch);
	    }
	  else
	    {
	      state = 9;
	      break;
	    }
	case 17:
	  /* We have seen "af" at the start of a symbol,
	     a ' here is a part of that symbol.  */
	  ch = GET ();
	  state = 9;
	  if (ch == '\'')
	    /* Change to avoid warning about unclosed string.  */
	    PUT ('`');
	  else if (ch != EOF)
	    UNGET (ch);
	  break;
#endif
	}

      /* OK, we are somewhere in states 0 through 4 or 9 through 11.  */

      /* flushchar: */
      ch = GET ();

#ifdef TC_PREDICATE_START_CHAR
      if (ch == TC_PREDICATE_START_CHAR && (state == 0 || state == 1))
	{
	  state += 14;
	  PUT (ch);
	  continue;
	}
      else if (state == 14 || state == 15)
	{
	  if (ch == TC_PREDICATE_END_CHAR)
	    {
	      state -= 14;
	      PUT (ch);
	      ch = GET ();
	    }
	  else
	    {
	      PUT (ch);
	      continue;
	    }
	}
#endif

    recycle:

#if defined TC_ARM && defined OBJ_ELF
      /* We need to watch out for .symver directives.  See the comment later
	 in this function.  */
      if (symver_state == NULL)
	{
	  if ((state == 0 || state == 1) && ch == symver_pseudo[0])
	    symver_state = symver_pseudo + 1;
	}
      else
	{
	  /* We advance to the next state if we find the right
	     character.  */
	  if (ch != '\0' && (*symver_state == ch))
	    ++symver_state;
	  else if (*symver_state != '\0')
	    /* We did not get the expected character, or we didn't
	       get a valid terminating character after seeing the
	       entire pseudo-op, so we must go back to the beginning.  */
	    symver_state = NULL;
	  else
	    {
	      /* We've read the entire pseudo-op.  If this is the end
		 of the line, go back to the beginning.  */
	      if (IS_NEWLINE (ch))
		symver_state = NULL;
	    }
	}
#endif /* TC_ARM && OBJ_ELF */

#ifdef TC_M68K
      /* We want to have pseudo-ops which control whether we are in
	 MRI mode or not.  Unfortunately, since m68k MRI mode affects
	 the scrubber, that means that we need a special purpose
	 recognizer here.  */
      if (mri_state == NULL)
	{
	  if ((state == 0 || state == 1)
	      && ch == mri_pseudo[0])
	    mri_state = mri_pseudo + 1;
	}
      else
	{
	  /* We advance to the next state if we find the right
	     character, or if we need a space character and we get any
	     whitespace character, or if we need a '0' and we get a
	     '1' (this is so that we only need one state to handle
	     ``.mri 0'' and ``.mri 1'').  */
	  if (ch != '\0'
	      && (*mri_state == ch
		  || (*mri_state == ' '
		      && lex[ch] == LEX_IS_WHITESPACE)
		  || (*mri_state == '0'
		      && ch == '1')))
	    {
	      mri_last_ch = ch;
	      ++mri_state;
	    }
	  else if (*mri_state != '\0'
		   || (lex[ch] != LEX_IS_WHITESPACE
		       && lex[ch] != LEX_IS_NEWLINE))
	    {
	      /* We did not get the expected character, or we didn't
		 get a valid terminating character after seeing the
		 entire pseudo-op, so we must go back to the
		 beginning.  */
	      mri_state = NULL;
	    }
	  else
	    {
	      /* We've read the entire pseudo-op.  mips_last_ch is
		 either '0' or '1' indicating whether to enter or
		 leave MRI mode.  */
	      do_scrub_begin (mri_last_ch == '1');
	      mri_state = NULL;

	      /* We continue handling the character as usual.  The
		 main gas reader must also handle the .mri pseudo-op
		 to control expression parsing and the like.  */
	    }
	}
#endif

      if (ch == EOF)
	{
	  if (state != 0)
	    {
	      as_warn (_("end of file not at end of a line; newline inserted"));
	      state = 0;
	      PUT ('\n');
	    }
	  goto fromeof;
	}

      switch (lex[ch])
	{
	case LEX_IS_WHITESPACE:
	  do
	    {
	      ch = GET ();
	    }
	  while (ch != EOF && IS_WHITESPACE (ch));
	  if (ch == EOF)
	    goto fromeof;

	  if (state == 0)
	    {
	      /* Preserve a single whitespace character at the
		 beginning of a line.  */
	      state = 1;
	      UNGET (ch);
	      PUT (' ');
	      break;
	    }

#ifdef KEEP_WHITE_AROUND_COLON
	  if (lex[ch] == LEX_IS_COLON)
	    {
	      /* Only keep this white if there's no white *after* the
		 colon.  */
	      ch2 = GET ();
	      if (ch2 != EOF)
		UNGET (ch2);
	      if (!IS_WHITESPACE (ch2))
		{
		  state = 9;
		  UNGET (ch);
		  PUT (' ');
		  break;
		}
	    }
#endif
	  if (IS_COMMENT (ch)
	      || ch == '/'
	      || IS_LINE_SEPARATOR (ch)
	      || IS_PARALLEL_SEPARATOR (ch))
	    {
	      if (scrub_m68k_mri)
		{
		  /* In MRI mode, we keep these spaces.  */
		  UNGET (ch);
		  PUT (' ');
		  break;
		}
	      goto recycle;
	    }

	  /* If we're in state 2 or 11, we've seen a non-white
	     character followed by whitespace.  If the next character
	     is ':', this is whitespace after a label name which we
	     normally must ignore.  In MRI mode, though, spaces are
	     not permitted between the label and the colon.  */
	  if ((state == 2 || state == 11)
	      && lex[ch] == LEX_IS_COLON
	      && ! scrub_m68k_mri)
	    {
	      state = 1;
	      PUT (ch);
	      break;
	    }

	  switch (state)
	    {
	    case 1:
	      /* We can arrive here if we leave a leading whitespace
		 character at the beginning of a line.  */
	      goto recycle;
	    case 2:
	      state = 3;
	      if (to + 1 < toend)
		{
		  /* Optimize common case by skipping UNGET/GET.  */
		  PUT (' ');	/* Sp after opco */
		  goto recycle;
		}
	      UNGET (ch);
	      PUT (' ');
	      break;
	    case 3:
#ifndef TC_KEEP_OPERAND_SPACES
	      /* For TI C6X, we keep these spaces as they may separate
		 functional unit specifiers from operands.  */
	      if (scrub_m68k_mri)
#endif
		{
		  /* In MRI mode, we keep these spaces.  */
		  UNGET (ch);
		  PUT (' ');
		  break;
		}
	      goto recycle;	/* Sp in operands */
	    case 9:
	    case 10:
#ifndef TC_KEEP_OPERAND_SPACES
	      if (scrub_m68k_mri)
#endif
		{
		  /* In MRI mode, we keep these spaces.  */
		  state = 3;
		  UNGET (ch);
		  PUT (' ');
		  break;
		}
	      state = 10;	/* Sp after symbol char */
	      goto recycle;
	    case 11:
	      if (LABELS_WITHOUT_COLONS || flag_m68k_mri)
		state = 1;
	      else
		{
		  /* We know that ch is not ':', since we tested that
		     case above.  Therefore this is not a label, so it
		     must be the opcode, and we've just seen the
		     whitespace after it.  */
		  state = 3;
		}
	      UNGET (ch);
	      PUT (' ');	/* Sp after label definition.  */
	      break;
	    default:
	      BAD_CASE (state);
	    }
	  break;

	case LEX_IS_TWOCHAR_COMMENT_1ST:
	  ch2 = GET ();
	  if (ch2 == '*')
	    {
	      for (;;)
		{
		  do
		    {
		      ch2 = GET ();
		      if (ch2 != EOF && IS_NEWLINE (ch2))
			add_newlines++;
		    }
		  while (ch2 != EOF && ch2 != '*');

		  while (ch2 == '*')
		    ch2 = GET ();

		  if (ch2 == EOF || ch2 == '/')
		    break;

		  /* This UNGET will ensure that we count newlines
		     correctly.  */
		  UNGET (ch2);
		}

	      if (ch2 == EOF)
		as_warn (_("end of file in multiline comment"));

	      ch = ' ';
	      goto recycle;
	    }
#ifdef DOUBLESLASH_LINE_COMMENTS
	  else if (ch2 == '/')
	    {
	      do
		{
		  ch = GET ();
		}
	      while (ch != EOF && !IS_NEWLINE (ch));
	      if (ch == EOF)
		as_warn ("end of file in comment; newline inserted");
	      state = 0;
	      PUT ('\n');
	      break;
	    }
#endif
	  else
	    {
	      if (ch2 != EOF)
		UNGET (ch2);
	      if (state == 9 || state == 10)
		state = 3;
	      PUT (ch);
	    }
	  break;

	case LEX_IS_STRINGQUOTE:
	  quotechar = ch;
	  if (state == 10)
	    {
	      /* Preserve the whitespace in foo "bar".  */
	      UNGET (ch);
	      state = 3;
	      PUT (' ');

	      /* PUT didn't jump out.  We could just break, but we
		 know what will happen, so optimize a bit.  */
	      ch = GET ();
	      old_state = 3;
	    }
	  else if (state == 9)
	    old_state = 3;
	  else
	    old_state = state;
	  state = 5;
	  PUT (ch);
	  break;

#ifndef IEEE_STYLE
	case LEX_IS_ONECHAR_QUOTE:
#ifdef H_TICK_HEX
	  if (state == 9 && enable_h_tick_hex)
	    {
	      char c;

	      c = GET ();
	      as_warn ("'%c found after symbol", c);
	      UNGET (c);
	    }
#endif
	  if (state == 10)
	    {
	      /* Preserve the whitespace in foo 'b'.  */
	      UNGET (ch);
	      state = 3;
	      PUT (' ');
	      break;
	    }
	  ch = GET ();
	  if (ch == EOF)
	    {
	      as_warn (_("end of file after a one-character quote; \\0 inserted"));
	      ch = 0;
	    }
	  if (ch == '\\')
	    {
	      ch = GET ();
	      if (ch == EOF)
		{
		  as_warn (_("end of file in escape character"));
		  ch = '\\';
		}
	      else
		ch = process_escape (ch);
	    }
	  sprintf (out_buf, "%d", (int) (unsigned char) ch);

	  /* None of these 'x constants for us.  We want 'x'.  */
	  if ((ch = GET ()) != '\'')
	    {
#ifdef REQUIRE_CHAR_CLOSE_QUOTE
	      as_warn (_("missing close quote; (assumed)"));
#else
	      if (ch != EOF)
		UNGET (ch);
#endif
	    }
	  if (strlen (out_buf) == 1)
	    {
	      PUT (out_buf[0]);
	      break;
	    }
	  if (state == 9)
	    old_state = 3;
	  else
	    old_state = state;
	  state = -1;
	  out_string = out_buf;
	  PUT (*out_string++);
	  break;
#endif

	case LEX_IS_COLON:
#ifdef KEEP_WHITE_AROUND_COLON
	  state = 9;
#else
	  if (state == 9 || state == 10)
	    state = 3;
	  else if (state != 3)
	    state = 1;
#endif
	  PUT (ch);
	  break;

	case LEX_IS_NEWLINE:
	  /* Roll out a bunch of newlines from inside comments, etc.  */
	  if (add_newlines)
	    {
	      --add_newlines;
	      UNGET (ch);
	    }
	  /* Fall through.  */

	case LEX_IS_LINE_SEPARATOR:
	  state = 0;
	  PUT (ch);
	  break;

	case LEX_IS_PARALLEL_SEPARATOR:
	  state = 1;
	  PUT (ch);
	  break;

#ifdef TC_V850
	case LEX_IS_DOUBLEDASH_1ST:
	  ch2 = GET ();
	  if (ch2 != '-')
	    {
	      if (ch2 != EOF)
		UNGET (ch2);
	      goto de_fault;
	    }
	  /* Read and skip to end of line.  */
	  do
	    {
	      ch = GET ();
	    }
	  while (ch != EOF && ch != '\n');

	  if (ch == EOF)
	    as_warn (_("end of file in comment; newline inserted"));

	  state = 0;
	  PUT ('\n');
	  break;
#endif
#ifdef DOUBLEBAR_PARALLEL
	case LEX_IS_DOUBLEBAR_1ST:
	  ch2 = GET ();
	  if (ch2 != EOF)
	    UNGET (ch2);
	  if (ch2 != '|')
	    goto de_fault;

	  /* Handle '||' in two states as invoking PUT twice might
	     result in the first one jumping out of this loop.  We'd
	     then lose track of the state and one '|' char.  */
	  state = 13;
	  PUT ('|');
	  break;
#endif
	case LEX_IS_LINE_COMMENT_START:
	  /* FIXME-someday: The two character comment stuff was badly
	     thought out.  On i386, we want '/' as line comment start
	     AND we want C style comments.  hence this hack.  The
	     whole lexical process should be reworked.  xoxorich.  */
	  if (ch == '/')
	    {
	      ch2 = GET ();
	      if (ch2 == '*')
		{
		  old_state = 3;
		  state = -2;
		  break;
		}
	      else
		{
		  UNGET (ch2);
		}
	    }

	  if (state == 0 || state == 1)	/* Only comment at start of line.  */
	    {
	      int startch;

	      startch = ch;

	      do
		{
		  ch = GET ();
		}
	      while (ch != EOF && IS_WHITESPACE (ch));

	      if (ch == EOF)
		{
		  as_warn (_("end of file in comment; newline inserted"));
		  PUT ('\n');
		  break;
		}

	      if (ch < '0' || ch > '9' || state != 0 || startch != '#')
		{
		  /* Not a cpp line.  */
		  while (ch != EOF && !IS_NEWLINE (ch))
		    ch = GET ();
		  if (ch == EOF)
		    {
		      as_warn (_("end of file in comment; newline inserted"));
		      PUT ('\n');
		    }
		  else /* IS_NEWLINE (ch) */
		    {
		      /* To process non-zero add_newlines.  */
		      UNGET (ch);
		    }
		  state = 0;
		  break;
		}
	      /* Looks like `# 123 "filename"' from cpp.  */
	      UNGET (ch);
	      old_state = 4;
	      state = -1;
	      if (scrub_m68k_mri)
		out_string = "\tlinefile ";
	      else
		out_string = "\t.linefile ";
	      PUT (*out_string++);
	      break;
	    }

#ifdef TC_D10V
	  /* All insns end in a char for which LEX_IS_SYMBOL_COMPONENT is true.
	     Trap is the only short insn that has a first operand that is
	     neither register nor label.
	     We must prevent exef0f ||trap #1 to degenerate to exef0f ||trap#1 .
	     We can't make '#' LEX_IS_SYMBOL_COMPONENT because it is
	     already LEX_IS_LINE_COMMENT_START.  However, it is the
	     only character in line_comment_chars for d10v, hence we
	     can recognize it as such.  */
	  /* An alternative approach would be to reset the state to 1 when
	     we see '||', '<'- or '->', but that seems to be overkill.  */
	  if (state == 10)
	    PUT (' ');
#endif
	  /* We have a line comment character which is not at the
	     start of a line.  If this is also a normal comment
	     character, fall through.  Otherwise treat it as a default
	     character.  */
	  if (strchr (tc_comment_chars, ch) == NULL
	      && (! scrub_m68k_mri
		  || (ch != '!' && ch != '*')))
	    goto de_fault;
	  if (scrub_m68k_mri
	      && (ch == '!' || ch == '*' || ch == '#')
	      && state != 1
	      && state != 10)
	    goto de_fault;
	  /* Fall through.  */
	case LEX_IS_COMMENT_START:
#if defined TC_ARM && defined OBJ_ELF
	  /* On the ARM, `@' is the comment character.
	     Unfortunately this is also a special character in ELF .symver
	     directives (and .type, though we deal with those another way).
	     So we check if this line is such a directive, and treat
	     the character as default if so.  This is a hack.  */
	  if ((symver_state != NULL) && (*symver_state == 0))
	    goto de_fault;
#endif

#ifdef TC_ARM
	  /* For the ARM, care is needed not to damage occurrences of \@
	     by stripping the @ onwards.  Yuck.  */
	  if (to > tostart && *(to - 1) == '\\')
	    /* Do not treat the @ as a start-of-comment.  */
	    goto de_fault;
#endif

#ifdef WARN_COMMENTS
	  if (!found_comment)
	    as_where (&found_comment_file, &found_comment);
#endif
	  do
	    {
	      ch = GET ();
	    }
	  while (ch != EOF && !IS_NEWLINE (ch));
	  if (ch == EOF)
	    as_warn (_("end of file in comment; newline inserted"));
	  state = 0;
	  PUT ('\n');
	  break;

#ifdef H_TICK_HEX
	case LEX_IS_H:
	  /* Look for strings like H'[0-9A-Fa-f] and if found, replace
	     the H' with 0x to make them gas-style hex characters.  */
	  if (enable_h_tick_hex)
	    {
	      char quot;

	      quot = GET ();
	      if (quot == '\'')
		{
		  UNGET ('x');
		  ch = '0';
		}
	      else
		UNGET (quot);
	    }
	  /* FALL THROUGH */
#endif

	case LEX_IS_SYMBOL_COMPONENT:
	  if (state == 10)
	    {
	      /* This is a symbol character following another symbol
		 character, with whitespace in between.  We skipped
		 the whitespace earlier, so output it now.  */
	      UNGET (ch);
	      state = 3;
	      PUT (' ');
	      break;
	    }

#ifdef TC_Z80
	  /* "af'" is a symbol containing '\''.  */
	  if (state == 3 && (ch == 'a' || ch == 'A'))
	    {
	      state = 16;
	      PUT (ch);
	      ch = GET ();
	      if (ch == 'f' || ch == 'F')
		{
		  state = 17;
		  PUT (ch);
		  break;
		}
	      else
		{
		  state = 9;
		  if (ch == EOF || !IS_SYMBOL_COMPONENT (ch))
		    {
		      if (ch != EOF)
			UNGET (ch);
		      break;
		    }
		}
	    }
#endif
	  if (state == 3)
	    state = 9;

	  /* This is a common case.  Quickly copy CH and all the
	     following symbol component or normal characters.  */
	  if (to + 1 < toend
	      && mri_state == NULL
#if defined TC_ARM && defined OBJ_ELF
	      && symver_state == NULL
#endif
	      )
	    {
	      char *s;
	      ptrdiff_t len;

	      for (s = from; s < fromend; s++)
		{
		  int type;

		  ch2 = *(unsigned char *) s;
		  type = lex[ch2];
		  if (type != 0
		      && type != LEX_IS_SYMBOL_COMPONENT)
		    break;
		}

	      if (s > from)
		/* Handle the last character normally, for
		   simplicity.  */
		--s;

	      len = s - from;

	      if (len > (toend - to) - 1)
		len = (toend - to) - 1;

	      if (len > 0)
		{
		  PUT (ch);
		  memcpy (to, from, len);
		  to += len;
		  from += len;
		  if (to >= toend)
		    goto tofull;
		  ch = GET ();
		}
	    }

	  /* Fall through.  */
	default:
	de_fault:
	  /* Some relatively `normal' character.  */
	  if (state == 0)
	    {
	      state = 11;	/* Now seeing label definition.  */
	    }
	  else if (state == 1)
	    {
	      state = 2;	/* Ditto.  */
	    }
	  else if (state == 9)
	    {
	      if (!IS_SYMBOL_COMPONENT (ch))
		state = 3;
	    }
	  else if (state == 10)
	    {
	      if (ch == '\\')
		{
		  /* Special handling for backslash: a backslash may
		     be the beginning of a formal parameter (of a
		     macro) following another symbol character, with
		     whitespace in between.  If that is the case, we
		     output a space before the parameter.  Strictly
		     speaking, correct handling depends upon what the
		     macro parameter expands into; if the parameter
		     expands into something which does not start with
		     an operand character, then we don't want to keep
		     the space.  We don't have enough information to
		     make the right choice, so here we are making the
		     choice which is more likely to be correct.  */
		  if (to + 1 >= toend)
		    {
		      /* If we're near the end of the buffer, save the
		         character for the next time round.  Otherwise
		         we'll lose our state.  */
		      UNGET (ch);
		      goto tofull;
		    }
		  *to++ = ' ';
		}

	      state = 3;
	    }
	  PUT (ch);
	  break;
	}
    }

  /*NOTREACHED*/

 fromeof:
  /* We have reached the end of the input.  */
  return to - tostart;

 tofull:
  /* The output buffer is full.  Save any input we have not yet
     processed.  */
  if (fromend > from)
    {
      saved_input = from;
      saved_input_len = fromend - from;
    }
  else
    saved_input = NULL;

  return to - tostart;
}
예제 #22
0
파일: mm3.c 프로젝트: ZHAOTING/ICS-lab
/*
 * malloc
 */
void *malloc (size_t size) 
{
    // mm_checkheap(2);

    int cur_index = 0;
    size_t asize;
    unsigned long mhi = (unsigned long)mem_heap_hi();

    // calculate aligned and minimum size
    if (size == 0)
        return 0;
    if (size < 2 * HSIZE)
        asize = EXTRA;
    else
        asize = WSIZE * ((size + (WSIZE - 1)) / WSIZE) + 2 * HSIZE;

    // find class of suitable size
    // cur_index = find_class(asize);

    // search free block in different lists for appropriate free block
    char *free_blk = 0;
    while (cur_index < CLASSES_NUM)
    {
        free_blk = REAL_ADDR((char *)GET(heap_listp + cur_index * HSIZE));
        // search appropriate free block in cur_index list

        while (free_blk != (char *)base_addr)
        {
            size_t free_blk_size = GET_SIZE(HDRP(free_blk));

            // if free_blk is too small, and it's not the last block in heap
            // ---- see next block
            if (free_blk_size < asize && (unsigned long)NEXT_BLKP(free_blk) < mhi)
            {
                free_blk = REAL_ADDR((char *)GET(SUCC(free_blk)));
                continue;
            }

            // if free_blk is too small, but it's the last block in heap
            // ---- then we can just expand this free_blk to asize and choose it
            else if (free_blk_size < asize)
            {
                // Destroy its relationship with other block, make it independent
                // So that it'll be convenient to use this free block
                destroy_relationship(free_blk);

                // get the size we want to expand
                size_t delta = asize - free_blk_size;
                if (mem_sbrk(delta) == (void *)-1)
                    return NULL;
            }

            // if free_blk is big enough to split
            // ---- split it
            else if (free_blk_size - asize >= 5 * HSIZE)
            {
                // Destroy its relationship with other block, make it independent
                // So that it'll be convenient to insert new free block
                destroy_relationship(free_blk);

                // I'M SURE new_blk_size IS ALIGNED TO WSIZE
                size_t new_blk_size = free_blk_size - asize;
                // we do spliting here!
                char *new_blk = free_blk + asize;
                insert(new_blk, new_blk_size);
            }
            // if free_blk is not big enough to split
            // ---- use the entire free block (that is free_blk)
            else
            {
                // Destroy its relationship with other block, make it independent
                // So that it'll be convenient to use this free block
                destroy_relationship(free_blk);

                asize = free_blk_size;
            }

            // turns free block into allocated block
            PUT(HDRP(free_blk), PACK(asize, 1));
            PUT(FTRP(free_blk), PACK(asize, 1));
            PUT(PRED(free_blk), 0);
            PUT(SUCC(free_blk), 0);
            char *alloc_blk = free_blk;

            // found and return
            return (void *)((unsigned long)alloc_blk - 2 * HSIZE);
        }
        cur_index++;
    }

    // found no appropriate free block, we need to mem_sbrk
    if (free_blk == (char *)base_addr)
    {
        char *new_blk = 0;

        if ((new_blk = mem_sbrk(asize)) == (void *)-1)
            return 0;

        new_blk += (3 * HSIZE);
        PUT(HDRP(new_blk), PACK(asize, 1));
        PUT(FTRP(new_blk), PACK(asize, 1));
        PUT(PRED(new_blk), 0);
        PUT(SUCC(new_blk), 0);

        return (void *)((unsigned long)new_blk - 2 * HSIZE);
    }

    // never reach here
    return NULL;
}
예제 #23
0
static void merge_case(void *current_block,int state)
{
//	dbg_printf("merge_case\n");
	void *prev_block = PREV_BLKP(current_block);
	void *next_block = NEXT_BLKP(current_block);
	int prev_size = GET_SIZE(HDRP(prev_block));
	int next_size = GET_SIZE(HDRP(next_block));
	int current_size = GET_SIZE(HDRP(current_block));
	switch ( state )
	{
	case 1://AXA
		{	//no correct	
//			dbg_printf("case1 : AXA\n");
//			dbg_printf("init : %d\n",init);
			int a;
			if ( init == NULL )
			{
				
				PUT(FLPB(current_block),&init);
				PUT(FLSB(current_block),init);
			}
			else
			{
				//v = init;
//				dbg_printf("else\n");
			//	print(init);
//				dbg_printf("\n");
				next_block = init;
				if ( next_block != NULL )
				{
//					dbg_printf("treu");
					PUT(FLSB(current_block),next_block);
					PUT(FLPB(next_block),current_block);
				
				}
				else
					PUT(FLSB(current_block),NULL);
				PUT(FLPB(current_block),&init);
//				dbg_printf("else end\n");
				a = 10;
			}
			free_count++;
			init = current_block;
			if ( a == 10 )
			//	print(init);
			
			return ;
		}
	case 2://AXF
		{
//			dbg_printf("case2 : AXF\n");
			PUT(HDRP(current_block),PACK(next_size+current_size,0));
			PUT(FTRP(next_block),PACK(next_size+current_size,0));
			return ;
		}
	case 3://FXA
		{	//no correct
//			dbg_printf("case3 : FXA\n");
			PUT(HDRP(prev_block),PACK(prev_size+current_size,0));
			PUT(FTRP(current_block),PACK(prev_size+current_size,0));
			return ;
		}
	case 4://FXF
		{
//			dbg_printf("case4 : FXF\n");
			PUT(HDRP(prev_block),PACK(prev_size+current_size+next_size,0));
			PUT(FTRP(next_block),PACK(prev_size+current_size+next_size,0));
			free_count--;
			free_sort();
			return ;
		}
	}
}
예제 #24
0
파일: asm.c 프로젝트: forestbelton/tenyr
int print_disassembly(FILE *out, struct instruction *i, int flags)
{
    if (flags & ASM_AS_DATA)
        return fprintf(out, ".word 0x%08x", i->u.word);

    if (flags & ASM_AS_CHAR) {
        char buf[10];
        if (is_printable(i->u.word, sizeof buf, buf))
            return fprintf(out, ".word '%s'%*s", buf, (int)(2 - strlen(buf)), "");
        else
            return fprintf(out, "          ");
    }

    int type = i->u._xxxx.t;
    switch (type) {
        default:
            if (i->u.word == 0xffffffff)
                return fprintf(out, "illegal");
            else
                return fprintf(out, ".word 0x%08x", i->u.word);

        case 0x0:
        case 0x1:
        case 0x2:
        case 0x3:
        case 0x4:
        case 0x5:
        case 0x6:
        case 0x7:
            break;
    }

    struct instruction_general *g = &i->u._0xxx;

    if (!op_meta[g->op].valid)   // reserved
        return fprintf(out, ".word 0x%08x", i->u.word);

    int rd = g->dd &  1;
    int ld = g->dd == 2;

    // LHS
          char    f0 = ld ? '[' : ' ';        // left side dereferenced ?
          char    f1 = 'A' + g->z;            // register name for Z
          char    f2 = ld ? ']' : ' ';        // left side dereferenced ?

    // arrow
    const char   *f3 = (g->dd == 3) ? "->" : "<-";    // arrow direction

    // RHS
          char    f4 = rd ? '[' : ' ';        // right side dereferenced ?
          char    f5 = 'A' + g->x;            // register name for X
    const char   *f6 = op_meta[g->op].name;   // operator name
          char    f7 = 'A' + g->y;            // register name for Y
          int32_t f8 = SEXTEND(12,g->imm);    // immediate value, sign-extended
          char    f9 = rd ? ']' : ' ';        // right side dereferenced ?

    int hex   = op_meta[g->op].hex;
    int inert = op_meta[g->op].inert;
    int opXA  = g->x == 0;
    int opYA  = g->y == 0;
    int op3   = g->p ? !opYA : (!!g->imm);
    int op2   = !inert || (g->p ? (g->imm || opYA) : !opYA);
    int op1   = !(opXA && inert) || (!op2 && !op3);
    int kind  = !!g->p;

    if (flags & ASM_VERBOSE)
        op1 = op2 = op3 = hex = 1;

    if (!(flags & (ASM_NO_SUGAR | ASM_VERBOSE))) {
        if (g->op == OP_BITWISE_XORN && g->y == 0) {
            f7 = f5;    // Y slot is now X
            f5 = ' ';   // don't print X
            f6 = "~";   // change op to a unary not
        } else if (g->op == OP_SUBTRACT && g->x == 0) {
            f5 = ' ';   // don't print X
        }
    }

    #define C_(E,D,C,B,A) (((E) << 4) | ((D) << 3) | ((C) << 2) | ((B) << 1) | (A))
    // We'd like to use positional references in these format strings, but to
    // preserve compatibility with Win32 libc, we don't.
    // indices : hex, g->p, op1, op2, op3
    static const char *fmts[C_(1,1,1,1,1)+1] = {
      //[C_(0,0,0,0,0)] = "%c%c%c %s %c"                   "%c", // [Z] <- [           ]
        [C_(0,0,0,0,1)] = "%c%c%c %s %c"              "%-10d%c", // [Z] <- [         -0]
        [C_(0,0,0,1,0)] = "%c%c%c %s %c"         "%c"      "%c", // [Z] <- [    Y      ]
        [C_(0,0,0,1,1)] = "%c%c%c %s %c"         "%c + %-10d%c", // [Z] <- [    Y +  -0]
        [C_(0,0,1,0,0)] = "%c%c%c %s %c%c"                 "%c", // [Z] <- [X          ]
        [C_(0,0,1,0,1)] = "%c%c%c %s %c%c"         " + %-10d%c", // [Z] <- [X     +  -0]
        [C_(0,0,1,1,0)] = "%c%c%c %s %c%c %-2s " "%c"      "%c", // [Z] <- [X - Y      ]
        [C_(0,0,1,1,1)] = "%c%c%c %s %c%c %-2s " "%c + %-10d%c", // [Z] <- [X - Y +  -0]
      //[C_(0,1,0,0,0)] = "%c%c%c %s %c"                   "%c", // [Z] <- [           ]
        [C_(0,1,0,0,1)] = "%c%c%c %s %c"                 "%c%c", // [Z] <- [          Y]
        [C_(0,1,0,1,0)] = "%c%c%c %s %c"        " %-10d"   "%c", // [Z] <- [     -0    ]
        [C_(0,1,0,1,1)] = "%c%c%c %s %c"        " %-10d + %c%c", // [Z] <- [     -0 + Y]
        [C_(0,1,1,0,0)] = "%c%c%c %s %c%c"                 "%c", // [Z] <- [X          ]
        [C_(0,1,1,0,1)] = "%c%c%c %s %c%c"            " + %c%c", // [Z] <- [X       + Y]
        [C_(0,1,1,1,0)] = "%c%c%c %s %c%c %-2s " "%-10d"   "%c", // [Z] <- [X -  -0    ]
        [C_(0,1,1,1,1)] = "%c%c%c %s %c%c %-2s " "%-10d + %c%c", // [Z] <- [X -  -0 + Y]
      //[C_(1,0,0,0,0)] = "%c%c%c %s %c"                   "%c", // [Z] <- [           ]
        [C_(1,0,0,0,1)] = "%c%c%c %s %c"             "0x%08x%c", // [Z] <- [        0x0]
        [C_(1,0,0,1,0)] = "%c%c%c %s %c"        "%c"       "%c", // [Z] <- [    Y      ]
        [C_(1,0,0,1,1)] = "%c%c%c %s %c"        "%c + 0x%08x%c", // [Z] <- [    Y + 0x0]
        [C_(1,0,1,0,0)] = "%c%c%c %s %c%c"                 "%c", // [Z] <- [X          ]
        [C_(1,0,1,0,1)] = "%c%c%c %s %c%c"        " + 0x%08x%c", // [Z] <- [X     + 0x0]
        [C_(1,0,1,1,0)] = "%c%c%c %s %c%c %-2s ""%c"       "%c", // [Z] <- [X - Y      ]
        [C_(1,0,1,1,1)] = "%c%c%c %s %c%c %-2s ""%c + 0x%08x%c", // [Z] <- [X - Y + 0x0]
      //[C_(1,1,0,0,0)] = "%c%c%c %s %c"                   "%c", // [Z] <- [           ]
        [C_(1,1,0,0,1)] = "%c%c%c %s %c"                 "%c%c", // [Z] <- [          Y]
        [C_(1,1,0,1,0)] = "%c%c%c %s %c"        "0x%08x"   "%c", // [Z] <- [    0x0    ]
        [C_(1,1,0,1,1)] = "%c%c%c %s %c"        "0x%08x + %c%c", // [Z] <- [    0x0 + Y]
        [C_(1,1,1,0,0)] = "%c%c%c %s %c%c"                 "%c", // [Z] <- [X          ]
        [C_(1,1,1,0,1)] = "%c%c%c %s %c%c"            " + %c%c", // [Z] <- [X       + Y]
        [C_(1,1,1,1,0)] = "%c%c%c %s %c%c %-2s ""0x%08x"   "%c", // [Z] <- [X - 0x0    ]
        [C_(1,1,1,1,1)] = "%c%c%c %s %c%c %-2s ""0x%08x + %c%c", // [Z] <- [X - 0x0 + Y]
    };

    #define PUT(...) return fprintf(out, fmts[C_(hex,kind,op1,op2,op3)], __VA_ARGS__)
    switch (C_(0,kind,op1,op2,op3)) {
      //case C_(0,0,0,0,0): PUT(f0,f1,f2,f3,f4,            f9); break;
        case C_(0,0,0,0,1): PUT(f0,f1,f2,f3,f4,         f8,f9); break;
        case C_(0,0,0,1,0): PUT(f0,f1,f2,f3,f4,      f7,   f9); break;
        case C_(0,0,0,1,1): PUT(f0,f1,f2,f3,f4,      f7,f8,f9); break;
        case C_(0,0,1,0,0): PUT(f0,f1,f2,f3,f4,f5,         f9); break;
        case C_(0,0,1,0,1): PUT(f0,f1,f2,f3,f4,f5,      f8,f9); break;
        case C_(0,0,1,1,0): PUT(f0,f1,f2,f3,f4,f5,f6,f7,   f9); break;
        case C_(0,0,1,1,1): PUT(f0,f1,f2,f3,f4,f5,f6,f7,f8,f9); break;
      //case C_(0,1,0,0,0): PUT(f0,f1,f2,f3,f4,            f9); break;
        case C_(0,1,0,0,1): PUT(f0,f1,f2,f3,f4,         f7,f9); break;
        case C_(0,1,0,1,0): PUT(f0,f1,f2,f3,f4,      f8,   f9); break;
        case C_(0,1,0,1,1): PUT(f0,f1,f2,f3,f4,      f8,f7,f9); break;
        case C_(0,1,1,0,0): PUT(f0,f1,f2,f3,f4,f5,         f9); break;
        case C_(0,1,1,0,1): PUT(f0,f1,f2,f3,f4,f5,      f7,f9); break;
        case C_(0,1,1,1,0): PUT(f0,f1,f2,f3,f4,f5,f6,f8,   f9); break;
        case C_(0,1,1,1,1): PUT(f0,f1,f2,f3,f4,f5,f6,f8,f7,f9); break;

        default:
            fatal(0, "Unsupported hex,kind,op1,op2,op3 %d,%d,%d,%d,%d",
                    hex,g->p,op1,op2,op3);
    }
}
예제 #25
0
/* 
 * coalesce - boundary tag coalescing. return ptr to coalesced block
 *
 */
static void* coalesce(void* bp) {

	size_t prev_alloc = GET_PREV_ALLOC(HDRP(bp));
	size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp)));
	size_t size = GET_SIZE(HDRP(bp));

	dbg1("[IN ] : coalesce()\n");

	switch (prev_alloc | next_alloc)
	{
		case 3:
			/* neither of the adjacent blocks are free */
			insert_free_block(bp);
			dbg1("[OUT] : coalesce() : neither of the adjacent blocks are free.\n");
			return bp;
		case 2:
			/* next block is free */
			size += GET_SIZE(HDRP(NEXT_BLKP(bp)));

			/* remove next block from free list */
			remove_free_block(NEXT_BLKP(bp));

			/* update header and footer pointers */
			PUT(HDRP(bp), PACK(size, prev_alloc));
			PUT(FTRP(bp), PACK(size, prev_alloc));

			/* insert new merged block into free list */
			insert_free_block(bp);
			dbg1("[OUT] : coalesce() : next block is free - merged \n");
			return(bp);
		case 1:
			/* prev block is free */
			size += GET_SIZE(HDRP(PREV_BLKP(bp)));

			/* remove this block from free list */
			remove_free_block(PREV_BLKP(bp));

			/* update header and footer pointers */
			prev_alloc = GET_PREV_ALLOC(HDRP(PREV_BLKP(bp)));
			PUT(FTRP(bp), PACK(size, prev_alloc));
			PUT(HDRP(PREV_BLKP(bp)), PACK(size, prev_alloc));

			/* insert new merged block into free list */
			insert_free_block(PREV_BLKP(bp));
			dbg1("[OUT] : coalesce() : previous block is free - merged \n");
			return(PREV_BLKP(bp));
		default:
			/* both previous and next blocks are free */
			size += GET_SIZE(HDRP(PREV_BLKP(bp))) + GET_SIZE(FTRP(NEXT_BLKP(bp)));

			/* remove next block from free list */
			remove_free_block(NEXT_BLKP(bp));

			/* remove this block from free list */
			remove_free_block(PREV_BLKP(bp));

			/* update header and footer pointers */
			prev_alloc = GET_PREV_ALLOC(HDRP(PREV_BLKP(bp)));
			PUT(HDRP(PREV_BLKP(bp)), PACK(size, prev_alloc));
			PUT(FTRP(NEXT_BLKP(bp)), PACK(size, prev_alloc));

			/* insert new merged block into free list */
			insert_free_block(PREV_BLKP(bp));

			dbg1("[OUT] : coalesce() : both previous and next blocks are free - merged \n");
			
			return(PREV_BLKP(bp));
	}
}
예제 #26
0
/*
 * java: read java file and pickup tag entries.
 */
void
java(const struct parser_param *param)
{
	int c;
	int level;					/* brace level */
	int startclass, startthrows, startequal;
	char classname[MAXTOKEN];
	char completename[MAXCOMPLETENAME];
	int classlevel;
	struct {
		char *classname;
		char *terminate;
		int level;
	} stack[MAXCLASSSTACK];
	const char *interested = "{}=;";

	*classname = *completename = 0;
	stack[0].classname = completename;
	stack[0].terminate = completename;
	stack[0].level = 0;
	level = classlevel = 0;
	startclass = startthrows = startequal = 0;

	if (!opentoken(param->file))
		die("'%s' cannot open.", param->file);
	while ((c = nexttoken(interested, java_reserved_word)) != EOF) {
		switch (c) {
		case SYMBOL:					/* symbol */
			for (; c == SYMBOL && peekc(1) == '.'; c = nexttoken(interested, java_reserved_word)) {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			}
			if (c != SYMBOL)
				break;
			if (startclass || startthrows) {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			} else if (peekc(0) == '('/* ) */) {
				if (level == stack[classlevel].level && !startequal)
					/* ignore constructor */
					if (strcmp(stack[classlevel].classname, token))
						PUT(PARSER_DEF, token, lineno, sp);
				if (level > stack[classlevel].level || startequal)
					PUT(PARSER_REF_SYM, token, lineno, sp);
			} else {
				PUT(PARSER_REF_SYM, token, lineno, sp);
			}
			break;
		case '{': /* } */
			DBG_PRINT(level, "{");	/* } */

			++level;
			if (startclass) {
				char *p = stack[classlevel].terminate;
				char *q = classname;

				if (++classlevel >= MAXCLASSSTACK)
					die("class stack over flow.[%s]", curfile);
				if (classlevel > 1)
					*p++ = '.';
				stack[classlevel].classname = p;
				while (*q)
					*p++ = *q++;
				stack[classlevel].terminate = p;
				stack[classlevel].level = level;
				*p++ = 0;
			}
			startclass = startthrows = 0;
			break;
			/* { */
		case '}':
			if (--level < 0) {
				if (param->flags & PARSER_WARNING)
					warning("missing left '{' (at %d).", lineno); /* } */
				level = 0;
			}
			if (level < stack[classlevel].level)
				*(stack[--classlevel].terminate) = 0;
			/* { */
			DBG_PRINT(level, "}");
			break;
		case '=':
			startequal = 1;
			break;
		case ';':
			startclass = startthrows = startequal = 0;
			break;
		case JAVA_CLASS:
		case JAVA_INTERFACE:
		case JAVA_ENUM:
			if ((c = nexttoken(interested, java_reserved_word)) == SYMBOL) {
				strlimcpy(classname, token, sizeof(classname));
				startclass = 1;
				PUT(PARSER_DEF, token, lineno, sp);
			}
			break;
		case JAVA_NEW:
		case JAVA_INSTANCEOF:
			while ((c = nexttoken(interested, java_reserved_word)) == SYMBOL && peekc(1) == '.')
				PUT(PARSER_REF_SYM, token, lineno, sp);
			if (c == SYMBOL)
				PUT(PARSER_REF_SYM, token, lineno, sp);
			break;
		case JAVA_THROWS:
			startthrows = 1;
			break;
		case JAVA_BOOLEAN:
		case JAVA_BYTE:
		case JAVA_CHAR:
		case JAVA_DOUBLE:
		case JAVA_FLOAT:
		case JAVA_INT:
		case JAVA_LONG:
		case JAVA_SHORT:
		case JAVA_VOID:
			if (peekc(1) == '.' && (c = nexttoken(interested, java_reserved_word)) != JAVA_CLASS)
				pushbacktoken();
			break;
		default:
			break;
		}
	}
	closetoken();
}
예제 #27
0
int do_fwr (cmd_tbl_t * cmdtp, int flag, int argc, char *argv[])
{
	unsigned int fslnum;
	unsigned int num;
	unsigned int blocking;

	if (argc < 3) {
		cmd_usage(cmdtp);
		return 1;
	}

	fslnum = (unsigned int)simple_strtoul (argv[1], NULL, 16);
	num = (unsigned int)simple_strtoul (argv[2], NULL, 16);
	blocking = (unsigned int)simple_strtoul (argv[3], NULL, 16);
	if (fslnum < 0 || fslnum >= XILINX_FSL_NUMBER) {
		cmd_usage(cmdtp);
		return 1;
	}

	switch (fslnum) {
#if (XILINX_FSL_NUMBER > 0)
	case 0:
		switch (blocking) {
		case 0:	NPUT (num, 0);
			break;
		case 1:	NCPUT (num, 0);
			break;
		case 2:	PUT (num, 0);
			break;
		case 3:	CPUT (num, 0);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 1)
	case 1:
		switch (blocking) {
		case 0:	NPUT (num, 1);
			break;
		case 1:	NCPUT (num, 1);
			break;
		case 2:	PUT (num, 1);
			break;
		case 3:	CPUT (num, 1);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 2)
	case 2:
		switch (blocking) {
		case 0:	NPUT (num, 2);
			break;
		case 1:	NCPUT (num, 2);
			break;
		case 2:	PUT (num, 2);
			break;
		case 3:	CPUT (num, 2);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 3)
	case 3:
		switch (blocking) {
		case 0:	NPUT (num, 3);
			break;
		case 1:	NCPUT (num, 3);
			break;
		case 2:	PUT (num, 3);
			break;
		case 3:	CPUT (num, 3);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 4)
	case 4:
		switch (blocking) {
		case 0:	NPUT (num, 4);
			break;
		case 1:	NCPUT (num, 4);
			break;
		case 2:	PUT (num, 4);
			break;
		case 3:	CPUT (num, 4);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 5)
	case 5:
		switch (blocking) {
		case 0:	NPUT (num, 5);
			break;
		case 1:	NCPUT (num, 5);
			break;
		case 2:	PUT (num, 5);
			break;
		case 3:	CPUT (num, 5);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 6)
	case 6:
		switch (blocking) {
		case 0:	NPUT (num, 6);
			break;
		case 1:	NCPUT (num, 6);
			break;
		case 2:	PUT (num, 6);
			break;
		case 3:	CPUT (num, 6);
			break;
		default:
			return 2;
		}
		break;
#endif
#if (XILINX_FSL_NUMBER > 7)
	case 7:
		switch (blocking) {
		case 0:	NPUT (num, 7);
			break;
		case 1:	NCPUT (num, 7);
			break;
		case 2:	PUT (num, 7);
			break;
		case 3:	CPUT (num, 7);
			break;
		default:
			return 2;
		}
		break;
#endif
	default:
		return 1;
	}

	printf ("%01x: 0x%08x - %s %s write\n", fslnum, num,
		blocking < 2  ? "non blocking" : "blocking",
		((blocking == 1) || (blocking == 3)) ? "control" : "data" );
	return 0;

}
예제 #28
0
/**********************************************************
 * add_to_free_list
 * adds the free block to the free list
 **********************************************************/
void add_to_free_list(void *bp)
{
//	printf("IN ADD_TO_FREE_LIST\n");
//	printf("adding free block %p\n",bp);

	//get the size of the free block
	size_t size = GET(HDRP(bp));
	
	int i = get_segregated_index(size);

	//print_ptr(bp);
	if(segregated_list[i] == NULL)
	{
		//add the free block to the free list which is NULL
		segregated_list[i] = bp;

		//set the previous as 0 or (null/nothing)
		PUT(LOCATION_PREV_FREE_BLKP(bp),0);

		//set the next free block as 0 or (null/nothing)
		PUT(LOCATION_NEXT_FREE_BLKP(bp),0);

	}
	else
	{
		if(GET_SIZE(HDRP(segregated_list[i]))>GET_SIZE(HDRP(bp))){

			if(GET_NEXT_FREE_BLK(segregated_list[i])!=0)
			{
		//	print_seg(1);
//				void* sec_ptr = GET_NEXT_FREE_BLK(segregated_list[i]);
				PUT(LOCATION_NEXT_FREE_BLKP(bp),GET_NEXT_FREE_BLK(segregated_list[i]));
				PUT(GET_PREV_FREE_BLK(LOCATION_NEXT_FREE_BLKP(segregated_list[i])),bp);
				PUT(LOCATION_NEXT_FREE_BLKP(segregated_list[i]),bp);				
				PUT(LOCATION_PREV_FREE_BLKP(bp),segregated_list[i]);
				//printf("test esfewfe\n");
			//	print_ptr(bp);
			//	print_ptr(segregated_list[i]);
//print_seg(1);				
				
			}else{
						//printf("test2\n");
			//we only have 1 block in the list
				PUT(LOCATION_NEXT_FREE_BLKP(segregated_list[i]),bp);
				PUT(LOCATION_PREV_FREE_BLKP(bp),segregated_list[i]);
				PUT(LOCATION_PREV_FREE_BLKP(segregated_list[i]),0);
				PUT(LOCATION_NEXT_FREE_BLKP(bp),0);			
			}
			
			
		}else
		{
			//Set the next block of the new head as the previous head
			PUT(LOCATION_NEXT_FREE_BLKP(bp),segregated_list[i]);

			//Set the previous block of the new head as NULL
			PUT(LOCATION_PREV_FREE_BLKP(bp), 0);

			//Set the previous block of the previous head to the new head
			PUT(LOCATION_PREV_FREE_BLKP(segregated_list[i]),bp);

			segregated_list[i] = bp;
		}
	}
}
예제 #29
0
/*
 * Actual conversion; called from iconv()
 */
size_t
_icv_iconv(struct _icv_state *st, char **inbuf, size_t *inbytesleft,
				char **outbuf, size_t *outbytesleft)
{
	int				cset, stat;
	unsigned char	*op, ic, offset;
	char			*ip;
	size_t			ileft, oleft;
	size_t			retval;

	cset = st->_st_cset;
	stat = st->_st_stat;

	if ((inbuf == 0) || (*inbuf == 0)) {
		cset = CS_0;
		stat = ST_INIT;
		op = (unsigned char *)*outbuf;
		oleft = *outbytesleft;
		retval = 0;
		goto ret2;
	}

	ip = *inbuf;
	op = (unsigned char *)*outbuf;
	ileft = *inbytesleft;
	oleft = *outbytesleft;
	offset = 0;

	/* Everything down to here was taken unchanged from  @(#)ISO-2022-JP%SJIS. 
	   =======================================================================
	
	 *
	 * Main loop; basically 1 loop per 1 input byte
	 */

	while (ileft > 0) 
	{
		GET(ic);
	/*
		If the char is one of the following [ / ] { | } then convert 
		it to its corresponding value. In all other cases if the char 
		is greater than octal \178 ( ie a high bit char) convert it 
		to an underscore (_), as it has no mapping to 7 bit ASCII.
		Otrherwise the char is the same in both cose sets. 
	*/
		ic=__is2_to_maz[ic];
		
			
		PUT(ic);	
	/* 
		Put the converted character into the output buffer, and decrement 
		the count of chars left in both the in and out buffers.
		If we have no space left in the out buffer, but we have no reached
		the end of the input buffer. We return what we have, and set the
		errno (Error) to E2BIG.
	*/
		if ((oleft < 1)	 && (ileft > 0))
		{
			errno = E2BIG;
			retval = ERR_RETURN;
			goto ret;
		}		


	}
/* 
We only get here if the end of the in buffer has been reached, we therefore return the
value 0 to denote that we have sucesfully converted the inbuffer.
*/
	retval = ileft;

/*  Taken unchanged from   @(#)ISO-2022-JP%SJIS.  */

ret:
	st->_st_cset = cset;
	st->_st_stat = stat;
	*inbuf = ip;
	*inbytesleft = ileft;
ret2:
	*outbuf = (char *)op;
	*outbytesleft = oleft;

	return (retval);
}
예제 #30
0
/*
 * mm_realloc - Implemented simply in terms of mm_malloc and mm_free
 */
void *mm_realloc(void *ptr, size_t req_size)
{
    size_t new_size = adjust_requested_block_size(req_size);

    size_t size = GET_SIZE(HDRP(ptr));

    mm_log("\nrealloc(%p, %d => %d)\noriginal=%d\n\n", ptr, (int)req_size, (int)new_size, (int)size);

    if (new_size < size)
    {
        mm_log("newsize < original! keep pointer.\n");
        size_t remain = size - new_size;
        if (remain >= DSIZE+WSIZE*2)
        {
            PUT(HDRP(ptr), PACK(new_size, 1));
            PUT(FTRP(ptr), PACK(new_size, 1));

            mm_log("have some leftover (%d), which is enough for a new block.\n",(int)remain);
            //split
            void *split_pt = ptr + new_size;

            init_free_block(split_pt, remain);
        }
        return ptr;
    }

    /* Okay, we need to find some new space. See if there are adjacent blocks we can coalesce into */
    void *new_ptr;

    void *prev_ftr = ptr - DSIZE;
    void *next_hdr = ptr + size - WSIZE;

    size_t extra_space = 0;
    char c_prev = 0;
    char c_next = 0;

    if (!GET_ALLOC(prev_ftr))
    {
        extra_space += GET_SIZE(prev_ftr);
        c_prev = 1;
    }
    if (!GET_ALLOC(next_hdr))
    {
        extra_space += GET_SIZE(next_hdr);
        c_next = 1;
    }

    size_t coalesced_size = extra_space + size;

    if (coalesced_size >= new_size)
    {
        mm_log("prev open = %d; next open = %d. together with %d, we have %d total space.\n",c_prev,c_next,(int)size,(int)coalesced_size);

        new_ptr = ptr;
        if (c_prev)
        {
            new_ptr -= GET_SIZE(prev_ftr); //move ptr back to prev block
            delete_free_block(new_ptr);

            memcpy(new_ptr, ptr, size);
        }
        if (c_next)
        {
            delete_free_block(ptr + size);
        }

        /* We can now see if there's enough room to split another block */
        size_t remain = coalesced_size - new_size;
        if (remain >= DSIZE+WSIZE*2)
        {
            PUT(HDRP(new_ptr), PACK(new_size, 1));
            PUT(FTRP(new_ptr), PACK(new_size, 1));

            mm_log("have some leftover (%d), which is enough for a new block.\n",(int)remain);
            //split
            void *split_pt = new_ptr + new_size;

            init_free_block(split_pt, remain);
        }
        else
        {
            PUT(HDRP(new_ptr), PACK(coalesced_size, 1));
            PUT(FTRP(new_ptr), PACK(coalesced_size, 1));
        }

        return new_ptr;
    }

    mm_log("can't coalesce. have to malloc new & free this thing\n");

    /* Can't coalesce. Have to malloc new & free this block :( */
    new_ptr = mm_malloc(req_size);
    memcpy(new_ptr, ptr, size);

    init_free_block(ptr, size);
    
    return new_ptr;
}