示例#1
0
void GraphState::print ( FILE *f ) {
    static int counter = 0;
    counter++;
    putc ( 't', f );
    putc ( ' ', f );
    puti ( f, (int) counter );
    putc ( '\n', f );
    for ( int i = 0; i < (int) nodes.size (); i++ ) {
        putc ( 'v', f );
        putc ( ' ', f );
        puti ( f, (int) i );
        putc ( ' ', f );
        puti ( f, (int) fm::database->nodelabels[nodes[i].label].inputlabel );
        putc ( '\n', f );
    }
    for ( int i = 0; i < (int) nodes.size (); i++ ) {
        for ( int j = 0; j < (int) nodes[i].edges.size (); j++ ) {
            GraphState::GSEdge &edge = nodes[i].edges[j];
            if ( i < edge.tonode ) {
                putc ( 'e', f );
                putc ( ' ', f );
                puti ( f, (int) i );
                putc ( ' ', f );
                puti ( f, (int) edge.tonode );
                putc ( ' ', f );
                puti ( f, (int) fm::database->edgelabels[
                           fm::database->edgelabelsindexes[edge.edgelabel]
                       ].inputedgelabel );
                putc ( '\n', f );
            }
        }
    }
}
示例#2
0
int prints(char *s)
{
	while(*s != 0){
		putc(*s++);
	}	
}
示例#3
0
文件: ar_io.c 项目: rodrigc/bz-vimage
/*
 * ar_close()
 *	closes archive device, increments volume number, and prints i/o summary
 */
void
ar_close(void)
{
	int status;

	if (arfd < 0) {
		did_io = io_ok = flcnt = 0;
		return;
	}

	/*
	 * Close archive file. This may take a LONG while on tapes (we may be
	 * forced to wait for the rewind to complete) so tell the user what is
	 * going on (this avoids the user hitting control-c thinking pax is
	 * broken).
	 */
	if (vflag && (artyp == ISTAPE)) {
		if (vfpart)
			(void)putc('\n', listf);
		(void)fprintf(listf,
			"%s: Waiting for tape drive close to complete...",
			argv0);
		(void)fflush(listf);
	}

	/*
	 * if nothing was written to the archive (and we created it), we remove
	 * it
	 */
	if (can_unlnk && (fstat(arfd, &arsb) == 0) && (S_ISREG(arsb.st_mode)) &&
	    (arsb.st_size == 0)) {
		(void)unlink(arcname);
		can_unlnk = 0;
	}

	/*
	 * for a quick extract/list, pax frequently exits before the child
	 * process is done
	 */
	if ((act == LIST || act == EXTRACT) && nflag && zpid > 0)
		kill(zpid, SIGINT);

	(void)close(arfd);

	/* Do not exit before child to ensure data integrity */
	if (zpid > 0)
		waitpid(zpid, &status, 0);

	if (vflag && (artyp == ISTAPE)) {
		(void)fputs("done.\n", listf);
		vfpart = 0;
		(void)fflush(listf);
	}
	arfd = -1;

	if (!io_ok && !did_io) {
		flcnt = 0;
		return;
	}
	did_io = io_ok = 0;

	/*
	 * The volume number is only increased when the last device has data
	 * and we have already determined the archive format.
	 */
	if (frmt != NULL)
		++arvol;

	if (!vflag) {
		flcnt = 0;
		return;
	}

	/*
	 * Print out a summary of I/O for this archive volume.
	 */
	if (vfpart) {
		(void)putc('\n', listf);
		vfpart = 0;
	}

	/*
	 * If we have not determined the format yet, we just say how many bytes
	 * we have skipped over looking for a header to id. there is no way we
	 * could have written anything yet.
	 */
	if (frmt == NULL) {
#	ifdef NET2_STAT
		(void)fprintf(listf, "%s: unknown format, %lu bytes skipped.\n",
		    argv0, rdcnt);
#	else
		(void)fprintf(listf, "%s: unknown format, %ju bytes skipped.\n",
		    argv0, (uintmax_t)rdcnt);
#	endif
		(void)fflush(listf);
		flcnt = 0;
		return;
	}

	if (strcmp(NM_CPIO, argv0) == 0)
		(void)fprintf(listf, "%llu blocks\n",
		    (unsigned long long)((rdcnt ? rdcnt : wrcnt) / 5120));
	else if (strcmp(NM_TAR, argv0) != 0)
		(void)fprintf(listf,
#	ifdef NET2_STAT
		    "%s: %s vol %d, %lu files, %lu bytes read, %lu bytes written.\n",
		    argv0, frmt->name, arvol-1, flcnt, rdcnt, wrcnt);
#	else
		    "%s: %s vol %d, %ju files, %ju bytes read, %ju bytes written.\n",
		    argv0, frmt->name, arvol-1, (uintmax_t)flcnt,
		    (uintmax_t)rdcnt, (uintmax_t)wrcnt);
#	endif
	(void)fflush(listf);
	flcnt = 0;
}
示例#4
0
int main(int argc, char** argv){

  if(argc < 3){
    printf("\nError: Not enough arguments.\n\nUsage: demodulate [input wave file] [output binary file]\n\n");
    exit(1);
  }
  
	/*open transmission file and get file info*/
  SF_INFO transmissionInformation;
  SNDFILE* inputWaveFile = sf_open(argv[1], SFM_READ, &transmissionInformation);
  
  if(inputWaveFile == NULL){
    printf("\nError \"%s\": could not open file!\n\n",argv[1]);
    exit(1);
  }
  
  FILE* outputFile = fopen(argv[2], "wb+");
  	
  if(outputFile == NULL){
    printf("\nError \"%s\": could not create file!\n\n",argv[2]);
    exit(1);
  }
  
    /*only get one sample at a time and check if the adjacent sample is of reversed sign
     * then, take the number of samples it took before the sign was reversed. if it is >3 but <14,
     * add 1 bit to the current number place. if it is >=14, do nothing (add 0)*/          
  short thisSample 			= 0;
    /*used for debugging; 44100/totalSamples = current timestamp along the audio file*/
  int totalSamples			= 0;
    /*number of times sign has changed for current wave; add 1 when # of 2400hz periods = 8
     add 0 when # of 1200hz periods = 4*/
  short numberOf1200hzHalfPeriods	= 0;  
  short numberOf2400hzHalfPeriods	= 0;
    
    /*start positive; transmission starts positive.*/
  short lastSample			= 1;
    /*number of samples read before sign was switched*/
  short numberOfSamplesBeforeSwitch 	= 0;
    /*number placed to be added per bit. decreases every time number is added*/
  char numberPlaceForThisByte 		= 7;
  
    /*byte to be written*/
  char writeByte 			= 0;
  
  for(int i = 0; i < transmissionInformation.frames; i++){    
      /*get next sample*/
    sf_read_short(inputWaveFile, &thisSample, 1);  
      /*used for debugging*/
    totalSamples++;
      /*check if sign has switched*/
    if(thisSample == 0 || (thisSample < 0 && lastSample > 0) || (thisSample > 0 && lastSample < 0)){
	// old output debugging
      //printf("Triggered! this: %d\tlast: %d\n",thisSample, lastSample);      
	
	/*number of samples between 3 and 14, is one. (a perfect 1 is 8.5 samples and
	 * a perfect 0 is 17 samples; 17 - 8 = 9. 9/2 = 4.5 (rounded to 5. 9 - 5 = 4, 9 + 5 = 14.
	 * Thus, the margin of error is +- 5*/
      if(numberOfSamplesBeforeSwitch > 3 && numberOfSamplesBeforeSwitch < 14){
	numberOf2400hzHalfPeriods++;
	  /*reset sample count*/
	numberOfSamplesBeforeSwitch = 0;
      }
      else if(numberOfSamplesBeforeSwitch >= 14 && numberOfSamplesBeforeSwitch <= 24){
	numberOf1200hzHalfPeriods++;
	numberOfSamplesBeforeSwitch = 0;
      }      
    }
      //more old debugging stuff
    //printf("this: %d last: %d at s: %f\n", thisSample, lastSample, (double)(totalSamples)/(double)(44100));
    //printf("%d\n",numberOfSamplesBeforeSwitch);
    //printf("%d - %d\n", numberOf2400hzHalfPeriods,numberOf1200hzHalfPeriods);
    
      /*# of half periods should be 8 (for 4 total periods)*/
    if(numberOf2400hzHalfPeriods == 8){
      //add 1 bit      
      
	/*reset metrics*/
      numberOf1200hzHalfPeriods = 0;
      numberOf2400hzHalfPeriods = 0;
	/*add 1 to current number place*/
      writeByte += pow(2,numberPlaceForThisByte);
	/*iterate to next number place*/
      numberPlaceForThisByte--;
    }
      /*# of half periods should be 4 (for 2 total periods*/
    if(numberOf1200hzHalfPeriods == 4){
      //add 0 bit (or do nothing really)
	/*reset metrics*/
      numberOf1200hzHalfPeriods = 0; 
      numberOf2400hzHalfPeriods = 0;
	/*iterate to number place. write nothing to current bit*/
      numberPlaceForThisByte--;
    }
    
      //debugging
    //printf("byte so far: %d at number place %d\n", writeByte, numberPlaceForThisByte);
    
    if(numberPlaceForThisByte == -1){
	//debugging
      //printf("byte written!\n");
      
	/*write byte to file stream*/
      putc(writeByte, outputFile);   
	/*reset byte*/
      writeByte = 0;
	/*reset number place*/
      numberPlaceForThisByte = 7;
    }
    
      /*iteratre number of samples*/
    numberOfSamplesBeforeSwitch++;
      
      /*get previous sample for comparing signs with next sample*/
    lastSample = thisSample;
    
  }
    /*write output*/
  fclose(outputFile);
}
示例#5
0
/**************************************************************//**
Restores the stored position of a persistent cursor bufferfixing the page and
obtaining the specified latches. If the cursor position was saved when the
(1) cursor was positioned on a user record: this function restores the position
to the last record LESS OR EQUAL to the stored record;
(2) cursor was positioned on a page infimum record: restores the position to
the last record LESS than the user record which was the successor of the page
infimum;
(3) cursor was positioned on the page supremum: restores to the first record
GREATER than the user record which was the predecessor of the supremum.
(4) cursor was positioned before the first or after the last in an empty tree:
restores to before first or after the last in the tree.
@return TRUE if the cursor position was stored when it was on a user
record and it can be restored on a user record whose ordering fields
are identical to the ones of the original user record */
UNIV_INTERN
ibool
btr_pcur_restore_position_func(
/*===========================*/
	ulint		latch_mode,	/*!< in: BTR_SEARCH_LEAF, ... */
	btr_pcur_t*	cursor,		/*!< in: detached persistent cursor */
	const char*	file,		/*!< in: file name */
	ulint		line,		/*!< in: line where called */
	mtr_t*		mtr)		/*!< in: mtr */
{
	dict_index_t*	index;
	dtuple_t*	tuple;
	ulint		mode;
	ulint		old_mode;
	mem_heap_t*	heap;

	ut_ad(mtr);
	ut_ad(mtr->state == MTR_ACTIVE);

	index = btr_cur_get_index(btr_pcur_get_btr_cur(cursor));

	if (UNIV_UNLIKELY(cursor->old_stored != BTR_PCUR_OLD_STORED)
	    || UNIV_UNLIKELY(cursor->pos_state != BTR_PCUR_WAS_POSITIONED
			     && cursor->pos_state != BTR_PCUR_IS_POSITIONED)) {
		ut_print_buf(stderr, cursor, sizeof(btr_pcur_t));
		putc('\n', stderr);
		if (cursor->trx_if_known) {
			trx_print(stderr, cursor->trx_if_known, 0);
		}

		ut_error;
	}

	if (UNIV_UNLIKELY
	    (cursor->rel_pos == BTR_PCUR_AFTER_LAST_IN_TREE
	     || cursor->rel_pos == BTR_PCUR_BEFORE_FIRST_IN_TREE)) {

		/* In these cases we do not try an optimistic restoration,
		but always do a search */

		btr_cur_open_at_index_side(
			cursor->rel_pos == BTR_PCUR_BEFORE_FIRST_IN_TREE,
			index, latch_mode, btr_pcur_get_btr_cur(cursor), mtr);

		cursor->block_when_stored = btr_pcur_get_block(cursor);

		return(FALSE);
	}

	ut_a(cursor->old_rec);
	ut_a(cursor->old_n_fields);

	if (UNIV_LIKELY(latch_mode == BTR_SEARCH_LEAF)
	    || UNIV_LIKELY(latch_mode == BTR_MODIFY_LEAF)) {
		/* Try optimistic restoration */

		if (UNIV_LIKELY(buf_page_optimistic_get(
					latch_mode,
					cursor->block_when_stored,
					cursor->modify_clock,
					file, line, mtr))) {
			cursor->pos_state = BTR_PCUR_IS_POSITIONED;

			buf_block_dbg_add_level(btr_pcur_get_block(cursor),
						SYNC_TREE_NODE);

			if (cursor->rel_pos == BTR_PCUR_ON) {
#ifdef UNIV_DEBUG
				const rec_t*	rec;
				const ulint*	offsets1;
				const ulint*	offsets2;
#endif /* UNIV_DEBUG */
				cursor->latch_mode = latch_mode;
#ifdef UNIV_DEBUG
				rec = btr_pcur_get_rec(cursor);

				heap = mem_heap_create(256);
				offsets1 = rec_get_offsets(
					cursor->old_rec, index, NULL,
					cursor->old_n_fields, &heap);
				offsets2 = rec_get_offsets(
					rec, index, NULL,
					cursor->old_n_fields, &heap);

				ut_ad(!cmp_rec_rec(cursor->old_rec,
						   rec, offsets1, offsets2,
						   index));
				mem_heap_free(heap);
#endif /* UNIV_DEBUG */
				return(TRUE);
			}

			return(FALSE);
		}
	}

	/* If optimistic restoration did not succeed, open the cursor anew */

	heap = mem_heap_create(256);

	tuple = dict_index_build_data_tuple(index, cursor->old_rec,
					    cursor->old_n_fields, heap);

	/* Save the old search mode of the cursor */
	old_mode = cursor->search_mode;

	if (UNIV_LIKELY(cursor->rel_pos == BTR_PCUR_ON)) {
		mode = PAGE_CUR_LE;
	} else if (cursor->rel_pos == BTR_PCUR_AFTER) {
		mode = PAGE_CUR_G;
	} else {
		ut_ad(cursor->rel_pos == BTR_PCUR_BEFORE);
		mode = PAGE_CUR_L;
	}

	btr_pcur_open_with_no_init_func(index, tuple, mode, latch_mode,
					cursor, 0, file, line, mtr);

	/* Restore the old search mode */
	cursor->search_mode = old_mode;

	if (cursor->rel_pos == BTR_PCUR_ON
	    && btr_pcur_is_on_user_rec(cursor)
	    && 0 == cmp_dtuple_rec(tuple, btr_pcur_get_rec(cursor),
				   rec_get_offsets(
					   btr_pcur_get_rec(cursor), index,
					   NULL, ULINT_UNDEFINED, &heap))) {

		/* We have to store the NEW value for the modify clock, since
		the cursor can now be on a different page! But we can retain
		the value of old_rec */

		cursor->block_when_stored = btr_pcur_get_block(cursor);
		cursor->modify_clock = buf_block_get_modify_clock(
			cursor->block_when_stored);
		cursor->old_stored = BTR_PCUR_OLD_STORED;

		mem_heap_free(heap);

		return(TRUE);
	}

	mem_heap_free(heap);

	/* We have to store new position information, modify_clock etc.,
	to the cursor because it can now be on a different page, the record
	under it may have been removed, etc. */

	btr_pcur_store_position(cursor, mtr);

	return(FALSE);
}
			int_type overflow(int_type c_= _Traits::eof())/*C++0x_override/**/{
				putc(c_);
				return 0;
			}
示例#7
0
文件: winduni.c 项目: CromFr/gdb
void
ascii_print (FILE *e, const char *s, rc_uint_type length)
{
  while (1)
    {
      char ch;

      if (length == 0)
	return;
      if ((bfd_signed_vma) length > 0)
	--length;

      ch = *s;

      if (ch == 0 && (bfd_signed_vma) length < 0)
	return;

      ++s;

      if ((ch & 0x7f) == ch)
	{
	  if (ch == '\\')
	    fputs ("\\\\", e);
	  else if (ch == '"')
	    fputs ("\"\"", e);
	  else if (ISPRINT (ch))
	    putc (ch, e);
	  else
	    {
	      switch (ch)
		{
		case ESCAPE_A:
		  fputs ("\\a", e);
		  break;

		case ESCAPE_B:
		  fputs ("\\b", e);
		  break;

		case ESCAPE_F:
		  fputs ("\\f", e);
		  break;

		case ESCAPE_N:
		  fputs ("\\n", e);
		  break;

		case ESCAPE_R:
		  fputs ("\\r", e);
		  break;

		case ESCAPE_T:
		  fputs ("\\t", e);
		  break;

		case ESCAPE_V:
		  fputs ("\\v", e);
		  break;

		default:
		  fprintf (e, "\\%03o", (unsigned int) ch);
		  break;
		}
	    }
	}
      else
	fprintf (e, "\\%03o", (unsigned int) ch & 0xff);
    }
}
void puts(const char *str)
{
	while (*str)
		putc(*str++);
}
示例#9
0
void
do_ranlib (const char *archive)
{
  FILE *infp;

  if (NULL == (infp = fopen (archive, "rb")))
    {
      fprintf (stderr, "asranlib: %s: ", archive);
      perror (NULL);
      exit (1);
    }

  if (!get_symbols (infp, archive))
    {
      fprintf (stderr, "asranlib: %s: Malformed archive\n", archive);
      fclose (infp);
      exit (1);
    }
  else if (!list && !print_index)
    {
      FILE *outfp;
      struct symbol_s *symp;
      char buf[4];
      int str_length;
      int pad;
      int nsym;
      int symtab_size;
      char tmpfile[] = "arXXXXXX";
      struct stat stat_buf;
      int can_stat;

#ifdef _WIN32
      if (NULL == _mktemp (tmpfile) || NULL == (outfp = fopen (tmpfile, "wb")))
        {
          fclose (infp);
          fprintf (stderr, "asranlib: %s: ", tmpfile);
          perror (NULL);
          exit (1);
        }
#else
      if ((pad = mkstemp (tmpfile)) < 0)
        {
          fclose (infp);
          fprintf (stderr, "asranlib: %s: ", tmpfile);
          perror (NULL);
          exit (1);
        }

      if (NULL == (outfp = fdopen (pad, "wb")))
        {
          close (pad);
          fclose (infp);
          perror ("asranlib");
          exit (1);
        }
#endif

      /* calculate the size of symbol table */
      for (str_length = 0, nsym = 0, symp = symlist; symp; ++nsym, symp = symp->next)
        {
          str_length += strlen (symp->name) + 1;
        }

      symtab_size = 4 + 4 * nsym + str_length;

      fprintf (outfp, ARMAG AR_SYMBOL_TABLE_NAME "%-12d%-6d%-6d%-8d%-10d" ARFMAG, (int) time (NULL), 0, 0, 0, symtab_size);

      if (symtab_size & 1)
        {
          pad = 1;
          ++symtab_size;
        }
      else
        pad = 0;

      symtab_size += SARMAG + ARHDR_LEN;

      sputl (nsym, buf);
      fwrite (buf, 1, sizeof (buf), outfp);

      for (symp = symlist; symp; symp = symp->next)
        {
          sputl (symp->offset + symtab_size, buf);
          fwrite (buf, 1, sizeof (buf), outfp);
        }

      for (symp = symlist; symp; symp = symp->next)
        {
          fputs (symp->name, outfp);
          putc ('\0', outfp);
        }

      if (pad)
        putc ('\n', outfp);

      fseek (infp, first_member_offset, SEEK_SET);

      while (EOF != (pad = getc (infp)))
        putc (pad, outfp);

      fclose (outfp);

      if (0 != fstat(fileno(infp), &stat_buf))
        {
          fprintf (stderr, "asranlib: can't stat %s: ", archive);
          perror (NULL);
          can_stat = 0;
        }
      else
        can_stat = 1;

      fclose (infp);

      if (0 != remove (archive))
        {
          fprintf (stderr, "asranlib: can't remove %s: ", archive);
          perror (NULL);
        }
      else if (0 != rename (tmpfile, archive))
        {
          fprintf (stderr, "asranlib: can't rename %s to %s: ", tmpfile, archive);
          perror (NULL);
        }
      else if (!can_stat || 0 != chmod (archive, stat_buf.st_mode))
        {
          fprintf (stderr, "asranlib: can't chmod %s: ", archive);
          perror (NULL);
        }
    }
  else
    fclose (infp);
}
示例#10
0
VOID
BlPrint(
    PCHAR cp,
    ...
    )

/*++

Routine Description:

    Standard printf function with a subset of formating features supported.

    Currently handles

     %d, %ld - signed short, signed long
     %u, %lu - unsigned short, unsigned long
     %c, %s  - character, string
     %x, %lx - unsigned print in hex, unsigned long print in hex

    Does not do:

     - field width specification
     - floating point.

Arguments:

    cp - pointer to the format string, text string.


Returns:

    Nothing


--*/

{
    USHORT b,c,w,len;
    PUCHAR ap;
    ULONG l;

    //
    // Cast a pointer to the first word on the stack
    //

    ap = (PUCHAR)&cp + sizeof(PCHAR);
    sc = ' '; // default padding char is space

    //
    // Process the arguments using the descriptor string
    //


    while (b = *cp++)
        {
        if (b == '%')
            {
            c = *cp++;

            switch (c)
                {
                case 'd':
                    puti((long)*((int *)ap));
                    ap += sizeof(int);
                    break;

                case 's':
                    BlPuts(*((PCHAR *)ap));
                    ap += sizeof (char *);
                    break;

                case 'c':
                    putc(*((char *)ap));
                    ap += sizeof(int);
                    break;

                case 'x':
                    w = *((USHORT *)ap);
                    len = ZLEN_SHORT(w);
                    while(len--) putc('0');
                    putx((ULONG)*((USHORT *)ap));
                    ap += sizeof(int);
                    break;

                case 'u':
                    putu((ULONG)*((USHORT *)ap));
                    ap += sizeof(int);
                    break;

                case 'l':
                    c = *cp++;

                switch(c) {

                    case 'u':
                        putu(*((ULONG *)ap));
                        ap += sizeof(long);
                        break;

                    case 'x':
                        l = *((ULONG *)ap);
                        len = ZLEN_LONG(l);
                        while(len--) putc('0');
                        putx(*((ULONG *)ap));
                        ap += sizeof(long);
                        break;

                    case 'd':
                        puti(*((ULONG *)ap));
                        ap += sizeof(long);
                        break;

                }
                break;

                default :
                    putc((char)b);
                    putc((char)c);
                }
            }
        else
            putc((char)b);
        }

}
示例#11
0
void writeIfd0(FILE *fptr, DngWriter *writer)
{
    /* Write the header */
    WriteHexString(fptr,"4d4d002a");    /* Big endian & TIFF identifier */
    offset = writer->rawwidht * writer->rawheight * 3 + 8;
    putc((offset & 0xff000000) / 16777216,fptr);
    putc((offset & 0x00ff0000) / 65536,fptr);
    putc((offset & 0x0000ff00) / 256,fptr);
    putc((offset & 0x000000ff),fptr);

    //raw file ?
    /* Write the binary data */
    for (j=0;j<ny;j++) {
        for (i=0;i<nx;i++) {
            //... calculate the RGB value between 0 and 255 ...
            fputc(red,fptr);
            fputc(green,fptr);
            fputc(blue,fptr);
        }
    }

    /* Write the footer */
    WriteHexString(fptr,"000e");  /* The number of directory entries (14) */

    //Use Tiff Tags for ints added To DngWriter Header file

    WriteHexString(fptr,TagGen(TIFFTAG_SUBFILETYPE,Sshort));  /* The number of directory entries (14) */

    //TIFFSetField (tif, TIFFTAG_SUBFILETYPE, 0);

    /* Width tag, short int */
    WriteHexString(fptr,"0100000300000001");
    fputc((writer->rawwidht & 0xff00) / 256,fptr);    /* Image width */
    fputc((writer->rawwidht & 0x00ff),fptr);
    WriteHexString(fptr,"0000");

    /* Height tag, short int */
    WriteHexString(fptr,"0101000300000001");
    fputc((writer->rawheight & 0xff00) / 256,fptr);    /* Image height */
    fputc((writer->rawheight & 0x00ff),fptr);
    WriteHexString(fptr,"0000");

    LOGD("subfiletype");

    assert(TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, writer->rawwidht) != 0);
    LOGD("width");


    assert(TIFFSetField(tif, TIFFTAG_IMAGELENGTH, writer->rawheight) != 0);
    LOGD("height");


    if(writer->rawType > 0)
        assert(TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 16) != 0);
    else
        assert(TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, 10) != 0);
    LOGD("bitspersample");
    assert(TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_CFA) != 0);
    LOGD("PhotometricCFA");
    //assert(TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, 480/2) != 0);
    assert(TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE) != 0);
    LOGD("Compression");
    TIFFSetField (tif, TIFFTAG_SAMPLESPERPIXEL, 1);
    LOGD("sampelsperpixel");
    TIFFSetField(tif, TIFFTAG_MAKE, writer->_make);
    LOGD("make");
    TIFFSetField(tif, TIFFTAG_MODEL, writer->_model);
    LOGD("model");
    try
    {
        if(0 == strcmp(writer->_orientation,"0") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);
        if(0 == strcmp(writer->_orientation,"90") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_RIGHTTOP);
        if(0 == strcmp(writer->_orientation,"180") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_BOTRIGHT);
        if(0 == strcmp(writer->_orientation,"270") )
            TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_LEFTBOT);
        LOGD("orientation");
    }
    catch(...)
    {
        LOGD("Caught NULL NOT SET Orientation");
    }
    assert(TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG) != 0);
    LOGD("planarconfig");
    //assert(TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, 3) != 0);
    TIFFSetField(tif, TIFFTAG_SOFTWARE, "FreedCam by Troop");
    LOGD("software");
    TIFFSetField(tif, TIFFTAG_DNGVERSION, "\001\003\0\0");
    TIFFSetField(tif, TIFFTAG_DNGBACKWARDVERSION, "\001\001\0\0");
    LOGD("dngversion");
    TIFFSetField(tif, TIFFTAG_UNIQUECAMERAMODEL, "SonyIMX");
    LOGD("CameraModel");
    TIFFSetField(tif, TIFFTAG_IMAGEDESCRIPTION, writer->_imagedescription);
    LOGD("imagedescription");
    TIFFSetField(tif, TIFFTAG_COLORMATRIX1, 9, writer->colorMatrix2);
    LOGD("colormatrix1");
    TIFFSetField(tif, TIFFTAG_ASSHOTNEUTRAL, 3, writer->neutralColorMatrix);
    LOGD("neutralMatrix");
    TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT1, 21);

    TIFFSetField(tif, TIFFTAG_CALIBRATIONILLUMINANT2, 17);

    TIFFSetField(tif, TIFFTAG_COLORMATRIX2, 9, writer->colorMatrix1);

    static const float cam_foward1[] = {
            // R 	G     	B
            0.6648, 0.2566, 0.0429, 0.197, 0.9994, -0.1964, -0.0894, -0.2304, 1.145
    };

    static const float cam_foward2[] = {
            0.6617, 0.3849, -0.0823, 0.24, 1.1138, -0.3538, -0.0062, -0.1147, 0.946
    };

    static const float cam_nex_foward1[] = {
            // R 	G     	B
            0.6328, 0.0469, 0.2813, 0.1641, 0.7578, 0.0781, -0.0469, -0.6406, 1.5078
    };

    static const float cam_nex_foward2[] = {
            0.7578, 0.0859, 0.1172, 0.2734, 0.8281, -0.1016, 0.0156, -0.2813, 1.0859
    };
    TIFFSetField(tif, TIFFTAG_FOWARDMATRIX1, 9,  writer->fowardMatrix2);
    TIFFSetField(tif, TIFFTAG_FOWARDMATRIX2, 9,  writer->fowardMatrix1);
    static const float testNR[] = {
            0.00051471, 0, 0.00051471,0, 0.00051471, 0};
    TIFFSetField(tif, TIFFTAG_NOISEPROFILE, 6,  writer->noiseMatrix);



    LOGD("colormatrix2");
    //////////////////////////////IFD POINTERS///////////////////////////////////////
    ///GPS//////////
    // TIFFSetField (tif, TIFFTAG_GPSIFD, gpsIFD_offset);
    ///EXIF////////

}
示例#12
0
void
done (int k)
{
  if (faction)
    fclose(faction);

  if (fattrs)
    fclose(fattrs);

  if (fguard)
    fclose(fguard);

  if (finput)
    fclose(finput);

  if (fparser)
    fclose(fparser);

  if (foutput)
    fclose(foutput);

	/* JF write out the output file */
  if (k == 0 && ftable)
    {
      FILE *ftmp;
      int c;

      ftmp=tryopen(tabfile, "w");
      rewind(ftable);
      while((c=getc(ftable)) != EOF)
        putc(c,ftmp);
      fclose(ftmp);
      fclose(ftable);

      if (definesflag)
        {
          ftmp = tryopen(defsfile, "w");
          fflush(fdefines);
          rewind(fdefines);
          while((c=getc(fdefines)) != EOF)
            putc(c,ftmp);
          fclose(ftmp);
          fclose(fdefines);
        }
    }

#ifdef VMS
  if (faction)
    delete(actfile);
  if (fattrs)
    delete(tmpattrsfile);
  if (ftable)
    delete(tmptabfile);
  if (k==0) sys$exit(SS$_NORMAL);
  sys$exit(SS$_ABORT);
#else
#ifdef MSDOS
  if (actfile) unlink(actfile);
  if (tmpattrsfile) unlink(tmpattrsfile);
  if (tmptabfile) unlink(tmptabfile);
  if (tmpdefsfile) unlink(tmpdefsfile);
#endif /* MSDOS */
  exit(k);
#endif /* not VMS */
}
示例#13
0
文件: getarg.c 项目: crherar/Admin
ROKEN_LIB_FUNCTION void ROKEN_LIB_CALL
arg_printusage_i18n (struct getargs *args,
		     size_t num_args,
		     const char *usage,
		     const char *progname,
		     const char *extra_string,
		     char *(*i18n)(const char *))
{
    size_t i, max_len = 0;
    char buf[128];
    int col = 0, columns;

    if (progname == NULL)
	progname = getprogname();

    if (i18n == NULL)
	i18n = builtin_i18n;

    if(getenv("GETARGMANDOC")){
	mandoc_template(args, num_args, progname, extra_string, i18n);
	return;
    }
    if(get_window_size(2, NULL, &columns) == -1)
	columns = 80;
    col = 0;
    col += fprintf (stderr, "%s: %s", usage, progname);
    buf[0] = '\0';
    for (i = 0; i < num_args; ++i) {
	if(args[i].short_name && ISFLAG(args[i])) {
	    char s[2];
	    if(buf[0] == '\0')
		strlcpy(buf, "[-", sizeof(buf));
	    s[0] = args[i].short_name;
	    s[1] = '\0';
	    strlcat(buf, s, sizeof(buf));
	}
    }
    if(buf[0] != '\0') {
	strlcat(buf, "]", sizeof(buf));
	col = check_column(stderr, col, strlen(buf) + 1, columns);
	col += fprintf(stderr, " %s", buf);
    }

    for (i = 0; i < num_args; ++i) {
	size_t len = 0;

	if (args[i].long_name) {
	    buf[0] = '\0';
	    strlcat(buf, "[--", sizeof(buf));
	    len += 2;
	    if(args[i].type == arg_negative_flag) {
		strlcat(buf, "no-", sizeof(buf));
		len += 3;
	    }
	    strlcat(buf, args[i].long_name, sizeof(buf));
	    len += strlen(args[i].long_name);
	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
			     0, 1, &args[i], i18n);
	    strlcat(buf, "]", sizeof(buf));
	    if(args[i].type == arg_strings)
		strlcat(buf, "...", sizeof(buf));
	    col = check_column(stderr, col, strlen(buf) + 1, columns);
	    col += fprintf(stderr, " %s", buf);
	}
	if (args[i].short_name && !ISFLAG(args[i])) {
	    snprintf(buf, sizeof(buf), "[-%c", args[i].short_name);
	    len += 2;
	    len += print_arg(buf + strlen(buf), sizeof(buf) - strlen(buf),
			     0, 0, &args[i], i18n);
	    strlcat(buf, "]", sizeof(buf));
	    if(args[i].type == arg_strings)
		strlcat(buf, "...", sizeof(buf));
	    col = check_column(stderr, col, strlen(buf) + 1, columns);
	    col += fprintf(stderr, " %s", buf);
	}
	if (args[i].long_name && args[i].short_name)
	    len += 2; /* ", " */
	max_len = max(max_len, len);
    }
    if (extra_string) {
	check_column(stderr, col, strlen(extra_string) + 1, columns);
	fprintf (stderr, " %s\n", extra_string);
    } else
	fprintf (stderr, "\n");
    for (i = 0; i < num_args; ++i) {
	if (args[i].help) {
	    size_t count = 0;

	    if (args[i].short_name) {
		count += fprintf (stderr, "-%c", args[i].short_name);
		print_arg (buf, sizeof(buf), 0, 0, &args[i], i18n);
		count += fprintf(stderr, "%s", buf);
	    }
	    if (args[i].short_name && args[i].long_name)
		count += fprintf (stderr, ", ");
	    if (args[i].long_name) {
		count += fprintf (stderr, "--");
		if (args[i].type == arg_negative_flag)
		    count += fprintf (stderr, "no-");
		count += fprintf (stderr, "%s", args[i].long_name);
		print_arg (buf, sizeof(buf), 0, 1, &args[i], i18n);
		count += fprintf(stderr, "%s", buf);
	    }
	    while(count++ <= max_len)
		putc (' ', stderr);
	    fprintf (stderr, "%s\n", (*i18n)(args[i].help));
	}
    }
}
示例#14
0
cont(xi,yi){
	putc('n',stdout);
	putsi(xi);
	putsi(yi);
}
示例#15
0
_nc_resolve_uses2(bool fullresolve, bool literal)
/* try to resolve all use capabilities */
{
    ENTRY *qp, *rp, *lastread = 0;
    bool keepgoing;
    unsigned i;
    int unresolved, total_unresolved, multiples;

    DEBUG(2, ("RESOLUTION BEGINNING"));

    /*
     * Check for multiple occurrences of the same name.
     */
    multiples = 0;
    for_entry_list(qp) {
	int matchcount = 0;

	for_entry_list(rp) {
	    if (qp > rp
		&& _nc_entry_match(qp->tterm.term_names, rp->tterm.term_names)) {
		matchcount++;
		if (matchcount == 1) {
		    (void) fprintf(stderr, "Name collision between %s",
				   _nc_first_name(qp->tterm.term_names));
		    multiples++;
		}
		if (matchcount >= 1)
		    (void) fprintf(stderr, " %s", _nc_first_name(rp->tterm.term_names));
	    }
	}
	if (matchcount >= 1)
	    (void) putc('\n', stderr);
    }
    if (multiples > 0)
	return (FALSE);

    DEBUG(2, ("NO MULTIPLE NAME OCCURRENCES"));

    /*
     * First resolution stage: compute link pointers corresponding to names.
     */
    total_unresolved = 0;
    _nc_curr_col = -1;
    for_entry_list(qp) {
	unresolved = 0;
	for (i = 0; i < qp->nuses; i++) {
	    bool foundit;
	    char *child = _nc_first_name(qp->tterm.term_names);
	    char *lookfor = qp->uses[i].name;
	    long lookline = qp->uses[i].line;

	    foundit = FALSE;

	    _nc_set_type(child);

	    /* first, try to resolve from in-core records */
	    for_entry_list(rp) {
		if (rp != qp
		    && _nc_name_match(rp->tterm.term_names, lookfor, "|")) {
		    DEBUG(2, ("%s: resolving use=%s (in core)",
			      child, lookfor));

		    qp->uses[i].link = rp;
		    foundit = TRUE;
		}
	    }

	    /* if that didn't work, try to merge in a compiled entry */
	    if (!foundit) {
		TERMTYPE thisterm;
		char filename[PATH_MAX];

		memset(&thisterm, 0, sizeof(thisterm));
		if (_nc_read_entry(lookfor, filename, &thisterm) == 1) {
		    DEBUG(2, ("%s: resolving use=%s (compiled)",
			      child, lookfor));

		    rp = typeMalloc(ENTRY, 1);
		    if (rp == 0)
			_nc_err_abort(MSG_NO_MEMORY);
		    rp->tterm = thisterm;
		    rp->nuses = 0;
		    rp->next = lastread;
		    lastread = rp;

		    qp->uses[i].link = rp;
		    foundit = TRUE;
		}
	    }

	    /* no good, mark this one unresolvable and complain */
	    if (!foundit) {
		unresolved++;
		total_unresolved++;

		_nc_curr_line = lookline;
		_nc_warning("resolution of use=%s failed", lookfor);
		qp->uses[i].link = 0;
	    }
	}
    }
    if (total_unresolved) {
	/* free entries read in off disk */
	_nc_free_entries(lastread);
	return (FALSE);
    }

    DEBUG(2, ("NAME RESOLUTION COMPLETED OK"));

    /*
     * OK, at this point all (char *) references in `name' members
     * have been successfully converted to (ENTRY *) pointers in
     * `link' members.  Time to do the actual merges.
     */
    if (fullresolve) {
	do {
	    TERMTYPE merged;

	    keepgoing = FALSE;

	    for_entry_list(qp) {
		if (qp->nuses > 0) {
		    DEBUG(2, ("%s: attempting merge",
			      _nc_first_name(qp->tterm.term_names)));
		    /*
		     * If any of the use entries we're looking for is
		     * incomplete, punt.  We'll catch this entry on a
		     * subsequent pass.
		     */
		    for (i = 0; i < qp->nuses; i++)
			if (qp->uses[i].link->nuses) {
			    DEBUG(2, ("%s: use entry %d unresolved",
				      _nc_first_name(qp->tterm.term_names), i));
			    goto incomplete;
			}

		    /*
		     * First, make sure there is no garbage in the
		     * merge block.  As a side effect, copy into
		     * the merged entry the name field and string
		     * table pointer.
		     */
		    _nc_copy_termtype(&merged, &(qp->tterm));

		    /*
		     * Now merge in each use entry in the proper
		     * (reverse) order.
		     */
		    for (; qp->nuses; qp->nuses--)
			_nc_merge_entry(&merged,
					&qp->uses[qp->nuses - 1].link->tterm);

		    /*
		     * Now merge in the original entry.
		     */
		    _nc_merge_entry(&merged, &qp->tterm);

		    /*
		     * Replace the original entry with the merged one.
		     */
		    FreeIfNeeded(qp->tterm.Booleans);
		    FreeIfNeeded(qp->tterm.Numbers);
		    FreeIfNeeded(qp->tterm.Strings);
#if NCURSES_XNAMES
		    FreeIfNeeded(qp->tterm.ext_Names);
#endif
		    qp->tterm = merged;
		    _nc_wrap_entry(qp, TRUE);

		    /*
		     * We know every entry is resolvable because name resolution
		     * didn't bomb.  So go back for another pass.
		     */
		    /* FALLTHRU */
		  incomplete:
		    keepgoing = TRUE;
		}
	    }
	} while
	    (keepgoing);

	DEBUG(2, ("MERGES COMPLETED OK"));
    }

    /*
     * We'd like to free entries read in off disk at this point, but can't.
     * The merge_entry() code doesn't copy the strings in the use entries,
     * it just aliases them.  If this ever changes, do a
     * free_entries(lastread) here.
     */

    DEBUG(2, ("RESOLUTION FINISHED"));

    if (fullresolve)
	if (_nc_check_termtype != 0) {
	    _nc_curr_col = -1;
	    for_entry_list(qp) {
		_nc_curr_line = qp->startline;
		_nc_set_type(_nc_first_name(qp->tterm.term_names));
		_nc_check_termtype2(&qp->tterm, literal);
	    }
	    DEBUG(2, ("SANITY CHECK FINISHED"));
	}
示例#16
0
int main( int argc, char **argv, char **envp )
{
	char buf[ 1024 ];
	FILE *fin;
	FILE *fout;
	char *p;
	int doDotC = 0;

	if( argc < 3 )
	{
	    fprintf( stderr, "usage: %s jambase.c Jambase ...\n", argv[0] );
	    return -1;
	}

	if( !( fout = fopen( argv[1], "w" ) ) )
	{
	    perror( argv[1] );
	    return -1;
	}

	/* If the file ends in .c generate a C source file */

	if( ( p = strrchr( argv[1], '.' ) ) && !strcmp( p, ".c" ) )
	    doDotC++;

	/* Now process the files */

	argc -= 2, argv += 2;

	if( doDotC )
	{
	    fprintf( fout, "/* Generated by mkjambase from Jambase */\n" );
	    fprintf( fout, "char *jambase[] = {\n" );
	}

	for( ; argc--; argv++ )
	{
	    if( !( fin = fopen( *argv, "r" ) ) )
	    {
		perror( *argv );
		return -1;
	    }

	    if( doDotC )
	    {
		fprintf( fout, "/* %s */\n", *argv );
	    }
	    else
	    {
		fprintf( fout, "### %s ###\n", *argv );
	    }

	    while( fgets( buf, sizeof( buf ), fin ) )
	    {
		if( doDotC )
		{
		    char *p = buf;

		    /* Strip leading whitespace. */

		    while( *p == ' ' || *p == '\t' || *p == '\n' )
			p++;

		    /* Drop comments and empty lines. */

		    if( *p == '#' || !*p )
			continue;

		    /* Copy */

		    putc( '"', fout );

		    for( ; *p && *p != '\n'; p++ )
			switch( *p )
		    {
		    case '\\': putc( '\\', fout ); putc( '\\', fout ); break;
		    case '"': putc( '\\', fout ); putc( '"', fout ); break;
                    case '\r': break;
		    default: putc( *p, fout ); break;
		    }

		    fprintf( fout, "\\n\",\n" );
		}
		else
		{
		    fprintf( fout, "%s", buf );
		}

	    }

	    fclose( fin );
	}
	    
	if( doDotC )
	    fprintf( fout, "0 };\n" );

	fclose( fout );

	return 0;
}
示例#17
0
FT_Error
TA_sfnt_build_glyph_instructions(SFNT* sfnt,
                                 FONT* font,
                                 FT_Long idx)
{
  FT_Face face = sfnt->face;
  FT_Error error;

  FT_Byte* ins_buf;
  FT_UInt ins_len;
  FT_Byte* bufp;
  FT_Byte* p;

  SFNT_Table* glyf_table = &font->tables[sfnt->glyf_idx];
  glyf_Data* data = (glyf_Data*)glyf_table->data;
  /* `idx' is never negative */
  GLYPH* glyph = &data->glyphs[idx];

  TA_GlyphHints hints;

  FT_UInt num_hints_records;
  Hints_Record* hints_records;

  Recorder recorder;

  FT_Int32 load_flags;
  FT_UInt size;


  /* XXX: right now, we abuse this flag to control */
  /*      the global behaviour of the auto-hinter */
  load_flags = font->fallback_script << 30;
  load_flags |= 1 << 28; /* vertical hinting only */
  if (font->increase_x_height)
    load_flags |= 1 << 29;
  if (!font->pre_hinting)
    load_flags |= FT_LOAD_NO_SCALE;

  /* computing the segments is resolution independent, */
  /* thus the pixel size in this call is arbitrary */
  error = FT_Set_Pixel_Sizes(face, 20, 20);
  if (error)
    return error;

  ta_loader_register_hints_recorder(font->loader, NULL, NULL);
  error = ta_loader_load_glyph(font->loader, face, (FT_UInt)idx, load_flags);
  if (error)
    return error;

  /* do nothing if we have an empty glyph */
  if (!face->glyph->outline.n_contours)
    return FT_Err_Ok;

  hints = &font->loader->hints;

  /* do nothing if the setup delivered the dummy module only */
  if (!hints->num_points)
    return FT_Err_Ok;

  /* we allocate a buffer which is certainly large enough */
  /* to hold all of the created bytecode instructions; */
  /* later on it gets reallocated to its real size */
  ins_len = hints->num_points * 1000;
  ins_buf = (FT_Byte*)malloc(ins_len);
  if (!ins_buf)
    return FT_Err_Out_Of_Memory;

  /* initialize array with an invalid bytecode */
  /* so that we can easily find the array length at reallocation time */
  memset(ins_buf, INS_A0, ins_len);

  num_hints_records = 0;
  hints_records = NULL;

  /* handle composite glyph */
  if (font->loader->gloader->base.num_subglyphs)
  {
    bufp = TA_font_build_subglyph_shifter(font, ins_buf);
    if (!bufp)
    {
      error = FT_Err_Out_Of_Memory;
      goto Err;
    }

    goto Done1;
  }

  /* only scale the glyph if the dummy hinter has been used */
  if (font->loader->metrics->clazz == &ta_dummy_script_class)
  {
    /* since `TA_init_recorder' hasn't been called yet, */
    /* we manually initialize the `glyph' field */
    recorder.glyph = glyph;

    bufp = TA_sfnt_build_glyph_scaler(sfnt, &recorder, ins_buf);
    if (!bufp)
    {
      error = FT_Err_Out_Of_Memory;
      goto Err;
    }

    goto Done1;
  }

  error = TA_init_recorder(&recorder, face->glyph->outline.n_contours,
                           font, glyph, hints);
  if (error)
    goto Err;

  bufp = TA_sfnt_build_glyph_segments(sfnt, &recorder, ins_buf);
  if (!bufp)
  {
    error = FT_Err_Out_Of_Memory;
    goto Err;
  }

  /* now we loop over a large range of pixel sizes */
  /* to find hints records which get pushed onto the bytecode stack */

#ifdef DEBUGGING
  {
    int num_chars, i;


    num_chars = fprintf(stderr, "glyph %ld\n", idx);
    for (i = 0; i < num_chars - 1; i++)
      putc('=', stderr);
    fprintf(stderr, "\n\n");

  }
#endif

  /* we temporarily use `ins_buf' to record the current glyph hints, */
  /* leaving two bytes at the beginning so that the number of actions */
  /* can be inserted later on */
  ta_loader_register_hints_recorder(font->loader,
                                    TA_hints_recorder,
                                    (void*)&recorder);

  for (size = font->hinting_range_min;
       size <= font->hinting_range_max;
       size++)
  {
    TA_rewind_recorder(&recorder, bufp, size);

    error = FT_Set_Pixel_Sizes(face, size, size);
    if (error)
      goto Err;

    /* calling `ta_loader_load_glyph' uses the */
    /* `TA_hints_recorder' function as a callback, */
    /* modifying `hints_record' */
    error = ta_loader_load_glyph(font->loader, face, idx, load_flags);
    if (error)
      goto Err;

    /* append the point hints data collected in `TA_hints_recorder' */
    TA_build_point_hints(&recorder, hints);

    /* store the number of actions in `ins_buf' */
    *bufp = HIGH(recorder.hints_record.num_actions);
    *(bufp + 1) = LOW(recorder.hints_record.num_actions);

    if (TA_hints_record_is_different(hints_records,
                                     num_hints_records,
                                     bufp, recorder.hints_record.buf))
    {
#ifdef DEBUGGING
      {
        fprintf(stderr, "  size %d:\n", size);

        ta_glyph_hints_dump_edges(_ta_debug_hints);
        ta_glyph_hints_dump_segments(_ta_debug_hints);
        ta_glyph_hints_dump_points(_ta_debug_hints);

        fprintf(stderr, "  hints record:\n");
        for (p = bufp; p < recorder.hints_record.buf; p += 2)
          fprintf(stderr, " %2d", *p * 256 + *(p + 1));
        fprintf(stderr, "\n");
      }
#endif

      error = TA_add_hints_record(&hints_records,
                                  &num_hints_records,
                                  bufp, recorder.hints_record);
      if (error)
        goto Err;
    }
  }

  if (num_hints_records == 1 && !hints_records[0].num_actions)
  {
    /* since we only have a single empty record we just scale the glyph, */
    /* overwriting the data from `TA_sfnt_build_glyph_segments' */
    bufp = TA_sfnt_build_glyph_scaler(sfnt, &recorder, ins_buf);
    if (!bufp)
    {
      error = FT_Err_Out_Of_Memory;
      goto Err;
    }

    /* clear the rest of the temporarily used part of `ins_buf' */
    p = bufp;
    while (*p != INS_A0)
      *(p++) = INS_A0;

    goto Done;
  }

  /* in most cases, the output of `TA_sfnt_build_glyph_segments' */
  /* is shorter than the previously stored data, */
  /* so clear the rest of the temporarily used part of `ins_buf' */
  /* before appending the hints records */
  p = bufp;
  while (*p != INS_A0)
    *(p++) = INS_A0;

  bufp = TA_sfnt_emit_hints_records(sfnt,
                                    hints_records, num_hints_records,
                                    bufp);

Done:
  TA_free_hints_records(hints_records, num_hints_records);
  TA_free_recorder(&recorder);

  /* we are done, so reallocate the instruction array to its real size */
  if (*bufp == INS_A0)
  {
    /* search backwards */
    while (*bufp == INS_A0)
      bufp--;
    bufp++;
  }
  else
  {
    /* search forwards */
    while (*bufp != INS_A0)
      bufp++;
  }

Done1:
  ins_len = bufp - ins_buf;

  if (ins_len > sfnt->max_instructions)
    sfnt->max_instructions = ins_len;

  glyph->ins_buf = (FT_Byte*)realloc(ins_buf, ins_len);
  glyph->ins_len = ins_len;

  return FT_Err_Ok;

Err:
  TA_free_hints_records(hints_records, num_hints_records);
  TA_free_recorder(&recorder);
  free(ins_buf);

  return error;
}
示例#18
0
unsigned long
decompress_kernel(unsigned long load_addr, int num_words, unsigned long cksum, RESIDUAL *residual)
{
	int timer;
	extern unsigned long start;
	char *cp, ch;
	unsigned long i, motorola_id = 0;
	char needs_reloc = 0;
	BATU *u;
	BATL *l;
	char	*dp;

	lines = 25;
	cols = 80;
	orig_x = 0;
	orig_y = 24;

	/* Grab some space for the command line and board info.  Since
	 * we no longer use the ELF header, but it was loaded, grab
	 * that space.
	 */
	cmd_line = (char *)(load_addr - 0x10000);
	hold_residual = (RESIDUAL *)(cmd_line + sizeof(cmd_buf));
	/* copy board data */
	if (residual)
		memcpy(hold_residual,residual,sizeof(bd_t));

	/* MBX/prep sometimes put the residual/board info at the end of mem 
	 * assume 16M for now  -- Cort
	 * To boot on standard MBX boards with 4M, we can't use initrd,
	 * and we have to assume less memory.  -- Dan
	 */
	if ( INITRD_OFFSET )
		end_avail = (char *)0x01000000;
	else
		end_avail = (char *)0x00400000;

	/* let residual data tell us it's higher */
	if ( (unsigned long)residual > 0x00800000 )
		end_avail = (char *)PAGE_ALIGN((unsigned long)residual);

	puts("loaded at:     "); puthex(load_addr);
	puts(" "); puthex((unsigned long)(load_addr + (4*num_words))); puts("\n");
	if ( (unsigned long)load_addr != (unsigned long)&start )
	{
		puts("relocated to:  "); puthex((unsigned long)&start);
		puts(" ");
		puthex((unsigned long)((unsigned long)&start + (4*num_words)));
		puts("\n");
	}

	if ( residual )
	{
		puts("board data at: "); puthex((unsigned long)residual);
		puts(" ");
		puthex((unsigned long)((unsigned long)residual + sizeof(bd_t)));
		puts("\n");
		puts("relocated to:  ");
		puthex((unsigned long)hold_residual);
		puts(" ");
		puthex((unsigned long)((unsigned long)hold_residual + sizeof(bd_t)));
		puts("\n");
	}

	/* we have to subtract 0x10000 here to correct for objdump including the
	   size of the elf header which we strip -- Cort */
	zimage_start = (char *)(load_addr - 0x10000 + ZIMAGE_OFFSET);
	zimage_size = ZIMAGE_SIZE;

	if ( INITRD_OFFSET )
		initrd_start = load_addr - 0x10000 + INITRD_OFFSET;
	else
		initrd_start = 0;
	initrd_end = INITRD_SIZE + initrd_start;

	/*
	 * setup avail_ram - this is the first part of ram usable
	 * by the uncompress code. -- Cort
	 */
	avail_ram = (char *)PAGE_ALIGN((unsigned long)zimage_start+zimage_size);
	if ( ((load_addr+(num_words*4)) > (unsigned long) avail_ram)
		&& (load_addr <= 0x01000000) )
		avail_ram = (char *)(load_addr+(num_words*4));
	if ( (((unsigned long)&start+(num_words*4)) > (unsigned long) avail_ram)
		&& (load_addr <= 0x01000000) )
		avail_ram = (char *)((unsigned long)&start+(num_words*4));
	
	/* relocate zimage */
	puts("zimage at:     "); puthex((unsigned long)zimage_start);
	puts(" "); puthex((unsigned long)(zimage_size+zimage_start)); puts("\n");
	/*
	 * don't relocate the zimage if it was loaded above 16M since
	 * things get weird if we try to relocate -- Cort
	 * We don't relocate zimage on a base MBX board because of
	 * insufficient memory.  In this case we don't have initrd either,
	 * so use that as an indicator.  -- Dan
	 */
	
	/* Determine if we have a Motorola board */
	needs_reloc = 0;
	if ( (( (unsigned long)zimage_start <= 0x01000000 ) && initrd_start)
		|| needs_reloc)
	{
		memcpy ((void *)PAGE_ALIGN(-PAGE_SIZE+(unsigned long)end_avail-zimage_size),
			(void *)zimage_start, zimage_size );	
		zimage_start = (char *)PAGE_ALIGN(-PAGE_SIZE+(unsigned long)end_avail-zimage_size);
		end_avail = (char *)zimage_start;
		puts("relocated to:  "); puthex((unsigned long)zimage_start);
		puts(" ");
		puthex((unsigned long)zimage_size+(unsigned long)zimage_start);
		puts("\n");
	}

	/* relocate initrd */
	if ( initrd_start )
	{
		puts("initrd at:     "); puthex(initrd_start);
		puts(" "); puthex(initrd_end); puts("\n");
		/*
		 * Memory is really tight on the MBX (we can assume 4M)
		 * so put the initrd at the TOP of ram, and set end_avail
		 * to right after that.
		 *
		 * I should do something like this for prep, too and keep
		 * a variable end_of_DRAM to keep track of what we think the
		 * max ram is.
		 * -- Cort
		 */
		if (needs_reloc)
		{
			memcpy ((void *)PAGE_ALIGN(-PAGE_SIZE+
				(unsigned long)end_avail-INITRD_SIZE),
				(void *)initrd_start,
				INITRD_SIZE );
			initrd_start = PAGE_ALIGN(-PAGE_SIZE+
				(unsigned long)end_avail-INITRD_SIZE);
			initrd_end = initrd_start + INITRD_SIZE;
			end_avail = (char *)initrd_start;
			puts("relocated to:  "); puthex(initrd_start);
			puts(" "); puthex(initrd_end); puts("\n");
		}
	}

	puts("avail ram:     "); puthex((unsigned long)avail_ram); puts(" ");
	puthex((unsigned long)end_avail); puts("\n");

	puts("\nLinux/PPC load: ");
	timer = 0;
	cp = cmd_line;
	memcpy (cmd_line, cmd_preset, sizeof(cmd_preset));
	while ( *cp ) putc(*cp++);
	while (timer++ < 5*1000) {
		if (tstc()) {
			while ((ch = getc()) != '\n' && ch != '\r') {
				if (ch == '\b') {
					if (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				  } else if (ch == '?') {
					if (!do_ipaddrs(&cp, 1)) {
						  *cp++ = ch;
						  putc(ch);
					}
				} else {
					*cp++ = ch;
					putc(ch);
				}
			}
			break;  /* Exit 'timer' loop */
		}
		udelay(1000);  /* 1 msec */
	}
	*cp = 0;
	/* The MBX does not currently have any default boot strategy.
	 * If the command line is not filled in, we will automatically
	 * create the default network boot.
	 */
	if (cmd_line[0] == 0) {
		dp = root_string;
		while (*dp != 0)
			*cp++ = *dp++;
		*cp++ = ' ';

		dp = nfsaddrs_string;
		while (*dp != 0)
			*cp++ = *dp++;
		dp = cp;
		do_ipaddrs(&cp, 0);
		*cp++ = ' ';

		/* Add the server address to the root file system path.
		*/
		dp = strrchr(dp, ':');
		dp++;
		do_nfsroot(&cp, dp);
		*cp = 0;
	}
	puts("\n");

	/* mappings on early boot can only handle 16M */
	if ( (int)(cmd_line[0]) > (16<<20))
		puts("cmd_line located > 16M\n");
	if ( (int)hold_residual > (16<<20))
		puts("hold_residual located > 16M\n");
	if ( initrd_start > (16<<20))
		puts("initrd_start located > 16M\n");
       
	puts("Uncompressing Linux...");

	gunzip(0, 0x400000, zimage_start, &zimage_size);
	puts("done.\n");
	puts("Now booting the kernel\n");
	return (unsigned long)hold_residual;
}
			virtual void puts(const _Elem* str,streamsize size){
				for(std::streamsize i=0;i<size;i++)putc(str[i]);
			}
示例#20
0
int
do_ipaddrs(char **cmd_cp, int echo)
{
	char	*cp, *ip, ch;
	unsigned char	ipd;
	int	i, j, retval;

	/* We need to create the string:
	 *	<my_ip>:<serv_ip>
	 */
	cp = *cmd_cp;
	retval = 0;

	if ((cp - 9) >= cmd_line) {
		if (strncmp(cp - 9, "nfsaddrs=", 9) == 0) {
			ip = (char *)0xfa000060;
			retval = 1;
			for (j=0; j<2; j++) {
				for (i=0; i<4; i++) {
					ipd = *ip++;

					ch = ipd/100;
					if (ch) {
						ch += '0';
						if (echo)
							putc(ch);
						*cp++ = ch;
						ipd -= 100 * (ch - '0');
					}

					ch = ipd/10;
					if (ch) {
						ch += '0';
						if (echo)
							putc(ch);
						*cp++ = ch;
						ipd -= 10 * (ch - '0');
					}

					ch = ipd + '0';
					if (echo)
						putc(ch);
					*cp++ = ch;

					ch = '.';
					if (echo)
						putc(ch);
					*cp++ = ch;
				}

				/* At the end of the string, remove the
				 * '.' and replace it with a ':'.
				 */
				*(cp - 1) = ':';
				if (echo) {
					putc('\b'); putc(':');
				}
			}

			/* At the end of the second string, remove the
			 * '.' from both the command line and the
			 * screen.
			 */
			--cp;
			putc('\b'); putc(' '); putc('\b');
		}
	}
	*cmd_cp = cp;
	return(retval);
}
示例#21
0
int main(int argc, char **argv) {
    int frame_cnt = 0;
    FILE *outfile = NULL;
    vpx_codec_ctx_t codec;
    const VpxInterface *decoder = NULL;
    VpxVideoReader *reader = NULL;
    const VpxVideoInfo *info = NULL;
    int n = 0;
    int m = 0;
    int is_range = 0;
    char *nptr = NULL;

    exec_name = argv[0];

    if (argc != 4)
        die("Invalid number of arguments.");

    reader = vpx_video_reader_open(argv[1]);
    if (!reader)
        die("Failed to open %s for reading.", argv[1]);

    if (!(outfile = fopen(argv[2], "wb")))
        die("Failed to open %s for writing.", argv[2]);

    n = strtol(argv[3], &nptr, 0);
    m = strtol(nptr + 1, NULL, 0);
    is_range = (*nptr == '-');
    if (!n || !m || (*nptr != '-' && *nptr != '/'))
        die("Couldn't parse pattern %s.\n", argv[3]);

    info = vpx_video_reader_get_info(reader);

    decoder = get_vpx_decoder_by_fourcc(info->codec_fourcc);
    if (!decoder)
        die("Unknown input codec.");

    printf("Using %s\n", vpx_codec_iface_name(decoder->codec_interface()));

    if (vpx_codec_dec_init(&codec, decoder->codec_interface(), NULL, 0))
        die_codec(&codec, "Failed to initialize decoder.");

    while (vpx_video_reader_read_frame(reader)) {
        vpx_codec_iter_t iter = NULL;
        vpx_image_t *img = NULL;
        size_t frame_size = 0;
        int skip;
        const unsigned char *frame = vpx_video_reader_get_frame(reader,
                                     &frame_size);
        if (vpx_codec_decode(&codec, frame, (unsigned int)frame_size, NULL, 0))
            die_codec(&codec, "Failed to decode frame.");

        ++frame_cnt;

        skip = (is_range && frame_cnt >= n && frame_cnt <= m) ||
               (!is_range && m - (frame_cnt - 1) % m <= n);

        if (!skip) {
            putc('.', stdout);

            while ((img = vpx_codec_get_frame(&codec, &iter)) != NULL)
                vpx_img_write(img, outfile);
        } else {
            putc('X', stdout);
        }

        fflush(stdout);
    }

    printf("Processed %d frames.\n", frame_cnt);
    if (vpx_codec_destroy(&codec))
        die_codec(&codec, "Failed to destroy codec.");

    printf("Play: ffplay -f rawvideo -pix_fmt yuv420p -s %dx%d %s\n",
           info->frame_width, info->frame_height, argv[2]);

    vpx_video_reader_close(reader);
    fclose(outfile);

    return EXIT_SUCCESS;
}
示例#22
0
int checkcpu (void)
{
#if !defined(CONFIG_405)	/* not used on Xilinx 405 FPGA implementations */
	uint pvr = get_pvr();
	ulong clock = gd->cpu_clk;
	char buf[32];
#if defined(CONFIG_460EX) || defined(CONFIG_460GT)
	u32 reg;
#endif

#if !defined(CONFIG_IOP480)
	char addstr[64] = "";
	sys_info_t sys_info;
	int cpu_num;

	cpu_num = get_cpu_num();
	if (cpu_num >= 0)
		printf("CPU%d:  ", cpu_num);
	else
		puts("CPU:   ");

	get_sys_info(&sys_info);

#if defined(CONFIG_XILINX_440)
	puts("IBM PowerPC 4");
#else
	puts("AMCC PowerPC 4");
#endif

#if defined(CONFIG_405GP) || defined(CONFIG_405CR) || \
    defined(CONFIG_405EP) || defined(CONFIG_405EZ) || \
    defined(CONFIG_405EX)
	puts("05");
#endif
#if defined(CONFIG_440)
#if defined(CONFIG_460EX) || defined(CONFIG_460GT)
	puts("60");
#else
	puts("40");
#endif
#endif

	switch (pvr) {
	case PVR_405GP_RB:
		puts("GP Rev. B");
		break;

	case PVR_405GP_RC:
		puts("GP Rev. C");
		break;

	case PVR_405GP_RD:
		puts("GP Rev. D");
		break;

#ifdef CONFIG_405GP
	case PVR_405GP_RE: /* 405GP rev E and 405CR rev C have same PVR */
		puts("GP Rev. E");
		break;
#endif

	case PVR_405CR_RA:
		puts("CR Rev. A");
		break;

	case PVR_405CR_RB:
		puts("CR Rev. B");
		break;

#ifdef CONFIG_405CR
	case PVR_405CR_RC: /* 405GP rev E and 405CR rev C have same PVR */
		puts("CR Rev. C");
		break;
#endif

	case PVR_405GPR_RB:
		puts("GPr Rev. B");
		break;

	case PVR_405EP_RB:
		puts("EP Rev. B");
		break;

	case PVR_405EZ_RA:
		puts("EZ Rev. A");
		break;

	case PVR_405EX1_RA:
		puts("EX Rev. A");
		strcpy(addstr, "Security support");
		break;

	case PVR_405EXR2_RA:
		puts("EXr Rev. A");
		strcpy(addstr, "No Security support");
		break;

	case PVR_405EX1_RC:
		puts("EX Rev. C");
		strcpy(addstr, "Security support");
		break;

	case PVR_405EX2_RC:
		puts("EX Rev. C");
		strcpy(addstr, "No Security support");
		break;

	case PVR_405EXR1_RC:
		puts("EXr Rev. C");
		strcpy(addstr, "Security support");
		break;

	case PVR_405EXR2_RC:
		puts("EXr Rev. C");
		strcpy(addstr, "No Security support");
		break;

	case PVR_405EX1_RD:
		puts("EX Rev. D");
		strcpy(addstr, "Security support");
		break;

	case PVR_405EX2_RD:
		puts("EX Rev. D");
		strcpy(addstr, "No Security support");
		break;

	case PVR_405EXR1_RD:
		puts("EXr Rev. D");
		strcpy(addstr, "Security support");
		break;

	case PVR_405EXR2_RD:
		puts("EXr Rev. D");
		strcpy(addstr, "No Security support");
		break;

#if defined(CONFIG_440)
	case PVR_440GP_RB:
		puts("GP Rev. B");
		/* See errata 1.12: CHIP_4 */
		if ((mfdcr(CPC0_SYS0) != mfdcr(CPC0_STRP0)) ||
		    (mfdcr(CPC0_SYS1) != mfdcr(CPC0_STRP1)) ){
			puts (  "\n\t CPC0_SYSx DCRs corrupted. "
				"Resetting chip ...\n");
			udelay( 1000 * 1000 ); /* Give time for serial buf to clear */
			do_chip_reset ( mfdcr(CPC0_STRP0),
					mfdcr(CPC0_STRP1) );
		}
		break;

	case PVR_440GP_RC:
		puts("GP Rev. C");
		break;

	case PVR_440GX_RA:
		puts("GX Rev. A");
		break;

	case PVR_440GX_RB:
		puts("GX Rev. B");
		break;

	case PVR_440GX_RC:
		puts("GX Rev. C");
		break;

	case PVR_440GX_RF:
		puts("GX Rev. F");
		break;

	case PVR_440EP_RA:
		puts("EP Rev. A");
		break;

#ifdef CONFIG_440EP
	case PVR_440EP_RB: /* 440EP rev B and 440GR rev A have same PVR */
		puts("EP Rev. B");
		break;

	case PVR_440EP_RC: /* 440EP rev C and 440GR rev B have same PVR */
		puts("EP Rev. C");
		break;
#endif /*  CONFIG_440EP */

#ifdef CONFIG_440GR
	case PVR_440GR_RA: /* 440EP rev B and 440GR rev A have same PVR */
		puts("GR Rev. A");
		break;

	case PVR_440GR_RB: /* 440EP rev C and 440GR rev B have same PVR */
		puts("GR Rev. B");
		break;
#endif /* CONFIG_440GR */
#endif /* CONFIG_440 */

#ifdef CONFIG_440EPX
	case PVR_440EPX1_RA: /* 440EPx rev A and 440GRx rev A have same PVR */
		puts("EPx Rev. A");
		strcpy(addstr, "Security/Kasumi support");
		break;

	case PVR_440EPX2_RA: /* 440EPx rev A and 440GRx rev A have same PVR */
		puts("EPx Rev. A");
		strcpy(addstr, "No Security/Kasumi support");
		break;
#endif /* CONFIG_440EPX */

#ifdef CONFIG_440GRX
	case PVR_440GRX1_RA: /* 440EPx rev A and 440GRx rev A have same PVR */
		puts("GRx Rev. A");
		strcpy(addstr, "Security/Kasumi support");
		break;

	case PVR_440GRX2_RA: /* 440EPx rev A and 440GRx rev A have same PVR */
		puts("GRx Rev. A");
		strcpy(addstr, "No Security/Kasumi support");
		break;
#endif /* CONFIG_440GRX */

	case PVR_440SP_6_RAB:
		puts("SP Rev. A/B");
		strcpy(addstr, "RAID 6 support");
		break;

	case PVR_440SP_RAB:
		puts("SP Rev. A/B");
		strcpy(addstr, "No RAID 6 support");
		break;

	case PVR_440SP_6_RC:
		puts("SP Rev. C");
		strcpy(addstr, "RAID 6 support");
		break;

	case PVR_440SP_RC:
		puts("SP Rev. C");
		strcpy(addstr, "No RAID 6 support");
		break;

	case PVR_440SPe_6_RA:
		puts("SPe Rev. A");
		strcpy(addstr, "RAID 6 support");
		break;

	case PVR_440SPe_RA:
		puts("SPe Rev. A");
		strcpy(addstr, "No RAID 6 support");
		break;

	case PVR_440SPe_6_RB:
		puts("SPe Rev. B");
		strcpy(addstr, "RAID 6 support");
		break;

	case PVR_440SPe_RB:
		puts("SPe Rev. B");
		strcpy(addstr, "No RAID 6 support");
		break;

#if defined(CONFIG_460EX) || defined(CONFIG_460GT)
	case PVR_460EX_RA:
		puts("EX Rev. A");
		strcpy(addstr, "No Security/Kasumi support");
		break;

	case PVR_460EX_SE_RA:
		puts("EX Rev. A");
		strcpy(addstr, "Security/Kasumi support");
		break;

	case PVR_460EX_RB:
		puts("EX Rev. B");
		mfsdr(SDR0_ECID3, reg);
		if (reg & 0x00100000)
			strcpy(addstr, "No Security/Kasumi support");
		else
			strcpy(addstr, "Security/Kasumi support");
		break;

	case PVR_460GT_RA:
		puts("GT Rev. A");
		strcpy(addstr, "No Security/Kasumi support");
		break;

	case PVR_460GT_SE_RA:
		puts("GT Rev. A");
		strcpy(addstr, "Security/Kasumi support");
		break;

	case PVR_460GT_RB:
		puts("GT Rev. B");
		mfsdr(SDR0_ECID3, reg);
		if (reg & 0x00100000)
			strcpy(addstr, "No Security/Kasumi support");
		else
			strcpy(addstr, "Security/Kasumi support");
		break;
#endif

	case PVR_460SX_RA:
		puts("SX Rev. A");
		strcpy(addstr, "Security support");
		break;

	case PVR_460SX_RA_V1:
		puts("SX Rev. A");
		strcpy(addstr, "No Security support");
		break;

	case PVR_460GX_RA:
		puts("GX Rev. A");
		strcpy(addstr, "Security support");
		break;

	case PVR_460GX_RA_V1:
		puts("GX Rev. A");
		strcpy(addstr, "No Security support");
		break;

	case PVR_VIRTEX5:
		puts("x5 VIRTEX5");
		break;

	default:
		printf (" UNKNOWN (PVR=%08x)", pvr);
		break;
	}

	printf (" at %s MHz (PLB=%lu OPB=%lu EBC=%lu",
		strmhz(buf, clock),
		sys_info.freqPLB / 1000000,
		get_OPB_freq() / 1000000,
		sys_info.freqEBC / 1000000);
#if defined(CONFIG_PCI) && \
	(defined(CONFIG_440EP) || defined(CONFIG_440EPX) || \
	 defined(CONFIG_440GR) || defined(CONFIG_440GRX))
	printf(" PCI=%lu MHz", sys_info.freqPCI / 1000000);
#endif
	printf(")\n");

	if (addstr[0] != 0)
		printf("       %s\n", addstr);

#if defined(I2C_BOOTROM)
	printf ("       I2C boot EEPROM %sabled\n", i2c_bootrom_enabled() ? "en" : "dis");
#endif	/* I2C_BOOTROM */
#if defined(SDR0_PINSTP_SHIFT)
	printf ("       Bootstrap Option %c - ", bootstrap_char[bootstrap_option()]);
	printf ("Boot ROM Location %s", bootstrap_str[bootstrap_option()]);
#ifdef CONFIG_NAND_U_BOOT
	puts(", booting from NAND");
#endif /* CONFIG_NAND_U_BOOT */
	putc('\n');
#endif	/* SDR0_PINSTP_SHIFT */

#if defined(CONFIG_PCI) && !defined(CONFIG_405EX)
	printf ("       Internal PCI arbiter %sabled", pci_arbiter_enabled() ? "en" : "dis");
#endif

#if defined(CONFIG_PCI) && defined(PCI_ASYNC)
	if (pci_async_enabled()) {
		printf (", PCI async ext clock used");
	} else {
		printf (", PCI sync clock at %lu MHz",
		       sys_info.freqPLB / sys_info.pllPciDiv / 1000000);
	}
#endif

#if defined(CONFIG_PCI) && !defined(CONFIG_405EX)
	putc('\n');
#endif

#if defined(CONFIG_405EP) || defined(CONFIG_405EZ) || defined(CONFIG_405EX)
	printf ("       16 kB I-Cache 16 kB D-Cache");
#elif defined(CONFIG_440)
	printf ("       32 kB I-Cache 32 kB D-Cache");
#else
	printf ("       16 kB I-Cache %d kB D-Cache",
		((pvr | 0x00000001) == PVR_405GPR_RB) ? 16 : 8);
#endif
#endif /* !defined(CONFIG_IOP480) */

#if defined(CONFIG_IOP480)
	printf ("PLX IOP480 (PVR=%08x)", pvr);
	printf (" at %s MHz:", strmhz(buf, clock));
	printf (" %u kB I-Cache", 4);
	printf (" %u kB D-Cache", 2);
#endif

#endif /* !defined(CONFIG_405) */

	putc ('\n');

	return 0;
}
示例#23
0
文件: git_id.cpp 项目: Coltage/mangos
bool convert_sql_updates()
{
    if(new_sql_updates.empty()) return true;

    printf("+ converting sql updates\n");

    // rename the sql update files and add the required update statement
    for(std::set<std::string>::iterator itr = new_sql_updates.begin(); itr != new_sql_updates.end(); ++itr)
    {
        sql_update_info info;
        if(!get_sql_update_info(itr->c_str(), info)) return false;
        if(info.db_idx == NUM_DATABASES) return false;

        // generating the new name should work for updates with or without a rev
        char src_file[MAX_PATH], new_name[MAX_PATH], dst_file[MAX_PATH];
        snprintf(src_file, MAX_PATH, "%s%s/%s", path_prefix, sql_update_dir, itr->c_str());
        snprintf(new_name, MAX_PATH, "%d_%0*d_%s%s%s", rev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
        snprintf(dst_file, MAX_PATH, "%s%s/%s.sql", path_prefix, sql_update_dir, new_name);

        FILE * fin = fopen( src_file, "r" );
        if(!fin) return false;
        FILE * fout = fopen( dst_file, "w" );
        if(!fout) { fclose(fin); return false; }

        // add the update requirements
        fprintf(fout, "ALTER TABLE %s CHANGE COLUMN required_%s required_%s bit;\n\n",
            db_version_table[info.db_idx], last_sql_update[info.db_idx], new_name);

        // skip the first one or two lines from the input
        // if it already contains update requirements
        if(fgets(buffer, MAX_BUF, fin))
        {
            char dummy[MAX_BUF];
            if(sscanf(buffer, "ALTER TABLE %s CHANGE COLUMN required_%s required_%s bit", dummy, dummy, dummy) == 3)
            {
                if(fgets(buffer, MAX_BUF, fin) && buffer[0] != '\n')
                    fputs(buffer, fout);
            }
            else
                fputs(buffer, fout);
        }

        // copy the rest of the file
        char c;
        while( (c = getc(fin)) != EOF )
            putc(c, fout);

        fclose(fin);
        fclose(fout);

        // rename the file in git
        snprintf(cmd, MAX_CMD, "git add %s", dst_file);
        system_switch_index(cmd);
        snprintf(cmd, MAX_CMD, "git rm --quiet %s", src_file);
        system_switch_index(cmd);

        // update the last sql update for the current database
        strncpy(last_sql_update[info.db_idx], new_name, MAX_PATH);
    }

    return true;
}
示例#24
0
文件: init.c 项目: TijmenW/FreeDOS
int initialize(void)
{
  int comPath;                /* path to COMMAND.COM (for COMSPEC/reload) */
  char *newTTY;                 /* what to change TTY to */
  int showinfo;                 /* show initial info only if no command line options */
  int key;

  int ec;           /* error code */
  unsigned offs;        /* offset into environment segment */

  int cmdlen;         /* length of command line */
  char *cmdline;        /* command line duplicated into heap */
  char *p, *h, *q;
#ifdef FEATURE_CALL_LOGGING
  FILE *f;
#endif

/* Set up the host environment of COMMAND.COM */

  /* Install the ^Break handler (see chkCBreak() for more details) */
  extern void initCBreakCatcher(void);
  initCBreakCatcher();

  /* Install INT 24 Critical error handler */
  init_error_handler();

  /* DOS shells patch the PPID to the own PID, how stupid this is, however,
    because then DOS won't terminate them, e.g. when a Critical Error
    occurs that is not detected by COMMAND.COM */

  oldPSP = OwnerPSP;
  atexit(exitfct);
  OwnerPSP = _psp;

  /* Some elder DOSs may not pass an initialzied environment segment */
  if (env_glbSeg && !isMCB(SEG2MCB(env_glbSeg)))
    env_setGlbSeg(0);       /* Disable the environment */

/* Now parse the command line parameters passed to COMMAND.COM */
  /* Preparations */
  newTTY = NULL;
  comPath = tracemode = 0;
  showinfo = 1;

  /* Because FreeCom should be executed in a DOS3+ compatible
    environment most of the time, it is assumed that its path
    can be determined from the environment.
    This has the advantage that the string area is accessable
    very early in the run.
    The name of the current file is string #0. */
  if((offs = env_string(0, 0)) != 0)    /* OK, environment filled */
    grabComFilename(0, (char far *)MK_FP(env_glbSeg, offs));

  /* Aquire the command line, there are three possible sources:
    1) DOS command line @PSP:0x80 as pascal string,
    2) extended DOS command line environment variable CMDLINE,
      if peekb(PSP, 0x80) == 127,&
    3) MKS command line @ENV:2, if peekb(ENV, 0) == '~'

    Currently implemented is version #1 only
  */
  cmdlen = peekb(_psp, 0x80);
  if(cmdlen < 0 || cmdlen > 126) {
    error_corrupt_command_line();
    cmdlen = 0;
  }
    /* duplicate the command line into the local address space */
  if((cmdline = malloc(cmdlen + 1)) == NULL) {
    error_out_of_memory();  /* Cannot recover from this problem */
    return E_NoMem;
  }
  _fmemcpy((char far*)cmdline, MK_FP(_psp, 0x81), cmdlen);
  cmdline[cmdlen] = '\0';
#ifdef FEATURE_CALL_LOGGING
  if((f = fopen(logFilename, "at")) == NULL) {
    fprintf(stderr, "Cannot open logfile: \"%s\"\n", logFilename);
    exit(125);
  }

  putc('"', f);
  if(ComPath)   /* path to command.com already known */
    fputs(ComPath, f);
  putc('"', f);
  putc(':', f);

  fputs(cmdline, f);
  putc('\n', f);
  fclose(f);
#endif

  canexit = 1;
  p = cmdline;    /* start of the command line */
  do {
  ec = leadOptions(&p, opt_init, NULL);
  if(ec == E_NoOption) {    /* /C or /K */
    assert(p && *p);
    if(!isoption(p)) {
      error_quoted_c_k();
      p = NULL;
      break;
    }
    assert(p[1] && strchr("kKcC", p[1]));
    p += 2;   /* p := start of command line to execute */
    break;
  } else if(ec != E_None) {
        showhelp = 1;
    p = NULL;
    break;
  }

  assert(p && !isoption(p) && !isspace(*p));
  if(!*p) {
    p = NULL;
    break;      /* end of line reached */
  }
  q = unquote(p, h = skip_word(p));
  p = h;      /* Skip this word */
  if(!q) {
    error_out_of_memory();
    p = NULL;
    break;
  }
  if(!comPath) {      /* 1st argument */
    grabComFilename(1, (char far*)q);
    comPath = 1;
    free(q);
  } else if(!newTTY) {  /* 2nd argument */
#ifdef INCLUDE_CMD_CTTY
    newTTY = q;
#else
      error_ctty_excluded();
    free(q);
#endif
      } else {
        error_too_many_parameters(q);
        showhelp = 1;
        free(q);
        break;
      }
   } while(1);

   /*
    * Now:
    * + autoexec: AUTOEXEC.BAT file to be executed if /P switch
    *   is enabled; if NULL, use default
    * + comPath: user-defined PATH to COMMAND.COM; if NULL, use
    *   the one from the environment
    * + newTTY: the name of the device to be CTTY'ed; if NULL,
    *   no change
    * + p: pointer to the command to be executed:
    *   *p == 'c' or 'C' --> spawn command, then terminate shell
    *   *p == 'k' or 'K' --> spawn command, then go interactive
    *   &p[1] --> command line, unless the first character is an
    *   argument character
    */

/* Now process the options */

#ifdef INCLUDE_CMD_CTTY
  if (newTTY) {                   /* change TTY as early as possible so the caller gets
                                   the messages into the correct channel */
    cmd_ctty(newTTY);
    free(newTTY);
  }
#endif

  if(!ComPath) {
    /* FreeCom is unable to find itself --> print error message */
    /* Emergency error */
    puts("You must specify the complete path to " COM_NAME);
    puts("as the first argument of COMMAND,");
    puts("for instance: C:\\FDOS");
    return E_Useage;
  }

  /* First of all, set up the environment */
  env_resizeCtrl |= ENV_USEUMB | ENV_ALLOWMOVE;
  if (envSize < 0)
    envSize = 32767;        /* Numeric overflow (number > 32767 specified) */
  else if (envSize < 256)
    envSize = 256;          /* Minimum size of 256. */
	if(envSize > env_resize(0, 0))	/* Test if to enlarge environment */
		env_setsize(0, envSize);
    /* Set the COMSPEC variable. */
#if 0
  if (chgEnv("COMSPEC", ComPath)) error_env_var("COMSPEC");
#else
  if (chgEnv("COMSPEC", ComPath)) {
    /* Failed to add this variable, the most likely problem should be that
      the environment is too small --> it is increased and the
      operation is redone */
    env_resize(0, strlen(ComPath) + 10);
    if (chgEnv("COMSPEC", ComPath))
    error_env_var("COMSPEC");
  }
#endif

  if(internalBufLen)
    error_l_notimplemented();
  if(inputBufLen)
    error_u_notimplemented();

  if(tracemode)
    showinfo = 0;

  if (showhelp)
    displayString(TEXT_CMDHELP_COMMAND);

  if ((showhelp || exitflag) && canexit)
    return E_None;

  /* Now the /P option can be processed */
  if (!canexit)
  {
    char *autoexec;

    autoexec = user_autoexec? user_autoexec: AUTO_EXEC;

    showinfo = 0;
    short_version();

    /* JP: changed so that if autoexec does not exist, then don't ask
       to trace or bypass.
     */
    if (exist(autoexec))
    {
      printf("\nPress F8 for trace mode, or F5 to bypass %s... ", autoexec);
      key = WaitForFkeys();
      putchar('\n');

      if (key == KEY_F8)
      {
        tracemode = 1;
      }

      if (key == KEY_F5)
      {
        printf("Bypassing %s\n", autoexec);
      }
      else
        process_input(1, autoexec);
    }
    else
    {
      if(user_autoexec)
        printf("%s not found.\n", autoexec);
#ifdef INCLUDE_CMD_DATE
      cmd_date(NULL);
#endif
#ifdef INCLUDE_CMD_TIME
      cmd_time(NULL);
#endif
    }

    free(user_autoexec);
  }
  else
  {
    assert(user_autoexec == NULL);
  }

  /* Now the /C or /K option can be processed */
  if (p)
  {
    process_input(1, p);
    return spawnAndExit;
  }

  /* Don't place something here that must be executed after a /K or /C */

  if (showinfo)
  {
    short_version();
    putchar('\n');
    showcmds(NULL);
    putchar('\n');
  }

  return E_None;
}
示例#25
0
/*
 * Perform a memory test. A more complete alternative test can be
 * configured using CONFIG_SYS_ALT_MEMTEST. The complete test loops until
 * interrupted by ctrl-c or by a failure of one of the sub-tests.
 */
int do_mem_mtest (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
{
	vu_long	*addr, *start, *end;
	ulong	val;
	ulong	readback;
	ulong	errs = 0;
	int iterations = 1;
	int iteration_limit;

#if defined(CONFIG_SYS_ALT_MEMTEST)
	vu_long	len;
	vu_long	offset;
	vu_long	test_offset;
	vu_long	pattern;
	vu_long	temp;
	vu_long	anti_pattern;
	vu_long	num_words;
#if defined(CONFIG_SYS_MEMTEST_SCRATCH)
	vu_long *dummy = (vu_long*)CONFIG_SYS_MEMTEST_SCRATCH;
#else
	vu_long *dummy = 0;	/* yes, this is address 0x0, not NULL */
#endif
	int	j;

	static const ulong bitpattern[] = {
		0x00000001,	/* single bit */
		0x00000003,	/* two adjacent bits */
		0x00000007,	/* three adjacent bits */
		0x0000000F,	/* four adjacent bits */
		0x00000005,	/* two non-adjacent bits */
		0x00000015,	/* three non-adjacent bits */
		0x00000055,	/* four non-adjacent bits */
		0xaaaaaaaa,	/* alternating 1/0 */
	};
#else
	ulong	incr;
	ulong	pattern;
#endif

	if (argc > 1)
		start = (ulong *)simple_strtoul(argv[1], NULL, 16);
	else
		start = (ulong *)CONFIG_SYS_MEMTEST_START;

	if (argc > 2)
		end = (ulong *)simple_strtoul(argv[2], NULL, 16);
	else
		end = (ulong *)(CONFIG_SYS_MEMTEST_END);

	if (argc > 3)
		pattern = (ulong)simple_strtoul(argv[3], NULL, 16);
	else
		pattern = 0;

	if (argc > 4)
		iteration_limit = (ulong)simple_strtoul(argv[4], NULL, 16);
	else
		iteration_limit = 0;

#if defined(CONFIG_SYS_ALT_MEMTEST)
	printf ("Testing %08x ... %08x:\n", (uint)start, (uint)end);
	PRINTF("%s:%d: start 0x%p end 0x%p\n",
		__FUNCTION__, __LINE__, start, end);

	for (;;) {
		if (ctrlc()) {
			putc ('\n');
			return 1;
		}


		if (iteration_limit && iterations > iteration_limit) {
			printf("Tested %d iteration(s) with %lu errors.\n",
				iterations-1, errs);
			return errs != 0;
		}

		printf("Iteration: %6d\r", iterations);
		PRINTF("\n");
		iterations++;

		/*
		 * Data line test: write a pattern to the first
		 * location, write the 1's complement to a 'parking'
		 * address (changes the state of the data bus so a
		 * floating bus doen't give a false OK), and then
		 * read the value back. Note that we read it back
		 * into a variable because the next time we read it,
		 * it might be right (been there, tough to explain to
		 * the quality guys why it prints a failure when the
		 * "is" and "should be" are obviously the same in the
		 * error message).
		 *
		 * Rather than exhaustively testing, we test some
		 * patterns by shifting '1' bits through a field of
		 * '0's and '0' bits through a field of '1's (i.e.
		 * pattern and ~pattern).
		 */
		addr = start;
		for (j = 0; j < sizeof(bitpattern)/sizeof(bitpattern[0]); j++) {
		    val = bitpattern[j];
		    for(; val != 0; val <<= 1) {
			*addr  = val;
			*dummy  = ~val; /* clear the test data off of the bus */
			readback = *addr;
			if(readback != val) {
			    printf ("FAILURE (data line): "
				"expected %08lx, actual %08lx\n",
					  val, readback);
			    errs++;
			    if (ctrlc()) {
				putc ('\n');
				return 1;
			    }
			}
			*addr  = ~val;
			*dummy  = val;
			readback = *addr;
			if(readback != ~val) {
			    printf ("FAILURE (data line): "
				"Is %08lx, should be %08lx\n",
					readback, ~val);
			    errs++;
			    if (ctrlc()) {
				putc ('\n');
				return 1;
			    }
			}
		    }
		}

		/*
		 * Based on code whose Original Author and Copyright
		 * information follows: Copyright (c) 1998 by Michael
		 * Barr. This software is placed into the public
		 * domain and may be used for any purpose. However,
		 * this notice must not be changed or removed and no
		 * warranty is either expressed or implied by its
		 * publication or distribution.
		 */

		/*
		 * Address line test
		 *
		 * Description: Test the address bus wiring in a
		 *              memory region by performing a walking
		 *              1's test on the relevant bits of the
		 *              address and checking for aliasing.
		 *              This test will find single-bit
		 *              address failures such as stuck -high,
		 *              stuck-low, and shorted pins. The base
		 *              address and size of the region are
		 *              selected by the caller.
		 *
		 * Notes:	For best results, the selected base
		 *              address should have enough LSB 0's to
		 *              guarantee single address bit changes.
		 *              For example, to test a 64-Kbyte
		 *              region, select a base address on a
		 *              64-Kbyte boundary. Also, select the
		 *              region size as a power-of-two if at
		 *              all possible.
		 *
		 * Returns:     0 if the test succeeds, 1 if the test fails.
		 */
		len = ((ulong)end - (ulong)start)/sizeof(vu_long);
		pattern = (vu_long) 0xaaaaaaaa;
		anti_pattern = (vu_long) 0x55555555;

		PRINTF("%s:%d: length = 0x%.8lx\n",
			__FUNCTION__, __LINE__,
			len);
		/*
		 * Write the default pattern at each of the
		 * power-of-two offsets.
		 */
		for (offset = 1; offset < len; offset <<= 1) {
			start[offset] = pattern;
		}

		/*
		 * Check for address bits stuck high.
		 */
		test_offset = 0;
		start[test_offset] = anti_pattern;

		for (offset = 1; offset < len; offset <<= 1) {
		    temp = start[offset];
		    if (temp != pattern) {
			printf ("\nFAILURE: Address bit stuck high @ 0x%.8lx:"
				" expected 0x%.8lx, actual 0x%.8lx\n",
				(ulong)&start[offset], pattern, temp);
			errs++;
			if (ctrlc()) {
			    putc ('\n');
			    return 1;
			}
		    }
		}
		start[test_offset] = pattern;
		WATCHDOG_RESET();

		/*
		 * Check for addr bits stuck low or shorted.
		 */
		for (test_offset = 1; test_offset < len; test_offset <<= 1) {
		    start[test_offset] = anti_pattern;

		    for (offset = 1; offset < len; offset <<= 1) {
			temp = start[offset];
			if ((temp != pattern) && (offset != test_offset)) {
			    printf ("\nFAILURE: Address bit stuck low or shorted @"
				" 0x%.8lx: expected 0x%.8lx, actual 0x%.8lx\n",
				(ulong)&start[offset], pattern, temp);
			    errs++;
			    if (ctrlc()) {
				putc ('\n');
				return 1;
			    }
			}
		    }
		    start[test_offset] = pattern;
		}

		/*
		 * Description: Test the integrity of a physical
		 *		memory device by performing an
		 *		increment/decrement test over the
		 *		entire region. In the process every
		 *		storage bit in the device is tested
		 *		as a zero and a one. The base address
		 *		and the size of the region are
		 *		selected by the caller.
		 *
		 * Returns:     0 if the test succeeds, 1 if the test fails.
		 */
		num_words = ((ulong)end - (ulong)start)/sizeof(vu_long) + 1;

		/*
		 * Fill memory with a known pattern.
		 */
		for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
			WATCHDOG_RESET();
			start[offset] = pattern;
		}

		/*
		 * Check each location and invert it for the second pass.
		 */
		for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
		    WATCHDOG_RESET();
		    temp = start[offset];
		    if (temp != pattern) {
			printf ("\nFAILURE (read/write) @ 0x%.8lx:"
				" expected 0x%.8lx, actual 0x%.8lx)\n",
				(ulong)&start[offset], pattern, temp);
			errs++;
			if (ctrlc()) {
			    putc ('\n');
			    return 1;
			}
		    }

		    anti_pattern = ~pattern;
		    start[offset] = anti_pattern;
		}

		/*
		 * Check each location for the inverted pattern and zero it.
		 */
		for (pattern = 1, offset = 0; offset < num_words; pattern++, offset++) {
		    WATCHDOG_RESET();
		    anti_pattern = ~pattern;
		    temp = start[offset];
		    if (temp != anti_pattern) {
			printf ("\nFAILURE (read/write): @ 0x%.8lx:"
				" expected 0x%.8lx, actual 0x%.8lx)\n",
				(ulong)&start[offset], anti_pattern, temp);
			errs++;
			if (ctrlc()) {
			    putc ('\n');
			    return 1;
			}
		    }
		    start[offset] = 0;
		}
	}

#else /* The original, quickie test */
	incr = 1;
	for (;;) {
		if (ctrlc()) {
			putc ('\n');
			return 1;
		}

		if (iteration_limit && iterations > iteration_limit) {
			printf("Tested %d iteration(s) with %lu errors.\n",
				iterations-1, errs);
			return errs != 0;
		}
		++iterations;

		printf ("\rPattern %08lX  Writing..."
			"%12s"
			"\b\b\b\b\b\b\b\b\b\b",
			pattern, "");

		for (addr=start,val=pattern; addr<end; addr++) {
			WATCHDOG_RESET();
			*addr = val;
			val  += incr;
		}

		puts ("Reading...");

		for (addr=start,val=pattern; addr<end; addr++) {
			WATCHDOG_RESET();
			readback = *addr;
			if (readback != val) {
				printf ("\nMem error @ 0x%08X: "
					"found %08lX, expected %08lX\n",
					(uint)addr, readback, val);
				errs++;
				if (ctrlc()) {
					putc ('\n');
					return 1;
				}
			}
			val += incr;
		}

		/*
		 * Flip the pattern each time to make lots of zeros and
		 * then, the next time, lots of ones.  We decrement
		 * the "negative" patterns and increment the "positive"
		 * patterns to preserve this feature.
		 */
		if(pattern & 0x80000000) {
			pattern = -pattern;	/* complement & increment */
		}
		else {
			pattern = ~pattern;
		}
		incr = -incr;
	}
#endif
	return 0;	/* not reached */
}
示例#26
0
/* converts stream ipInF to DOS format text and write to stream ipOutF
 * RetVal: 0  if success
 *         -1  otherwise
 */
int ConvertUnixToDos(FILE* ipInF, FILE* ipOutF, CFlag *ipFlag)
{
    int RetVal = 0;
    int TempChar;
    int PreviousChar = 0;

    ipFlag->status = 0;

    /* LF    -> CR-LF */
    /* CR-LF -> CR-LF, in case the input file is a DOS text file */
    /* \x0a = Newline/Line Feed (LF) */
    /* \x0d = Carriage Return (CR) */

    switch (ipFlag->ConvMode)
    {
      case 0: /* ascii */
        while ((TempChar = getc(ipInF)) != EOF) {  /* get character */
          if ((ipFlag->Force == 0) &&
              (TempChar < 32) &&
              (TempChar != '\x0a') &&  /* Not an LF */
              (TempChar != '\x0d') &&  /* Not a CR */
              (TempChar != '\x09')) {  /* Not a TAB */
            RetVal = -1;
            ipFlag->status |= BINARY_FILE ;
            break;
          }
          if (TempChar == '\x0a')
	  {
            putc('\x0d', ipOutF); /* got LF, put CR */
	  } else {
             if (TempChar == '\x0d') /* got CR */
	     {
               if ((TempChar = getc(ipInF)) == EOF) /* get next char */
                 TempChar = '\x0d';  /* Read error, or end of file. */
	       else
	       {
                 putc('\x0d', ipOutF); /* put CR */
                 PreviousChar = '\x0d';
	       }
	     }
	  }
          if (putc(U2DAsciiTable[TempChar], ipOutF) == EOF)
          {
              RetVal = -1;
              if (!ipFlag->Quiet)
                fprintf(stderr, _("unix2dos: can not write to output file\n"));
              break;
          } else {
            AddDOSNewLine( ipInF, ipOutF, ipFlag, TempChar, PreviousChar);
          }
          PreviousChar = TempChar;
        }
        break;
      case 1: /* 7bit */
        while ((TempChar = getc(ipInF)) != EOF) {
          if ((ipFlag->Force == 0) &&
              (TempChar < 32) &&
              (TempChar != '\x0a') &&  /* Not an LF */
              (TempChar != '\x0d') &&  /* Not a CR */
              (TempChar != '\x09')) {  /* Not a TAB */
            RetVal = -1;
            ipFlag->status |= BINARY_FILE ;
            break;
          }
          if (TempChar == '\x0a')
	  {
            putc('\x0d', ipOutF); /* got LF, put CR */
	  } else {
             if (TempChar == '\x0d') /* got CR */
	     {
               if ((TempChar = getc(ipInF)) == EOF) /* get next char */
                 TempChar = '\x0d';  /* Read error, or end of file. */
	       else
	       {
                 putc('\x0d', ipOutF); /* put CR */
                 PreviousChar = '\x0d';
	       }
	     }
	  }
          if (putc(U2D7BitTable[TempChar], ipOutF) == EOF)
          {
              RetVal = -1;
              if (!ipFlag->Quiet)
                fprintf(stderr, _("unix2dos: can not write to output file\n"));
              break;
          } else {
            AddDOSNewLine( ipInF, ipOutF, ipFlag, TempChar, PreviousChar);
          }
          PreviousChar = TempChar;
        }
        break;
      case 2: /* iso */
        while ((TempChar = getc(ipInF)) != EOF) {
          if ((ipFlag->Force == 0) &&
              (TempChar < 32) &&
              (TempChar != '\x0a') &&  /* Not an LF */
              (TempChar != '\x0d') &&  /* Not a CR */
              (TempChar != '\x09')) {  /* Not a TAB */
            RetVal = -1;
            ipFlag->status |= BINARY_FILE ;
            break;
          }
          if (TempChar == '\x0a')
	  {
            putc('\x0d', ipOutF); /* got LF, put CR */
	  } else {
             if (TempChar == '\x0d') /* got CR */
	     {
               if ((TempChar = getc(ipInF)) == EOF) /* get next char */
                 TempChar = '\x0d';  /* Read error, or end of file. */
	       else
	       {
                 putc('\x0d', ipOutF); /* put CR */
                 PreviousChar = '\x0d';
	       }
	     }
	  }
          if (putc(U2DIsoTable[TempChar], ipOutF) == EOF)
          {
              RetVal = -1;
              if (!ipFlag->Quiet)
                fprintf(stderr, _("unix2dos: can not write to output file\n"));
              break;
          } else {
            AddDOSNewLine( ipInF, ipOutF, ipFlag, TempChar, PreviousChar);
          }
          PreviousChar = TempChar;
        }
        break;
      case 3: /* Mac */
        while ((TempChar = getc(ipInF)) != EOF) {
          if ((ipFlag->Force == 0) &&
              (TempChar < 32) &&
              (TempChar != '\x0a') &&  /* Not an LF */
              (TempChar != '\x0d') &&  /* Not a CR */
              (TempChar != '\x09')) {  /* Not a TAB */
            RetVal = -1;
            ipFlag->status |= BINARY_FILE ;
            break;
          }
          if ((TempChar != '\x0a')) /* Not an LF */
            {
              if(putc(U2DAsciiTable[TempChar], ipOutF) == EOF){
                RetVal = -1;
                if (!ipFlag->Quiet)
                  fprintf(stderr, _("unix2dos: can not write to output file\n"));
                break;
              }
              PreviousChar = TempChar;
            }
          else{
            /* TempChar is an LF */
            /* Don't touch this delimiter if it's a CR,LF pair. */
            if ( PreviousChar == '\x0d' ) {
              if (putc('\x0a', ipOutF) == EOF)  /* CR,LF pair. Put LF */
                {
                  RetVal = -1;
                  if (!ipFlag->Quiet)
                    fprintf(stderr, _("unix2dos: can not write to output file\n"));
                  break;
                }
              PreviousChar = TempChar;
              continue;
            }
            PreviousChar = TempChar;
            if (putc('\x0d', ipOutF) == EOF) /* Unix line end (LF). Put CR */
              {
                RetVal = -1;
                if (!ipFlag->Quiet)
                  fprintf(stderr, _("unix2dos: can not write to output file\n"));
                break;
              }
            if (ipFlag->NewLine) {  /* add additional CR? */
              putc('\x0d', ipOutF);
            }
          }
        }
        break;
      default: /* unknown convmode */
      ;
#ifdef DEBUG
      fprintf(stderr, _("unix2dos: program error, invalid conversion mode %d\n"),ipFlag->ConvMode);
      exit(1);
#endif
    }
    return RetVal;
}
示例#27
0
文件: fdwrite.c 项目: 2asoft/freebsd
int
main(int argc, char **argv)
{
    int inputfd = -1, c, fdn = 0, i,j,fd;
    int bpt, verbose=1, nbytes=0, track;
    int interactive = 1;
    const char *device= "/dev/fd0";
    char *trackbuf = 0,*vrfybuf = 0;
    struct fd_type fdt;
    FILE *tty;

    setbuf(stdout,0);
    while((c = getopt(argc, argv, "d:f:vy")) != -1)
	    switch(c) {
	    case 'd':	/* Which drive */
		    device = optarg;
		    break;

	    case 'f':	/* input file */
		    if (inputfd >= 0)
			    close(inputfd);
		    inputfd = open(optarg,O_RDONLY);
		    if (inputfd < 0)
			    err(1, "%s", optarg);
		    break;

	    case 'v':  /* Toggle verbosity */
		    verbose = !verbose;
		    break;

	    case 'y':  /* Don't confirm? */
		    interactive = 0;
		    break;

	    case '?': default:
		    usage();
	    }

    if (inputfd < 0)
	inputfd = 0;

    if (!isatty(1))
	interactive = 0;

    if(optind < argc)
	    usage();

    tty = fopen(_PATH_TTY,"r+");
    if(!tty)
	    err(1, _PATH_TTY);
    setbuf(tty,0);

    for(j=1;j > 0;) {
        fdn++;
	if (interactive) {
	    fprintf(tty,
		    "Please insert floppy #%d in drive %s and press return >",
		    fdn,device);
	    while(1) {
		i = getc(tty);
		if(i == '\n') break;
	    }
	}

	if((fd = open(device, O_RDWR)) < 0)
	    err(1, "%s", device);

	if(ioctl(fd, FD_GTYPE, &fdt) < 0)
	    errx(1, "not a floppy disk: %s", device);

	bpt = fdt.sectrac * (1<<fdt.secsize) * 128;
	if(!trackbuf) {
	    trackbuf = malloc(bpt);
	    if(!trackbuf) errx(1, "malloc");
	}
	if(!vrfybuf) {
	    vrfybuf = malloc(bpt);
	    if(!vrfybuf) errx(1, "malloc");
	}

	if(fdn == 1) {
	    if(verbose) {
		printf("Format: %d cylinders, %d heads, %d sectors, %d bytes = %dkb\n",
		fdt.tracks,fdt.heads,fdt.sectrac,(1<<fdt.secsize) * 128,
		fdt.tracks*bpt*fdt.heads/1024);

	    }
	    memset(trackbuf,0,bpt);
	    for(j=0;inputfd >= 0 && j<bpt;j+=i) {
		if(!(i = read(inputfd,trackbuf+j,bpt-j))) {
		    close(inputfd);
		    inputfd = -1;
		    break;
		}
		nbytes += i;
	    }
	}
	for (track = 0; track < fdt.tracks * fdt.heads; track++) {
	    if(verbose) printf("\r%3d ",fdt.tracks * fdt.heads-track);
	    if(verbose) putc((j ? 'I':'Z'),stdout);
	    format_track(fd, track / fdt.heads, fdt.sectrac, track % fdt.heads,
		    fdt.trans, fdt.f_gap, fdt.secsize, 0xe6,
		    fdt.f_inter);
	    if(verbose) putc('F',stdout);

	    if (lseek (fd, (long) track*bpt, 0) < 0) err(1, "lseek");
	    if (write (fd, trackbuf, bpt) != bpt) err(1, "write");
	    if(verbose) putc('W',stdout);

	    if (lseek (fd, (long) track*bpt, 0) < 0) err(1, "lseek");
	    if (read (fd, vrfybuf, bpt) != bpt) err(1, "read");
	    if(verbose) putc('R',stdout);

	    if (memcmp(trackbuf,vrfybuf,bpt)) err(1, "compare");
	    if(verbose) putc('C',stdout);

	    memset(trackbuf,0,bpt);
	    for(j=0;inputfd >= 0 && j<bpt;j+=i) {
		if(!(i = read(inputfd,trackbuf+j,bpt-j))) {
		    close(inputfd);
		    inputfd = -1;
		    break;
		}
		nbytes += i;
	    }
	}
	close(fd);
	putc('\r',stdout);
    }
    if(verbose)
	printf("%d bytes on %d flopp%s\n",nbytes,fdn,fdn==1?"y":"ies");
    exit(0);
}
示例#28
0
文件: mkmakefile.c 项目: Bitesher/xnu
void
do_objs(FILE *fp, const char *msg, int ext)
{
	register struct file_list *tp;
	register int lpos, len;
	char *cp;
	char och;
	const char *sp;
#if	DO_SWAPFILE
	register struct file_list *fl;
	char swapname[32];
#endif	/* DO_SWAPFILE */

	fprintf(fp, "%s", msg);
	lpos = strlen(msg);
	for (tp = ftab; tp != 0; tp = tp->f_next) {
		if (tp->f_type == INVISIBLE)
			continue;

		/*
		 *	Check for '.o' file in list
		 */
		cp = tp->f_fn + (len = strlen(tp->f_fn)) - 1;
		if ((ext == -1 && tp->f_flags & ORDERED) ||		/* not in objs */
		    (ext != -1 && *cp != ext))
			continue;
		else if (*cp == 'o') {
			if (len + lpos > 72) {
				lpos = 8;
				fprintf(fp, "\\\n\t");
			}
			put_source_file_name(fp, tp);
			fprintf(fp, " ");
			lpos += len + 1;
			continue;
		}
		sp = tail(tp->f_fn);
#if	DO_SWAPFILE
		for (fl = conf_list; fl; fl = fl->f_next) {
			if (fl->f_type != SWAPSPEC)
				continue;
			(void) sprintf(swapname, "swap%s.c", fl->f_fn);
			if (eq(sp, swapname))
				goto cont;
		}
#endif	/* DO_SWAPFILE */
		cp = (char *)sp + (len = strlen(sp)) - 1;
		och = *cp;
		*cp = 'o';
		if (len + lpos > 72) {
			lpos = 8;
			fprintf(fp, "\\\n\t");
		}
		fprintf(fp, "%s ", sp);
		lpos += len + 1;
		*cp = och;
#if	DO_SWAPFILE
cont:
		;
#endif	/* DO_SWAPFILE */
	}
	if (lpos != 8)
		putc('\n', fp);
}
示例#29
0
/*
 ****************************************************************
 *	Programa principal					*
 ****************************************************************
 */
void
main (int argc, const char *argv[])
{
	Display		*dp;
	Window		win;
	int		screen;
	ulong		fg, bg;
	GC		gc;
	XEvent		ev;
	Font		font;
	KeySym		key;
	char		text[80];
	int		doneflag, len, opt, exitval;

	/*
	 *	Inicializa opções.
	 */
	exitval = 0;

	/*
	 *	Analisa as opções de execução.
	 */
	while ((opt = getopt (argc, argv, "G:f:MH")) != EOF)
	{
		switch (opt)
		{
		    case 'M':
			exit (0);

		    case 'H':
			help (0);
			break;

		    case 'f':
			fontname = (char *)optarg;
			break;

		    case 'G':
			get_geometry (optarg);
			break;

		    default:
			putc ('\n', stderr);
			help (2);

		}	/* end switch (opt) */

	}	/* while ((opt = getopt (...))) */

	/*
	 *	Conecta-se ao servidor.
	 */
	if ((dp = XOpenDisplay (NULL)) == (Display *)NULL)
		msg ("$Não consegui conectar-me ao servidor");

	screen = DefaultScreen (dp);

	bg = WhitePixel (dp, screen);
	fg = BlackPixel (dp, screen);

	win =	XCreateSimpleWindow
		(	dp,
			DefaultRootWindow (dp), 
			x, y, dx, dy,
			2,
			fg, bg			/* cores: frente e fundo */
		);

	gc = DefaultGC (dp, screen);

	if (fontname != NOSTR)
	{
		if (font = XLoadFont (dp, fontname))
			XSetFont (dp, gc, font);
	}

	XSelectInput (dp, win, ButtonPressMask|KeyPressMask|ExposureMask);

	XMapRaised (dp, win);

	for (doneflag = 0; doneflag == 0; /* sem incremento */)
	{
		XNextEvent (dp, &ev);

		switch (ev.type)
		{
		    case Expose:
			break;

		    case ButtonPress:
			sprintf
			(	text,
#if (0)	/****************************************************/
				"(%d, %d), (%d, %d)",
				ev.xbutton.x_root, ev.xbutton.y_root,
#endif	/****************************************************/
				"(%d, %d)",
				ev.xbutton.x, ev.xbutton.y
			);

			XDrawImageString
			(	dp, win, gc,
				ev.xbutton.x, ev.xbutton.y,
				text, strlen (text)
			);

			break;

		    case KeyPress:
			len = XLookupString (&ev.xkey, text, 10, &key, 0);

			if (len == 1 && text[0] == 'q')
				doneflag++;
			break;
		}
	}


	XDestroyWindow (dp, win);
	XCloseDisplay (dp);

	exit (0);

}	/* end main */
示例#30
0
文件: azy_events.c 项目: Limsik/e17
Eina_Bool
azy_events_header_parse(Azy_Net       *net,
                        unsigned char *event_data,
                        size_t         event_len,
                        int            offset)
{
   unsigned char *r = NULL, *p = NULL, *start = NULL, *buf_start = NULL;
   unsigned char *data = (event_data) ? event_data + offset : NULL;
   int64_t len = (event_len) ? event_len - offset : 0;
   const char *s = NULL;
   unsigned char slen = 0;
   unsigned char sep[5];
   int line_len = 0;
   int64_t prev_size = 0;

   DBG("(net=%p, event_data=%p, len=%zu, offset=%i)", net, event_data, event_len, offset);
   if (!AZY_MAGIC_CHECK(net, AZY_MAGIC_NET))
     {
        AZY_MAGIC_FAIL(net, AZY_MAGIC_NET);
        return EINA_FALSE;
     }
   if (net->headers_read)
     return EINA_TRUE;
   EINA_SAFETY_ON_TRUE_RETURN_VAL((!net->buffer) && (!data), EINA_FALSE);

   if (net->size && net->buffer)
     {
        if (event_data && (azy_rpc_log_dom >= 0))
          {
             char buf[64];
             snprintf(buf, sizeof(buf), "STORED:\n<<<<<<<<<<<<<\n%%.%"PRIi64"s\n<<<<<<<<<<<<<", net->size);
             RPC_INFO(buf, net->buffer);
             snprintf(buf, sizeof(buf), "RECEIVED:\n<<<<<<<<<<<<<\n%%.%"PRIi64"s\n<<<<<<<<<<<<<", len - offset);
             RPC_INFO(buf, data);
          }
        /* previous buffer */
        /* alloca should be safe here because ecore_con reads at most 64k
         * and even if no headers were found previously, the entire
         * buffer would not be copied
         */
        buf_start = alloca(len + net->size - offset);
        /* grab and combine buffers */
        if (event_data)
          {
             memcpy(buf_start, net->buffer + offset, net->size - offset);
             memcpy(buf_start + net->size, event_data, len);
          }
        else
          memcpy(buf_start, net->buffer + offset, net->size - offset);

        free(net->buffer);
        net->buffer = NULL;
        len += net->size - offset;

        prev_size = net->size;
        net->size = 0;
        start = buf_start;
        AZY_SKIP_BLANK(start);
     }
   else
   /* only current buffer plus possible net->overflow */
     {
        /* copy pointer */
         start = data;
         /* skip all spaces/newlines/etc and decrement len */
         AZY_SKIP_BLANK(start);
     }

   if ((!len) && (event_len - offset > 0)) /* only blanks were passed, assume http separator */
     {
        net->headers_read = EINA_TRUE;
        return EINA_TRUE;
     }
   /* apparently this can happen? */
   EINA_SAFETY_ON_NULL_RETURN_VAL(start, EINA_FALSE);
   /* find a header or append to buffer */
   if ((!(r = memchr(start, '\r', len)) && !(r = memchr(start, '\n', len)))) /* append to a buffer and use net->overflow */
     {
        unsigned char *tmp;

        if (net->size)
          {
             tmp = realloc(net->buffer, net->size + len);
             EINA_SAFETY_ON_NULL_RETURN_VAL(tmp, EINA_FALSE);

             net->buffer = tmp;
             memcpy(net->buffer + net->size, start, len);
             net->size += len;
          }
        else
          {
             tmp = realloc(net->buffer, len);
             EINA_SAFETY_ON_NULL_RETURN_VAL(tmp, EINA_FALSE);

             net->buffer = tmp;
             memcpy(net->buffer, start, len);
             net->size = len;
          }
        return EINA_TRUE;
     }

   if (*r == '\r')
     {
        unsigned char *x;
        if ((x = memchr(start, '\n', len)))
          {
             if ((x - r) > 0)
               s = "\r\n";
             else
               { /* we currently have \n\r: b64 encoding can leave a trailing \n
                  * so we have to check for an extra \n
                  */
                   if ((x - r < 0) && ((unsigned int)(r + 1 - start) < len) && (r[1] == '\n')) /* \n\r\n */
                     {
                        if (((unsigned int)(r + 2 - start) < len) && (r[2] == '\r')) /* \n\r\n\r */
                          {
                             if (((unsigned int)(r + 3 - start) < len) && (r[3] == '\n'))
                               /* \n\r\n\r\n oh hey I'm gonna stop here before it gets too insane */
                               s = "\r\n";
                             else
                               s = "\n\r";
                          }
                        else
                          s = "\r\n";
                     }
                   else
                     s = "\n\r";
               }
          }
        else
          s = "\r";
     }
   else
     s = "\n";

   slen = strlen(s);
   snprintf((char *)sep, sizeof(sep), "%s%s", s, s);

   p = start;
   line_len = r - p;
   while (len && r)
     {
        unsigned char *ptr, *semi = p;

        if (line_len > MAX_HEADER_SIZE)
          {
             WARN("Ignoring unreasonably large header starting with:\n %.32s\n", p);
             goto skip_header;
          }
        semi += (line_len - _azy_events_valid_header_name((const char *)p, line_len));
        if (semi == p) goto skip_header;

        ptr = semi + 1;
        while ((isspace(*ptr)) && (ptr - p < line_len))
          ptr++;

        if (_azy_events_valid_header_value((const char *)ptr, line_len - (ptr - p)))
          {
             const char *key, *value;

             p[semi - p] = 0;
             ptr[line_len - (ptr - p)] = 0;
             key = (const char *)p;
             value = (const char *)ptr;
             INFO("Found header: key='%s'", key);
             INFO("Found header: value='%s'", value);
             azy_net_header_set(net, key, value);
             if (!strcasecmp(key, "content-length"))
               net->http.content_length = strtol((const char *)value, NULL, 10);
          }

skip_header:
        len -= line_len + slen;
        if (len < slen)
          break;
        p = r + slen;
        /* double separator: STOP */
        if (!strncmp((char*)p, s, slen))
          {
             net->headers_read = EINA_TRUE;
             break;
          }
        r = azy_memstr(p, (const unsigned char *)s, len, slen);
        line_len = r - p;
        /* FIXME: to be fully 1.1 compliant, lines without a colon
         * be filtered and checked to see if is a continuing header
         * from the previous line
         */
     }

   AZY_SKIP_BLANK(p);

   if (!net->headers_read)
     return EINA_TRUE;

   if (!net->http.content_length) net->http.content_length = -1;
   if (len)
     {
        int64_t rlen;
        /* if we get here, we need to append to the buffers */

        if (net->http.content_length > 0)
          {
             if (len > net->http.content_length)
               {
                  rlen = net->http.content_length;
                  net->overflow_length = len - rlen;
                  WARN("Extra content length of %"PRIi64"!", net->overflow_length);
                  net->overflow = malloc(net->overflow_length);
     /* FIXME: uhhhh f**k? */
                  EINA_SAFETY_ON_NULL_RETURN_VAL(net->overflow, EINA_FALSE);
                  memcpy(net->overflow, p + rlen, net->overflow_length);
#ifdef ISCOMFITOR
                if (azy_rpc_log_dom >= 0)
                  {
                     int64_t x;
                     RPC_INFO("OVERFLOW:\n<<<<<<<<<<<<<");
                     for (x = 0; x < net->overflow_length; x++)
                       putc(net->overflow[x], stdout);
                     fflush(stdout);
                  }
#endif
               }
             else
               rlen = len;
          }
        else
          /* this shouldn't be possible unless someone is violating spec */
          rlen = len;

        INFO("Set recv size to %"PRIi64" (previous %"PRIi64")", rlen, prev_size);
        net->size = rlen;
        net->buffer = malloc(rlen);
        /* FIXME: cleanup */
        EINA_SAFETY_ON_NULL_RETURN_VAL(net->buffer, EINA_FALSE);

        memcpy(net->buffer, p, rlen);
     }

   return EINA_TRUE;
}