Beispiel #1
0
int fp_setpos(void *handle, size_t pos)
{
	return fseek((FILE *)handle, (long)pos, SEEK_SET);
}
Beispiel #2
0
void areplay_init(void)
{
  int size;
  FILE *f;
  
  memset(&action_replay,0,sizeof(action_replay));

  /* store Action replay ROM (max. 128k) & RAM (64k) above cartridge ROM + SRAM area */
  if (cart.romsize > 0x810000) return;
  action_replay.rom = cart.rom + 0x810000;
  action_replay.ram = cart.rom + 0x830000;

  /* Open Action Replay ROM */
  f = fopen(AR_ROM,"rb");
  if (f == NULL) return;

  /* ROM size */
  fseek(f, 0, SEEK_END);
  size = ftell(f);
  fseek(f, 0, SEEK_SET);

  /* detect Action Replay board type */
  switch (size)
  {
    case 0x8000:  
    {
      /* normal Action Replay (32K) */
      action_replay.enabled = TYPE_AR;
  
      /* internal registers mapped at $010000-$01ffff */
      m68k.memory_map[0x01].write16 = ar_write_regs;
      break;
    }

    case 0x10000:
    case 0x20000:
    {
      /* read Stack Pointer */
      uint8 sp[4];
      fread(&sp, 4, 1, f);
      fseek(f, 0, SEEK_SET);

      /* Detect board version */
      if (sp[1] == 0x42)
      {
        /* PRO Action Replay 1 (64/128K) */
        action_replay.enabled = TYPE_PRO1;

        /* internal registers mapped at $010000-$01ffff */
        m68k.memory_map[0x01].write16 = ar_write_regs;
      }
      else if (sp[1] == 0x60)
      {
        /* PRO Action Replay 2 (64K) */
        action_replay.enabled = TYPE_PRO2;

        /* internal registers mapped at $100000-$10ffff */
        m68k.memory_map[0x10].write16 = ar_write_regs_2;
      }

      /* internal RAM (64k), mapped at $420000-$42ffff or $600000-$60ffff */
      if (action_replay.enabled)
      {
        m68k.memory_map[sp[1]].base      = action_replay.ram;
        m68k.memory_map[sp[1]].read8     = NULL;
        m68k.memory_map[sp[1]].read16    = NULL;
        m68k.memory_map[sp[1]].write8    = ar_write_ram_8;
        m68k.memory_map[sp[1]].write16   = NULL;
      }
      break;
    }

    default:
    {
      break;
    }
  }

  if (action_replay.enabled)
  {
    /* Load ROM */
    int i = 0;
    for (i=0; i<size; i+=0x1000)
    {
      fread(action_replay.rom + i, 0x1000, 1, f);
    }

#ifdef LSB_FIRST
    for (i= 0; i<size; i+=2)
    {
      /* Byteswap ROM */
      uint8 temp = action_replay.rom[i];
      action_replay.rom[i] = action_replay.rom[i+1];
      action_replay.rom[i+1] = temp;
    }
#endif
  }

  /* Close ROM file */
  fclose(f);
}
Beispiel #3
0
int fileSkip(FILE *fp, int sz)
{
	return fseek(fp, sz, SEEK_CUR);
}
int getdelim1(char **lineptr, size_t *n, int delim, FILE *stream)
{
        char *p;                    // reads stored here
        size_t const rchunk = 512;  // number of bytes to read
        size_t const mchunk = 512;  // number of extra bytes to malloc
        size_t m = rchunk + 1;      // initial buffer size

        if (*lineptr) {
                if (*n < m) {
                        *lineptr = (char*)realloc(*lineptr, m);
                        if (!*lineptr) return -1;
                        *n = m;
                }
        } else {
                *lineptr = (char*)malloc(m);
                if (!*lineptr) return -1;
                *n = m;
        }

        m = 0; // record length including seperator

        do {
                size_t i;     // number of bytes read etc
                size_t j = 0; // number of bytes searched

                p = *lineptr + m;

                i = fread(p, 1, rchunk, stream);
                if (i < rchunk && ferror(stream))
                        return -1;
		while (j < i) {
                        ++j;
                        if (*p++ == (char)delim) {
                                *p = '\0';
                                if (j != i) {
                                        if (fseek(stream, j - i, SEEK_CUR))
                                                return -1;
                                        if (feof(stream))
                                                clearerr(stream);
                                }
                                m += j;
                                return m;
                        }
                }

                m += j;
                if (feof(stream)) {
                        if (m) return m;
                        if (!i) return -1;
                }

                // allocate space for next read plus possible null terminator
                i = ((m + (rchunk + 1 > mchunk ? rchunk + 1 : mchunk) +
                      mchunk - 1) / mchunk) * mchunk;
                if (i != *n) {
                        *lineptr = (char*)realloc(*lineptr, i);
                        if (!*lineptr) return -1;
                        *n = i;
                }
        } while (1);
}
Beispiel #5
0
static int gf_read_bitmap(FILE *p, DviFontChar *ch)
{
    int    op;
    int    min_n, max_n;
    int    min_m, max_m;
    int    paint_switch;
    int    x, y;
    int    bpl;
    Int32    par;
    BmUnit    *line;
    BITMAP    *map;
    
    fseek(p, (long)ch->offset, SEEK_SET);
    op = fuget1(p);
    if(op == GF_BOC) {
        /* skip character code */
        fuget4(p);
        /* skip pointer */
        fuget4(p);
        min_m = fsget4(p);
        max_m = fsget4(p);
        min_n = fsget4(p);
        max_n = fsget4(p);
    } else if(op == GF_BOC1) {
        /* skip character code */
        fuget1(p);
        min_m = fuget1(p); /* this is max_m - min_m */
        max_m = fuget1(p);
        min_n = fuget1(p); /* this is max_n - min_n */
        max_n = fuget1(p); 
        min_m = max_m - min_m;
        min_n = max_n - min_n;
    } else {
        mdvi_error(_("GF: invalid opcode %d in character %d\n"),
               op, ch->code);
        return -1;
    }

    ch->x = -min_m;
    ch->y = max_n;
    ch->width = max_m - min_m + 1;
    ch->height = max_n - min_n + 1;
    map = bitmap_alloc(ch->width, ch->height);

    ch->glyph.data = map;
    ch->glyph.x = ch->x;
    ch->glyph.y = ch->y;
    ch->glyph.w = ch->width;
    ch->glyph.h = ch->height;

#define COLOR(x)    ((x) ? "BLACK" : "WHITE")

    paint_switch = WHITE;
    x = y = 0;
    line = map->data;
    bpl = map->stride;
    DEBUG((DBG_BITMAPS, "(gf) reading character %d\n", ch->code));
    while((op = fuget1(p)) != GF_EOC) {
        Int32    n;
        
        if(feof(p))
            break;
        if(op == GF_PAINT0) {
            DEBUG((DBG_BITMAPS, "(gf) Paint0 %s -> %s\n",
                COLOR(paint_switch), COLOR(!paint_switch)));    
            paint_switch = !paint_switch;
        } else if(op <= GF_PAINT3) {
            if(op < GF_PAINT1)
                par = op;
            else
                par = fugetn(p, op - GF_PAINT1 + 1);            
            if(y >= ch->height || x + par >= ch->width)
                goto toobig;
            /* paint everything between columns x and x + par - 1 */
            DEBUG((DBG_BITMAPS, "(gf) Paint %d %s from (%d,%d)\n",
                par, COLOR(paint_switch), x, y));
            if(paint_switch == BLACK)
                bitmap_paint_bits(line + (x / BITMAP_BITS),
                    x % BITMAP_BITS, par);
            paint_switch = !paint_switch;
            x += par;
        } else if(op >= GF_NEW_ROW_0 && op <= GF_NEW_ROW_MAX) {
            y++; 
            line = bm_offset(line, bpl);
            x = op - GF_NEW_ROW_0;
            paint_switch = BLACK;
            DEBUG((DBG_BITMAPS, "(gf) new_row_%d\n", x));
        } else switch(op) {
            case GF_SKIP0:
                y++; 
                line = bm_offset(line, bpl);
                x = 0;
                paint_switch = WHITE;
                DEBUG((DBG_BITMAPS, "(gf) skip_0\n"));
                break;
            case GF_SKIP1:
            case GF_SKIP2:
            case GF_SKIP3:
                par = fugetn(p, op - GF_SKIP1 + 1);
                y += par + 1;
                line = bm_offset(line, (par + 1) * bpl);
                x = 0;
                paint_switch = WHITE;
                DEBUG((DBG_BITMAPS, "(gf) skip_%d\n", op - GF_SKIP1));
                break;
            case GF_XXX1:
            case GF_XXX2:
            case GF_XXX3:
            case GF_XXX4: {
#ifndef NODEBUG
                char    *s;

                s = read_string(p, op - GF_XXX1 + 1, NULL, 0);
                DEBUG((DBG_SPECIAL, "(gf) Character %d: Special \"%s\"\n",
                    ch->code, s));
                mdvi_free(s);
#else
                n = fugetn(p, op - GF_XXX1 + 1);
                fseek(p, (long)n, SEEK_CUR);
#endif
                break;
            }
            case GF_YYY:
                n = fuget4(p);
                DEBUG((DBG_SPECIAL, "(gf) Character %d: MF special %u\n",
                    ch->code, n));
                break;
            case GF_NOOP:
                DEBUG((DBG_BITMAPS, "(gf) no_op\n"));
                break;
            default:
                mdvi_error(_("(gf) Character %d: invalid opcode %d\n"),
                       ch->code, op);
                goto error;
        }
        /* chech that we're still inside the bitmap */
        if(x > ch->width || y > ch->height)
            goto toobig;
        DEBUG((DBG_BITMAPS, "(gf) curr_loc @ (%d,%d)\n", x, y));
    }

    if(op != GF_EOC)
        goto error;
    DEBUG((DBG_BITMAPS, "(gf) end of character %d\n", ch->code));
    return 0;

toobig:
    mdvi_error(_("(gf) character %d has an incorrect bounding box\n"),
           ch->code);
error:
    bitmap_destroy(map);
    ch->glyph.data = NULL;
    return -1;
}
Beispiel #6
0
// Issue a message for an error, clean up files and memory, and exit. return
//   value is the the same as 'c'. c :: Error code from the ZEN_ class.
int ziperr(int c, struct Globals *pG)
{
  char errmsg[ERRORLENGTH];
  int i;

  ziperror(c, pG);
  freeup(pG); // free memory for file linked lists, etc.

  if (pG->tempzip != pG->zipfile)
  {
    // using temp file
    if (pG->hOutz == pG->hTempzf)
    // 1.73.2.6 make sure not same
      pG->hOutz = INVALID_HANDLE_VALUE;
    //    if ( pG->hTempzf != INVALID_HANDLE_VALUE )
    Close_Handle(&pG->hTempzf);
    pG->hTempzf = INVALID_HANDLE_VALUE;

    // remove bad file
    destroy(pG->tempzip, pG);
    FREE(pG->tempzip);
    pG->tempzip = NULL;
  }

  if (pG->tempath != NULL)
  {
    FREE(pG->tempath);
    pG->tempath = NULL;
  }

  //  if ( pG->hInz != INVALID_HANDLE_VALUE )
  //  {
  Close_Handle(&pG->hInz);
  //    pG->hInz = INVALID_HANDLE_VALUE;
  //  }

  if (pG->hOutz != INVALID_HANDLE_VALUE)
  {
    Close_Handle(&pG->hOutz);
    //    pG->hOutz = INVALID_HANDLE_VALUE;
    // remove damaged file
    if (pG->verbose)
    {
      Inform(pG, 0, IDIAG, "deleting damaged %s", pG->zipfile);
    }
    destroy(pG->zipfile, pG);
  }

  if (pG->zipfile != NULL)
  {
    FREE(pG->zipfile);
    pG->zipfile = NULL;
  }
  #ifdef CRYPT
    if (pG->user_key)
    // p release user password
    {
      FREE(pG->user_key);
      pG->user_key = NULL;
    }

  #endif
  #ifdef NEVER
    // EWE NOTE: This code is problematic!!!
    // -g option, attempt to restore the old file
    // int k = 0; /* keep count for end header
    // ulg cb = cenbeg; /* get start of central
    // struct zlist *z; /* steps through zfiles linked list
    Inform(pG, 0, 0, "attempting to restore %s to its previous state\n", pG
      ->zipfile);
    fseek(pG->tempzf, pG->cenbeg, SEEK_SET);
    pG->tempzn = pG->cenbeg;
    for (z = pG->zfiles; z != NULL; z = z->nxt)
    {
      putcentral(z, pG->tempzf, pG);
      pG->tempzn += 4+CENHEAD + z->nam + z->cext + z->com;
      k++;
    }

    putend(k, pG->tempzn - cb, cb, pG->zcomlen, pG->zcomment, pG->tempzf);
    Close_Handle(&pG->tempzf);
    //  pG->tempzf = NULL;

    freeup(pG); // free memory for file linked lists,
    ///etc.
    if (pG->zipfile != NULL)
    {
      FREE(pG->zipfile);
      pG->zipfile = NULL;
    }

  #endif
  return c;
}
Beispiel #7
0
/*
**
**  [func] - fsetpos.
**  [desc] - attempts to set the stream file pointer position to the pos offset.
**           if able to set the stream file pointer position to pos then returns
**           0. else returns -1.
**  [entr] - FILE *stream; the pointer to the FILE stream.
**           const fpos_t *pos; the pointer to the source file position buffer.
**  [exit] - 0 if able to set the stream file pointer position. else -1.
**  [prec] - stream is a valid FILE pointer and pos is a valid fpos_t pointer.
**  [post] - the stream file pointer position is modified.
**
*/
int fsetpos(FILE *stream, const fpos_t *pos)
{
  return (fseek(stream, (long)*pos, SEEK_SET));
}
Beispiel #8
0
int main()
{
	SHA256_CTX md_ctx;
	AES_KEY key;
	_AES_CTX ctx;
	uint8_t buf[64], nb[32], enb[32];
	int i, len;
	int nk = BITS >> 5, nr = 6 + nk, key_nb = (nr + 1) * AES_NB * 4;
	FILE *fp, *ofp;
	struct timeval tv_start, tv_end;

	for (len = 0; len < 64; len += 32) {
		SHA256_Init(&md_ctx);
		if (len == 0) {
			SHA256_Update(&md_ctx, KEY, strlen(KEY));
			SHA256_Final(buf, &md_ctx);
		} else {
			SHA256_Update(&md_ctx, buf + len - 32, 32);
			SHA256_Update(&md_ctx, KEY, strlen(KEY));
			SHA256_Final(buf + len, &md_ctx);
		}
	}

	AES_set_encrypt_key(buf, BITS, &key);
	hex_dump((uint8_t *)key.rd_key, key_nb);

	expand_key(&(ctx.key), buf, BITS);
	ctx.encrypt = _AES_ecb_encrypt;
	ctx.decrypt = _AES_ecb_decrypt;
	hex_dump(ctx.key.rd_key, key_nb);


	for (i = 0; i < 32; i++)
		nb[i] = '\0';

	gettimeofday(&tv_start, NULL);
	for (i = 0; i < 1024; i++)
		AES_encrypt(nb, enb, &key);
	gettimeofday(&tv_end, NULL);
	print_elapsed_time(&tv_start, &tv_end);
	hex_dump(enb, 16);

	gettimeofday(&tv_start, NULL);
	for (i = 0; i < 1024; i++)
		ctx.encrypt(nb, enb, &ctx);
	gettimeofday(&tv_end, NULL);
	print_elapsed_time(&tv_start, &tv_end);
	hex_dump(enb, 16);

	for (i = 0; i < 32; i++)
		nb[i] = enb[i];
	ctx.decrypt(nb, enb, &ctx);
	hex_dump(enb, 16);


	if ((fp = fopen("test.bin", "r")) == NULL) {
		fprintf(stderr, "File open failed\n");
		exit(-1);
	}

	while (!feof(fp)) {
		if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) {
			fprintf(stderr, "Failed in call to fread()\n");
			exit(-1);
		}
	}

	fseek(fp, 0, SEEK_SET);
	i = 0;
	gettimeofday(&tv_start, NULL);
	while (!feof(fp)) {
		++i;
		if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) {
			fprintf(stderr, "Failed in call to fread()\n");
			exit(-1);
		}
		AES_encrypt(nb, enb, &key);
	}
	gettimeofday(&tv_end, NULL);
	print_elapsed_time(&tv_start, &tv_end);
	printf("blocks = %d\n", i);

	fseek(fp, 0, SEEK_SET);
	i = 0;
	gettimeofday(&tv_start, NULL);
	while (!feof(fp)) {
		++i;
		if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) {
			fprintf(stderr, "Failed in call to fread()\n");
			exit(-1);
		}
		ctx.encrypt(nb, enb, &ctx);
	}
	gettimeofday(&tv_end, NULL);
	print_elapsed_time(&tv_start, &tv_end);
	printf("blocks = %d\n", i);

	fclose(fp);


	fp = fopen("test.enc", "r");
	ofp = fopen("tmp.bin", "w");
	ctx.encrypt = _AES_cbc_encrypt;
	ctx.decrypt = _AES_cbc_decrypt;
	memcpy(ctx.ivec, buf + 32, _AES_BLOCK_SIZE);
	while (!feof(fp)) {
		if (fread(nb, 1, _AES_BLOCK_SIZE, fp) == 0) {
			fprintf(stderr, "Failed in call to fread()\n");
			exit(-1);
		}
		ctx.decrypt(nb, enb, &ctx);
		fwrite(enb, 1, _AES_BLOCK_SIZE, ofp);
	}
	fclose(fp);
	fclose(ofp);

	return 0;
}
Beispiel #9
0
static int d2ladder_readladder(void)
{
	FILE				* fp;
	t_d2ladderfile_ladderindex	* ladderheader;
	t_d2ladderfile_ladderinfo	* ladderinfo;
	char				* ladderfile;
	t_d2ladderfile_header		header;
	unsigned int			i, n, temp, count, type, number;

	ladderfile=xmalloc(strlen(prefs_get_ladder_dir())+1+strlen(LADDER_FILE_PREFIX)+1+
			strlen(CLIENTTAG_DIABLO2DV)+1);
	sprintf(ladderfile,"%s/%s.%s",prefs_get_ladder_dir(),LADDER_FILE_PREFIX,CLIENTTAG_DIABLO2DV);
	if (!(fp=fopen(ladderfile,"rb"))) {
		eventlog(eventlog_level_error,__FUNCTION__,"error opening ladder file \"%s\" for reading (fopen: %s)",ladderfile,strerror(errno));
		xfree(ladderfile);
		return -1;
	}
	xfree(ladderfile);
	if (fread(&header,1,sizeof(header),fp)!=sizeof(header)) {
		eventlog(eventlog_level_error,__FUNCTION__,"error reading ladder file");
		fclose(fp);
		return -1;
	}
	max_ladder_type= bn_int_get(header.maxtype);
	if (d2ladderlist_create(max_ladder_type)<0) {
		eventlog(eventlog_level_error,__FUNCTION__,"error create ladder list");
		fclose(fp);
		return -1;
	}
	temp= max_ladder_type * sizeof(*ladderheader);
	ladderheader=xmalloc(temp);
	if (fread(ladderheader,1,temp,fp)!=temp) {
		eventlog(eventlog_level_error,__FUNCTION__,"error read ladder file");
		xfree(ladderheader);
		fclose(fp);
		return -1;
	}
	for (i=0, count=0; i< max_ladder_type ; i++) {
		type=bn_int_get(ladderheader[i].type);
		number=bn_int_get(ladderheader[i].number);
		if (d2ladder_create(type,number)<0) {
			eventlog(eventlog_level_error,__FUNCTION__,"error create ladder %d",type);
			continue;
		}
		fseek(fp,bn_int_get(ladderheader[i].offset),SEEK_SET);
		temp=number * sizeof(*ladderinfo);
		ladderinfo=xmalloc(temp);
		if (fread(ladderinfo,1,temp,fp)!=temp) {
			eventlog(eventlog_level_error,__FUNCTION__,"error read ladder file");
			xfree(ladderinfo);
			continue;
		}
		for (n=0; n< number; n++) {
			d2ladder_append_ladder(type,ladderinfo+n);
		}
		xfree(ladderinfo);
		if (number) count++;
	}
	xfree(ladderheader);
	fclose(fp);
	eventlog(eventlog_level_info,__FUNCTION__,"ladder file loaded successfully (%d types %d maxtype)",count,max_ladder_type);
	return 0;
}
Beispiel #10
0
Datei: vtls.c Projekt: curl/curl
CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
                              const char *pinnedpubkey,
                              const unsigned char *pubkey, size_t pubkeylen)
{
  FILE *fp;
  unsigned char *buf = NULL, *pem_ptr = NULL;
  long filesize;
  size_t size, pem_len;
  CURLcode pem_read;
  CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
#ifdef curlssl_sha256sum
  CURLcode encode;
  size_t encodedlen, pinkeylen;
  char *encoded, *pinkeycopy, *begin_pos, *end_pos;
  unsigned char *sha256sumdigest = NULL;
#endif

  /* if a path wasn't specified, don't pin */
  if(!pinnedpubkey)
    return CURLE_OK;
  if(!pubkey || !pubkeylen)
    return result;

  /* only do this if pinnedpubkey starts with "sha256//", length 8 */
  if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
#ifdef curlssl_sha256sum
    /* compute sha256sum of public key */
    sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
    if(!sha256sumdigest)
      return CURLE_OUT_OF_MEMORY;
    curlssl_sha256sum(pubkey, pubkeylen,
                      sha256sumdigest, SHA256_DIGEST_LENGTH);
    encode = Curl_base64_encode(data, (char *)sha256sumdigest,
                                SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
    Curl_safefree(sha256sumdigest);

    if(encode)
      return encode;

    infof(data, "\t public key hash: sha256//%s\n", encoded);

    /* it starts with sha256//, copy so we can modify it */
    pinkeylen = strlen(pinnedpubkey) + 1;
    pinkeycopy = malloc(pinkeylen);
    if(!pinkeycopy) {
      Curl_safefree(encoded);
      return CURLE_OUT_OF_MEMORY;
    }
    memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
    /* point begin_pos to the copy, and start extracting keys */
    begin_pos = pinkeycopy;
    do {
      end_pos = strstr(begin_pos, ";sha256//");
      /*
       * if there is an end_pos, null terminate,
       * otherwise it'll go to the end of the original string
       */
      if(end_pos)
        end_pos[0] = '\0';

      /* compare base64 sha256 digests, 8 is the length of "sha256//" */
      if(encodedlen == strlen(begin_pos + 8) &&
         !memcmp(encoded, begin_pos + 8, encodedlen)) {
        result = CURLE_OK;
        break;
      }

      /*
       * change back the null-terminator we changed earlier,
       * and look for next begin
       */
      if(end_pos) {
        end_pos[0] = ';';
        begin_pos = strstr(end_pos, "sha256//");
      }
    } while(end_pos && begin_pos);
    Curl_safefree(encoded);
    Curl_safefree(pinkeycopy);
#else
    /* without sha256 support, this cannot match */
    (void)data;
#endif
    return result;
  }

  fp = fopen(pinnedpubkey, "rb");
  if(!fp)
    return result;

  do {
    /* Determine the file's size */
    if(fseek(fp, 0, SEEK_END))
      break;
    filesize = ftell(fp);
    if(fseek(fp, 0, SEEK_SET))
      break;
    if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
      break;

    /*
     * if the size of our certificate is bigger than the file
     * size then it can't match
     */
    size = curlx_sotouz((curl_off_t) filesize);
    if(pubkeylen > size)
      break;

    /*
     * Allocate buffer for the pinned key
     * With 1 additional byte for null terminator in case of PEM key
     */
    buf = malloc(size + 1);
    if(!buf)
      break;

    /* Returns number of elements read, which should be 1 */
    if((int) fread(buf, size, 1, fp) != 1)
      break;

    /* If the sizes are the same, it can't be base64 encoded, must be der */
    if(pubkeylen == size) {
      if(!memcmp(pubkey, buf, pubkeylen))
        result = CURLE_OK;
      break;
    }

    /*
     * Otherwise we will assume it's PEM and try to decode it
     * after placing null terminator
     */
    buf[size] = '\0';
    pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
    /* if it wasn't read successfully, exit */
    if(pem_read)
      break;

    /*
     * if the size of our certificate doesn't match the size of
     * the decoded file, they can't be the same, otherwise compare
     */
    if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
      result = CURLE_OK;
  } while(0);

  Curl_safefree(buf);
  Curl_safefree(pem_ptr);
  fclose(fp);

  return result;
}
Beispiel #11
0
ILint64  ILAPIENTRY mySeek (SIO* io, ILint64 offset, ILuint origin)
{
	return fseek(writeFile, offset, origin);
}
Beispiel #12
0
void tablecalc_2D(int oplx, int oply, int nx, float dx, int ny, float dy, float dz, float alpha, float fmin, float fmax, float cmin, float cmax, float df, float weight, int fine, int method, char *file_table, int verbose)
{
	int 	ikx, nkx, nky, nkx2, nky2, hoplx, hoply, ntable, ix, iy;
	int     size;
	float	k, kmax, wfact, fampl, w_start, limit, k1, k2;
	complex *hopkx, *hopx;

	kmin   = 2.0*M_PI*(MAX(fmin-df,0))/cmax;
	kmax   = 2.0*M_PI*(fmax+df)/cmin;
	dkx    = 2.0*M_PI*df/(float)(cmax*fine);
	ntable = (int)((kmax - kmin)/dkx)+1;
	nkx	   = pow(2.0, ceil(log(nx)/log(2.0)));
	nky	   = pow(2.0, ceil(log(ny)/log(2.0)));
	nkx = nky = 512;
	nkx2   = nkx/2+1;
	nky2   = nky/2+1;
	hoplx  = (oplx+1)/2;
	hoply  = (oply+1)/2;
	size   = hoplx*hoply;
    w_start= 1e-6;
	limit  = 1.002;


	if (file_table != NULL) { /* read table from file */
		FILE *fp;
		size_t nread, bytes, trace_sz;
		segy hdr;

		fp = fopen(file_table, "r");
		assert(fp);
		nread = fread( &hdr, 1, TRCBYTES, fp );
		assert (nread == TRCBYTES);

		trace_sz = sizeof(float)*hdr.ns+TRCBYTES;
		fseek ( fp, 0, SEEK_END );
		bytes = ftell(fp);
		ntable  = (int) (bytes/trace_sz);
		assert (ntable == hdr.trwf);

		/* check if table is correct for this model */
		if (kmin >= hdr.f1) kmin = hdr.f1;
		dkx = hdr.d1;
		assert(size == (hdr.ns/2));

		table = (complex *)malloc(size*ntable*sizeof(complex));

		fseek ( fp, 0, SEEK_SET );
		for (ikx = 0; ikx < ntable; ikx++) {
			nread = fread( &hdr, 1, TRCBYTES, fp );
			assert (nread == TRCBYTES);
			nread = fread( &table[ikx*size].r, sizeof(float), hdr.ns, fp );
			assert (nread == hdr.ns); 
		}
		if (verbose) {
			fprintf(stderr,"Number of operators read in = %d\n", ntable);
			fprintf(stderr,"Size of operator table = %d bytes \n", (int)sizeof(complex)*ntable*size);
			fflush(stderr);
		}
		return;
	}

	if (verbose) {
		fprintf(stderr,"Number of operators to calculate = %d\n", ntable);
		fprintf(stderr,"Size of operator table = %d bytes \n", (int)sizeof(complex)*ntable*hoplx*hoply);
		fprintf(stderr,"Operator calculation = %d\n",method);
	}

	hopkx = (complex *)malloc(nkx2*nky2*sizeof(complex));
	assert (hopkx != NULL);
	hopx  = (complex *)malloc(hoplx*hoply*sizeof(complex));
	assert (hopx != NULL);
	table = (complex *)malloc(hoplx*hoply*ntable*sizeof(complex));
	assert (table != NULL);

/* WLSQ operator */

	k = kmin;
	for (ikx = 0; ikx < ntable; ikx++) {

		if (method == 1) {
			Woper3d_ph(k, dx, dy, dz, nkx2, nky2, alpha, hopkx);
			wfact = weight;
			if (ikx==0) fprintf(stderr,"smooth phase operator weight = %e\n", wfact);
		}
		else if (method == 2) {
			Woper3d(k, dx, dy, dz, nkx2, nky2, hopkx);
			wfact = weight;
			if (ikx==0) fprintf(stderr,"phase shift operator weight = %e\n", wfact);
			fprintf(stderr,"phase shift operator weight = %e\n", wfact);
		}
		else {
			if (ikx==0) fprintf(stderr,"standard direct convolution operator\n");
			W3d(k, dx, dy, dz, nkx2, nky2, alpha, hopkx, &wfact);
		}

		if (dx == dy) {
			wlsq2d8c(hopkx,nkx2,hopx,hoplx,dx,k,alpha,wfact);

			table[ikx*size].r = 0.25*hopx[0].r;
			table[ikx*size].i = 0.25*hopx[0].i;
			for (ix = 1; ix < hoplx; ix++) {
				table[ikx*size+ix].r = 0.5*hopx[ix].r;
				table[ikx*size+ix].i = 0.5*hopx[ix].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				table[ikx*size+iy*hoplx].r = 0.5*hopx[iy*hoplx].r;
				table[ikx*size+iy*hoplx].i = 0.5*hopx[iy*hoplx].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				for (ix = 1; ix < hoplx; ix++) {
					table[ikx*size+iy*hoplx+ix] = hopx[iy*hoplx+ix];
				}
			}
		
/*
			wlsq2dc(hopkx,nkx2,nky2,hopx,hoplx,hoply,dx,dy,k,alpha,wfact);

			table[ikx*size].r = 0.25*hopx[0].r;
			table[ikx*size].i = 0.25*hopx[0].i;
			for (ix = 1; ix < hoplx; ix++) {
				table[ikx*size+ix].r = 0.5*hopx[ix].r;
				table[ikx*size+ix].i = 0.5*hopx[ix].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				table[ikx*size+iy*hoplx].r = 0.5*hopx[iy*hoplx].r;
				table[ikx*size+iy*hoplx].i = 0.5*hopx[iy*hoplx].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				for (ix = 1; ix < hoplx; ix++) {
					table[ikx*size+iy*hoplx+ix] = hopx[iy*hoplx+ix];
				}
			}
*/


		}
		else {
			wlsq2dc(hopkx,nkx2,nky2,hopx,hoplx,hoply,dx,dy,k,alpha,wfact);

			table[ikx*size].r = 0.25*hopx[0].r;
			table[ikx*size].i = 0.25*hopx[0].i;
			for (ix = 1; ix < hoplx; ix++) {
				table[ikx*size+ix].r = 0.5*hopx[ix].r;
				table[ikx*size+ix].i = 0.5*hopx[ix].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				table[ikx*size+iy*hoplx].r = 0.5*hopx[iy*hoplx].r;
				table[ikx*size+iy*hoplx].i = 0.5*hopx[iy*hoplx].i;
			}
			for (iy = 1; iy < hoply; iy++) {
				for (ix = 1; ix < hoplx; ix++) {
					table[ikx*size+iy*hoplx+ix] = hopx[iy*hoplx+ix];
				}
			}
		}

		k += dkx;
	}

	free(hopx);
	free(hopkx);

	return;
}
Beispiel #13
0
int main(int argc, const char* argv[]) {
  int log_tab_size = 12;
  int compress = 1;
  FSCCodingMethod method = CODING_METHOD_DEFAULT;
  int stats_only = 0;
  int ok = 0;
  int c;

  for (c = 1; c < argc; ++c) {
    if (!strcmp(argv[c], "-l") && c + 1 < argc) {
      log_tab_size = atoi(argv[++c]);
      if (log_tab_size > LOG_TAB_SIZE) log_tab_size = LOG_TAB_SIZE;
      else if (log_tab_size < 2) log_tab_size = 2;
    } else if (FSCParseCodingMethodOpt(argv[c], &method)) {
      continue;
    } else if (!strcmp(argv[c], "-m") && c + 1 < argc) {
      method = (FSCCodingMethod)atoi(argv[++c]);
    } else if (!strcmp(argv[c], "-s")) {
      stats_only = 1;
    } else if (!strcmp(argv[c], "-c")) {
      compress = 1;
    } else if (!strcmp(argv[c], "-d")) {
      compress = 0;
    } else if (!strcmp(argv[c], "-h")) {
      Help();
    }
  }

  uint8_t* out = NULL;
  size_t out_size = 0;
  uint8_t* in = NULL;
  size_t in_size = 0;

  // Read input
  fseek(stdin, 0L, SEEK_END);
  in_size = ftell(stdin);
  fseek(stdin, 0L, SEEK_SET);
  if (in_size == (size_t)-1) {
    fprintf(stderr, "Missing/erroneous input!\n");
    goto End;
  }
  in = (uint8_t*)malloc(in_size * sizeof(*in));
  if (in == NULL) {
    fprintf(stderr, "Malloc(%lu) failed!\n", in_size);
    exit(-1);
  }
  ok = (fread(in, in_size, 1, stdin) == 1);
  if (!ok) {
    fprintf(stderr, "Error reading from stdin!\n");
    goto End;
  }

  // Compress or decompress.
  MyClock start, tmp;
  if (compress) {   // encoding
    GetElapsed(&start, NULL);
    ok = FSCEncode(in, in_size, &out, &out_size, log_tab_size, method);
    if (!ok) {
      fprintf(stderr, "ERROR while encoding!\n");
      goto End;
    }

    if (stats_only) {
      const double elapsed = GetElapsed(&tmp, &start);
      const double entropy = GetEntropy(in, in_size);
      const double MS = 1.e-6 * in_size;
      const double reduction = 1. * out_size / in_size;
      printf("Enc time: %.3f sec [%.2lf MS/s] (%ld bytes out, %ld in).\n",
             elapsed, MS / elapsed, out_size, in_size);
      printf("Entropy: %.4lf vs expected %.4lf "
             "(off by %.5lf bit/symbol [%.3lf%%])\n",
             reduction, entropy, reduction - entropy,
             100. * (reduction - entropy) / entropy);
    }
  } else {         // decoding
    GetElapsed(&start, NULL);
    ok = FSCDecode(in, in_size, &out, &out_size);
    if (!ok) {
      fprintf(stderr, "ERROR while decoding!\n");
      goto End;
    }
    if (stats_only) {
      const double elapsed = GetElapsed(&tmp, &start);
      const double MS = 1.e-6 * out_size;
      printf("Dec time: %.3f sec [%.2lf MS/s].\n", elapsed, MS / elapsed);
    }
  }

  if (!stats_only) {
    ok = (fwrite(out, out_size, 1, stdout) == 1);
    if (!ok) {
      fprintf(stderr, "Error writing to stdout!\n");
      goto End;
    }
  }

 End:
  free(in);
  free(out);
  return !ok;
}
void
main (int argc, char **argv)
{
  int i;
  if (argc != 4)
    {
      printf ("Syntax: convfont fontfile fontheight vgafontfile\n");
      printf (
      "\nconvfont - convert standard format binary font to codepage format\n"
	       "The converted font is written to vgafontfile.\n");
      printf (
	       "A binary font file of any number of characters up to 256 can be used, although\n"
	       "at least defining the first 128 characters is a good idea. The fontheight\n"
	       "should be in the range 1-32.\n"
	);
      exit (1);
    }
  if ((sf = fopen (argv[1], "rb")) == NULL)
    {
      printf ("convfont: Unable to open file.\n");
      exit (1);
    }
  if ((tf = fopen (argv[3], "wb")) == NULL)
    {
      printf ("convfont: Unable to create file.\n");
      exit (1);
    }
  fontheight = atoi (argv[2]);
  if (fontheight < 1 || fontheight > 32)
    {
      printf ("convfont: Invalid fontheight.\n");
      exit (1);
    }

  fseek (sf, 0, SEEK_END);
  sfontsize = ftell (sf);
  fseek (sf, 0, SEEK_SET);
  font_nuchars = sfontsize / fontheight;
  printf ("Converting %d characters\n", font_nuchars);
  if (font_nuchars < 1 || font_nuchars > 256)
    {
      printf ("convfont: Invalid number of characters in font.\n");
      exit (1);
    }
  fread (sfontbuf, 1, sfontsize, sf);
  fclose (sf);
  for (i = 0; i < font_nuchars; i++)
    {
      int j;

      for (j = 0; j < fontheight; j++)
	tfontbuf[i * 32 + j] =
	  sfontbuf[i * fontheight + j];

      for (j = 0; j < 32 - fontheight; j++)
	tfontbuf[i * 32 + fontheight] = 0;
    }
  /* clear remaining characters */
  for (i = font_nuchars * 32; i < 32 * 256; i++)
    tfontbuf[i] = 0;
  printf ("Writing font file.\n");
  fwrite (tfontbuf, 1, 32 * 256, tf);
  fclose (tf);
  exit (0);
}
static int32 ini_write_mode_value(INI_FILE *fp, int32 modu, int8 * puc_var, int8 * puc_value)
{
	int32 l_len;
	int32 ret;
	int8 auc_tmp[MAX_READ_LINE_NUM + 1] = {0};
	int8 auc_mode_var[INI_STR_MODU_LEN + 1] = {0};
	int8 *puc_val = NULL;
	int8 auc_change_bin[INI_STR_MODU_LEN * 2 + 1] = {0};
	int8 auc_cmd[INI_STR_MODU_LEN * 4 + 1] = {0};
    int16 search_var_len;

	switch (modu)
	{
		case INI_MODU_WIFI:			 
			strncpy(auc_mode_var, INI_MODE_VAR_WIFI, INI_STR_MODU_LEN);
			if ('0' > puc_value[0] || '2' < puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			break;
		case INI_MODU_GNSS:			 
			if ('0' > puc_value[0] || '1' < puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			strncpy(auc_mode_var, INI_MODE_VAR_GNSS, INI_STR_MODU_LEN);
			break;
		case INI_MODU_BT:			 
			if ('0' != puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			strncpy(auc_mode_var, INI_MODE_VAR_BT, INI_STR_MODU_LEN);
			break;
		case INI_MODU_FM:			 
			if ('0' != puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			strncpy(auc_mode_var, INI_MODE_VAR_FM, INI_STR_MODU_LEN);
			break;
		case INI_MODU_WIFI_PLAT:			 
			if ('0' != puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			strncpy(auc_mode_var, INI_MODE_VAR_WIFI_PLAT, INI_STR_MODU_LEN);
			break;
		case INI_MODU_BFG_PLAT:			 
			if ('0' != puc_value[0])
			{
				INI_ERROR("not support mode!!!");
				return INI_FAILED;
			}
			strncpy(auc_mode_var, INI_MODE_VAR_BFG_PLAT, INI_STR_MODU_LEN);
			break;
		default :
			INI_ERROR("not suport modu type!!!");
			break;
	}

	while(1)
	{
        ret = ini_readline_func(fp, auc_tmp);
        if (INI_FAILED == ret)
        {
            INI_ERROR("have end of .ini file!!!");
            return INI_FAILED;
        }

		if (NULL != strstr(auc_tmp, INI_STR_WIFI_NORMAL0))
		{
			INI_ERROR("not find %s!!!", auc_mode_var);
			return INI_FAILED;
		}
		
        ret = ini_check_str(fp, auc_tmp, auc_mode_var);
        if (INI_SUCC == ret)
        {
            INI_DEBUG("have found %s", auc_mode_var);
            break;
        }
        else
        {
            continue;
        }
	}

	puc_val = strstr(auc_tmp, "=");
	if (NULL == puc_val)
	{
		INI_ERROR("has not find = in %s", auc_tmp);
		return INI_FAILED;
	}
	if (INI_FAILED == ini_check_value(puc_val + 1))
	{
		INI_ERROR("not support to write :%s:", auc_tmp);
		return INI_FAILED;
	}
	
	l_len = strlen(auc_tmp);
	search_var_len = strlen(puc_var);
    strncpy(&auc_tmp[search_var_len+1], puc_value, 1);

	if (INI_FAILED == fseek(fp, -l_len, SEEK_CUR))
	{
		INI_ERROR("file seek failed!!!");
		return INI_FAILED;
	}
	if (fputs(auc_tmp, fp))
	{
		INI_DEBUG("puc_write_val :%s: ok", auc_tmp);
	}
	
    if (INI_MODU_WIFI == modu)
    {
        if ('0' == puc_value[0])
        {
            strncpy(auc_change_bin, INI_SDIOBIN_NORMAL, INI_STR_MODU_LEN * 2);
        }
        else if ('1' == puc_value[0])
        {
            strncpy(auc_change_bin, INI_SDIOBIN_PERFORMANCE, INI_STR_MODU_LEN * 2);
        }
        else if ('2' == puc_value[0])
        {
            strncpy(auc_change_bin, INI_SDIOBIN_CERTIFY, INI_STR_MODU_LEN * 2);
        }
        else
        {
            INI_ERROR("not support to bin type %s", auc_change_bin);
            return INI_FAILED;
        }
        sprintf(auc_cmd, INI_STR_MODU_LEN * 4,"cp %s %s", auc_change_bin, INI_SDIOBIN_DEFAULT);
        INI_INFO("exct %s", auc_cmd);
        system(auc_cmd);
    }

	return INI_SUCC;
}
Beispiel #16
0
ModelInstance::ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile)
{
    float ff[3];
    f.read(&id, 4);
    f.read(ff, 12);
    pos = fixCoords(Vec3D(ff[0], ff[1], ff[2]));
    f.read(ff, 12);
    rot = Vec3D(ff[0], ff[1], ff[2]);
    f.read(&scale, 2);
    f.read(&flags, 2);
    // scale factor - divide by 1024. blizzard devs must be on crack, why not just use a float?
    sc = scale / 1024.0f;

    char tempname[512];
    sprintf(tempname, "%s/%s", szWorkDirWmo, ModelInstName);
    FILE* input = fopen(tempname, "r+b");

    if (!input)
    {
        //printf("ModelInstance::ModelInstance couldn't open %s\n", tempname);
        return;
    }

    fseek(input, 8, SEEK_SET); // get the correct no of vertices
    int nVertices;
    int count = fread(&nVertices, sizeof (int), 1, input);
    fclose(input);

    if (count != 1 || nVertices == 0)
        return;

    uint16 adtId = 0;// not used for models
    uint32 flags = MOD_M2;
    if (tileX == 65 && tileY == 65)
        flags |= MOD_WORLDSPAWN;

    //write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, name
    fwrite(&mapID, sizeof(uint32), 1, pDirfile);
    fwrite(&tileX, sizeof(uint32), 1, pDirfile);
    fwrite(&tileY, sizeof(uint32), 1, pDirfile);
    fwrite(&flags, sizeof(uint32), 1, pDirfile);
    fwrite(&adtId, sizeof(uint16), 1, pDirfile);
    fwrite(&id, sizeof(uint32), 1, pDirfile);
    fwrite(&pos, sizeof(float), 3, pDirfile);
    fwrite(&rot, sizeof(float), 3, pDirfile);
    fwrite(&sc, sizeof(float), 1, pDirfile);
    uint32 nlen=strlen(ModelInstName);
    fwrite(&nlen, sizeof(uint32), 1, pDirfile);
    fwrite(ModelInstName, sizeof(char), nlen, pDirfile);

    /* int realx1 = (int) ((float) pos.x / 533.333333f);
    int realy1 = (int) ((float) pos.z / 533.333333f);
    int realx2 = (int) ((float) pos.x / 533.333333f);
    int realy2 = (int) ((float) pos.z / 533.333333f);

    fprintf(pDirfile,"%s/%s %f,%f,%f_%f,%f,%f %f %d %d %d,%d %d\n",
        MapName,
        ModelInstName,
        (float) pos.x, (float) pos.y, (float) pos.z,
        (float) rot.x, (float) rot.y, (float) rot.z,
        sc,
        nVertices,
        realx1, realy1,
        realx2, realy2
        ); */
}
Beispiel #17
0
int main(int argc, char **argv)
{
	char inbuf[4096];
	struct addr_range vmlinux;
	FILE *ramDisk;
	FILE *inputVmlinux;
	FILE *outputVmlinux;

	char *rd_name, *lx_name, *out_name;

	size_t i;
	unsigned long ramFileLen;
	unsigned long ramLen;
	unsigned long roundR;
	unsigned long offset_end;

	unsigned long kernelLen;
	unsigned long actualKernelLen;
	unsigned long round;
	unsigned long roundedKernelLen;
	unsigned long ramStartOffs;
	unsigned long ramPages;
	unsigned long roundedKernelPages;
	unsigned long hvReleaseData;
	u_int32_t eyeCatcher = 0xc8a5d9c4;
	unsigned long naca;
	unsigned long xRamDisk;
	unsigned long xRamDiskSize;
	long padPages;
  
  
	if (argc < 2) {
		fprintf(stderr, "Name of RAM disk file missing.\n");
		exit(1);
	}
	rd_name = argv[1];

	if (argc < 3) {
		fprintf(stderr, "Name of vmlinux file missing.\n");
		exit(1);
	}
	lx_name = argv[2];

	if (argc < 4) {
		fprintf(stderr, "Name of vmlinux output file missing.\n");
		exit(1);
	}
	out_name = argv[3];


	ramDisk = fopen(rd_name, "r");
	if ( ! ramDisk ) {
		fprintf(stderr, "RAM disk file \"%s\" failed to open.\n", rd_name);
		exit(1);
	}

	inputVmlinux = fopen(lx_name, "r");
	if ( ! inputVmlinux ) {
		fprintf(stderr, "vmlinux file \"%s\" failed to open.\n", lx_name);
		exit(1);
	}
  
	outputVmlinux = fopen(out_name, "w+");
	if ( ! outputVmlinux ) {
		fprintf(stderr, "output vmlinux file \"%s\" failed to open.\n", out_name);
		exit(1);
	}

	i = fread(inbuf, 1, sizeof(inbuf), inputVmlinux);
	if (i != sizeof(inbuf)) {
		fprintf(stderr, "can not read vmlinux file %s: %u\n", lx_name, i);
		exit(1);
	}

	i = check_elf64(inbuf, sizeof(inbuf), &vmlinux);
	if (i == 0) {
		fprintf(stderr, "You must have a linux kernel specified as argv[2]\n");
		exit(1);
	}

	/* Input Vmlinux file */
	fseek(inputVmlinux, 0, SEEK_END);
	kernelLen = ftell(inputVmlinux);
	fseek(inputVmlinux, 0, SEEK_SET);
	printf("kernel file size = %lu\n", kernelLen);

	actualKernelLen = kernelLen - ElfHeaderSize;

	printf("actual kernel length (minus ELF header) = %lu\n", actualKernelLen);

	round = actualKernelLen % 4096;
	roundedKernelLen = actualKernelLen;
	if ( round )
		roundedKernelLen += (4096 - round);
	printf("Vmlinux length rounded up to a 4k multiple = %ld/0x%lx \n", roundedKernelLen, roundedKernelLen);
	roundedKernelPages = roundedKernelLen / 4096;
	printf("Vmlinux pages to copy = %ld/0x%lx \n", roundedKernelPages, roundedKernelPages);

	offset_end = _ALIGN_UP(vmlinux.memsize, 4096);
	/* calc how many pages we need to insert between the vmlinux and the start of the ram disk */
	padPages = offset_end/4096 - roundedKernelPages;

	/* Check and see if the vmlinux is already larger than _end in System.map */
	if (padPages < 0) {
		/* vmlinux is larger than _end - adjust the offset to the start of the embedded ram disk */ 
		offset_end = roundedKernelLen;
		printf("vmlinux is larger than _end indicates it needs to be - offset_end = %lx \n", offset_end);
		padPages = 0;
		printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages);
	}
	else {
		/* _end is larger than vmlinux - use the offset to _end that we calculated from the system map */
		printf("vmlinux is smaller than _end indicates is needed - offset_end = %lx \n", offset_end);
		printf("will insert %lx pages between the vmlinux and the start of the ram disk \n", padPages);
	}



	/* Input Ram Disk file */
	// Set the offset that the ram disk will be started at.
	ramStartOffs = offset_end;  /* determined from the input vmlinux file and the system map */
	printf("Ram Disk will start at offset = 0x%lx \n", ramStartOffs);
  
	fseek(ramDisk, 0, SEEK_END);
	ramFileLen = ftell(ramDisk);
	fseek(ramDisk, 0, SEEK_SET);
	printf("%s file size = %ld/0x%lx \n", rd_name, ramFileLen, ramFileLen);

	ramLen = ramFileLen;

	roundR = 4096 - (ramLen % 4096);
	if ( roundR ) {
		printf("Rounding RAM disk file up to a multiple of 4096, adding %ld/0x%lx \n", roundR, roundR);
		ramLen += roundR;
	}

	printf("Rounded RAM disk size is %ld/0x%lx \n", ramLen, ramLen);
	ramPages = ramLen / 4096;
	printf("RAM disk pages to copy = %ld/0x%lx\n", ramPages, ramPages);



  // Copy 64K ELF header
	for (i=0; i<(ElfPages); ++i) {
		get4k( inputVmlinux, inbuf );
		put4k( outputVmlinux, inbuf );
	}

	/* Copy the vmlinux (as full pages). */
	fseek(inputVmlinux, ElfHeaderSize, SEEK_SET);
	for ( i=0; i<roundedKernelPages; ++i ) {
		get4k( inputVmlinux, inbuf );
		put4k( outputVmlinux, inbuf );
	}
  
	/* Insert pad pages (if appropriate) that are needed between */
	/* | the end of the vmlinux and the ram disk. */
	for (i=0; i<padPages; ++i) {
		memset(inbuf, 0, 4096);
		put4k(outputVmlinux, inbuf);
	}

	/* Copy the ram disk (as full pages). */
	for ( i=0; i<ramPages; ++i ) {
		get4k( ramDisk, inbuf );
		put4k( outputVmlinux, inbuf );
	}

	/* Close the input files */
	fclose(ramDisk);
	fclose(inputVmlinux);
	/* And flush the written output file */
	fflush(outputVmlinux);



	/* Fixup the new vmlinux to contain the ram disk starting offset (xRamDisk) and the ram disk size (xRamDiskSize) */
	/* fseek to the hvReleaseData pointer */
	fseek(outputVmlinux, ElfHeaderSize + 0x24, SEEK_SET);
	if (fread(&hvReleaseData, 4, 1, outputVmlinux) != 1) {
		death("Could not read hvReleaseData pointer\n", outputVmlinux, out_name);
	}
	hvReleaseData = ntohl(hvReleaseData); /* Convert to native int */
	printf("hvReleaseData is at %08lx\n", hvReleaseData);

	/* fseek to the hvReleaseData */
	fseek(outputVmlinux, ElfHeaderSize + hvReleaseData, SEEK_SET);
	if (fread(inbuf, 0x40, 1, outputVmlinux) != 1) {
		death("Could not read hvReleaseData\n", outputVmlinux, out_name);
	}
	/* Check hvReleaseData sanity */
	if (memcmp(inbuf, &eyeCatcher, 4) != 0) {
		death("hvReleaseData is invalid\n", outputVmlinux, out_name);
	}
	/* Get the naca pointer */
	naca = ntohl(*((u_int32_t*) &inbuf[0x0C])) - KERNELBASE;
	printf("Naca is at offset 0x%lx \n", naca);

	/* fseek to the naca */
	fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET);
	if (fread(inbuf, 0x18, 1, outputVmlinux) != 1) {
		death("Could not read naca\n", outputVmlinux, out_name);
	}
	xRamDisk = ntohl(*((u_int32_t *) &inbuf[0x0c]));
	xRamDiskSize = ntohl(*((u_int32_t *) &inbuf[0x14]));
	/* Make sure a RAM disk isn't already present */
	if ((xRamDisk != 0) || (xRamDiskSize != 0)) {
		death("RAM disk is already attached to this kernel\n", outputVmlinux, out_name);
	}
	/* Fill in the values */
	*((u_int32_t *) &inbuf[0x0c]) = htonl(ramStartOffs);
	*((u_int32_t *) &inbuf[0x14]) = htonl(ramPages);

	/* Write out the new naca */
	fflush(outputVmlinux);
	fseek(outputVmlinux, ElfHeaderSize + naca, SEEK_SET);
	if (fwrite(inbuf, 0x18, 1, outputVmlinux) != 1) {
		death("Could not write naca\n", outputVmlinux, out_name);
	}
	printf("Ram Disk of 0x%lx pages is attached to the kernel at offset 0x%08lx\n",
	       ramPages, ramStartOffs);

	/* Done */
	fclose(outputVmlinux);
	/* Set permission to executable */
	chmod(out_name, S_IRUSR|S_IWUSR|S_IXUSR|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);

	return 0;
}
int
rrd_resize(int argc, char **argv)
{
    char		*infilename,outfilename[11]="resize.rrd";
    FILE		*infile,*outfile;
    rrd_t		rrdold,rrdnew;
    rrd_value_t		buffer;
    int			version;
    unsigned long	l,rra;
    long		modify;
    unsigned long	target_rra;
    int			grow=0,shrink=0;
    char		*endptr;

    infilename=argv[1];
    if (!strcmp(infilename,"resize.rrd")) {
        rrd_set_error("resize.rrd is a reserved name");
        return(-1);
    }
    if (argc!=5) {
        rrd_set_error("wrong number of parameters");
        return(-1);
    }

    target_rra=strtol(argv[2],&endptr,0);

    if (!strcmp(argv[3],"GROW")) grow=1;
    else if (!strcmp(argv[3],"SHRINK")) shrink=1;
    else {
        rrd_set_error("I can only GROW or SHRINK");
        return(-1);
    }

    modify=strtol(argv[4],&endptr,0);

    if ((modify<1)) {
        rrd_set_error("Please grow or shrink with at least 1 row");
        return(-1);
    }

    if (shrink) modify = -modify;


    if (rrd_open(infilename, &infile, &rrdold, RRD_READWRITE)==-1) {
        rrd_set_error("could not open RRD");
        return(-1);
    }
    if (LockRRD(infile) != 0) {
        rrd_set_error("could not lock original RRD");
        rrd_free(&rrdold);
        fclose(infile);
        return(-1);
    }

    if (target_rra >= rrdold.stat_head->rra_cnt) {
        rrd_set_error("no such RRA in this RRD");
        rrd_free(&rrdold);
        fclose(infile);
        return(-1);
    }

    if (modify < 0)
	if ((long)rrdold.rra_def[target_rra].row_cnt <= -modify) {
	    rrd_set_error("This RRA is not that big");
	    rrd_free(&rrdold);
	    fclose(infile);
	    return(-1);
	}

    rrdnew.stat_head = rrdold.stat_head;
    rrdnew.ds_def    = rrdold.ds_def;
    rrdnew.rra_def   = rrdold.rra_def;
    rrdnew.live_head = rrdold.live_head;
    rrdnew.pdp_prep  = rrdold.pdp_prep;
    rrdnew.cdp_prep  = rrdold.cdp_prep;
    rrdnew.rra_ptr   = rrdold.rra_ptr;

    version = atoi(rrdold.stat_head->version);
    switch (version) {
	case 3: break;
	case 1: rrdold.stat_head->version[3]='3';
		break;
	default: {
		rrd_set_error("Do not know how to handle RRD version %s",rrdold.stat_head->version);
		rrd_free(&rrdold);	
		fclose(infile);
		return(-1);
		}
    }

    if ((outfile=fopen(outfilename,"wb"))==NULL) {
        rrd_set_error("Can't create '%s'",outfilename);
        return(-1);
    }
    if (LockRRD(outfile) != 0) {
        rrd_set_error("could not lock new RRD");
        rrd_free(&rrdold);
        fclose(infile);
        fclose(outfile);
        return(-1);
    }
    fwrite(rrdnew.stat_head, sizeof(stat_head_t),1,outfile);
    fwrite(rrdnew.ds_def,sizeof(ds_def_t),rrdnew.stat_head->ds_cnt,outfile);
    fwrite(rrdnew.rra_def,sizeof(rra_def_t),rrdnew.stat_head->rra_cnt,outfile);
    fwrite(rrdnew.live_head,sizeof(live_head_t),1,outfile);
    fwrite(rrdnew.pdp_prep,sizeof(pdp_prep_t),rrdnew.stat_head->ds_cnt,outfile);
    fwrite(rrdnew.cdp_prep,sizeof(cdp_prep_t),rrdnew.stat_head->ds_cnt*rrdnew.stat_head->rra_cnt,outfile);
    fwrite(rrdnew.rra_ptr,sizeof(rra_ptr_t),rrdnew.stat_head->rra_cnt,outfile);

    /* Move the CDPs from the old to the new database.
    ** This can be made (much) faster but isn't worth the effort. Clarity
    ** is much more important.
    */

    /* Move data in unmodified RRAs
    */
    l=0;
    for (rra=0;rra<target_rra;rra++) {
        l+=rrdnew.stat_head->ds_cnt * rrdnew.rra_def[rra].row_cnt;
    }
    while (l>0) {
        fread(&buffer,sizeof(rrd_value_t),1,infile);
        fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
        l--;
    }
    /* Move data in this RRA, either removing or adding some rows
    */
    if (modify>0) {
        /* Adding extra rows; insert unknown values just after the
        ** current row number.
        */
        l = rrdnew.stat_head->ds_cnt * (rrdnew.rra_ptr[target_rra].cur_row+1);
        while (l>0) {
            fread(&buffer,sizeof(rrd_value_t),1,infile);
            fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            l--;
        }
        buffer=DNAN;
        l=rrdnew.stat_head->ds_cnt * modify;
        while (l>0) {
            fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            l--;
        }
    } else {
        /* Removing rows. Normally this would be just after the cursor
        ** however this may also mean that we wrap to the beginning of
        ** the array.
        */
        signed long int remove_end=0;

        remove_end=(rrdnew.rra_ptr[target_rra].cur_row-modify)%rrdnew.rra_def[target_rra].row_cnt;
        if (remove_end <= (signed long int)rrdnew.rra_ptr[target_rra].cur_row) {
            while (remove_end >= 0) {
                fseek(infile,sizeof(rrd_value_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
                rrdnew.rra_ptr[target_rra].cur_row--;
                rrdnew.rra_def[target_rra].row_cnt--;
                remove_end--;
                modify++;
            }
            remove_end=rrdnew.rra_def[target_rra].row_cnt-1;
        }
        for (l=0;l<=rrdnew.rra_ptr[target_rra].cur_row;l++) {
            unsigned int tmp;
            for (tmp=0;tmp<rrdnew.stat_head->ds_cnt;tmp++) {
                fread(&buffer,sizeof(rrd_value_t),1,infile);
                fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
            }
        }
        while (modify<0) {
            fseek(infile,sizeof(rrd_value_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
            rrdnew.rra_def[target_rra].row_cnt--;
            modify++;
        }
    }
    /* Move the rest of the CDPs
    */
    while (1) {
	fread(&buffer,sizeof(rrd_value_t),1,infile);
	if (feof(infile))
	    break;
        fwrite(&buffer,sizeof(rrd_value_t),1,outfile);
    }
    rrdnew.rra_def[target_rra].row_cnt += modify;
    fseek(outfile,sizeof(stat_head_t)+sizeof(ds_def_t)*rrdnew.stat_head->ds_cnt,SEEK_SET);
    fwrite(rrdnew.rra_def,sizeof(rra_def_t),rrdnew.stat_head->rra_cnt, outfile);
    fseek(outfile,sizeof(live_head_t),SEEK_CUR);
    fseek(outfile,sizeof(pdp_prep_t)*rrdnew.stat_head->ds_cnt,SEEK_CUR);
    fseek(outfile,sizeof(cdp_prep_t)*rrdnew.stat_head->ds_cnt*rrdnew.stat_head->rra_cnt,SEEK_CUR);
    fwrite(rrdnew.rra_ptr,sizeof(rra_ptr_t),rrdnew.stat_head->rra_cnt, outfile);
    
    fclose(outfile);
    rrd_free(&rrdold);
    fclose(infile);
    return(0);
}
Beispiel #19
0
/*
**
**  [func] - rewind.
**  [desc] - resets the stream file pointer to 0.
**  [entr] - FILE *stream; the pointer to the FILE stream.
**  [exit] - none.
**  [prec] - stream is a valid FILE pointer.
**  [post] - the stream file pointer is modified.
**
*/
void rewind(FILE *stream)
{
  fseek(stream, 0, SEEK_SET);
}
Beispiel #20
0
	bool KeyMagicKeyboard::ReadHeader(FILE * hFile, FileHeader * fh) {
		
		fread(fh, sizeof(FileHeader), 1, hFile);

		if (fh->magicCode[0] != 'K' || fh->magicCode[1] != 'M' || fh->magicCode[2] != 'K' || fh->magicCode[3] != 'L') {
			PERROR("Not KeyMagic keyboard file.\n");
			return false;
		}

		if (fh->majorVersion > MAJOR_VERSION) {
			PERROR("Can't load newer version of keyboard file.\n");
			return false;
		}

		if (fh->minorVersion > MINOR_VERSION) {
			PERROR("Can't load newer version of keyboard file.\n");
			return false;
		}

		if (fh->majorVersion == MAJOR_VERSION && fh->minorVersion == MINOR_VERSION) {
			return true;
		}

		// if older version 1.4
		if (fh->majorVersion == 1) {
			if (fh->minorVersion == 4) {
				FileHeader_1_4 fh14;
				fseek(hFile, 0, SEEK_SET);
				// read the header back
				fread(&fh14, sizeof(FileHeader_1_4), 1, hFile);
				// backward compability
				fh->stringCount = fh14.stringCount;
				fh->infoCount = fh14.infoCount;
				fh->ruleCount = fh14.ruleCount;
				
				fh->layoutOptions.trackCaps = fh14.layoutOptions.trackCaps;
				fh->layoutOptions.autoBksp = fh14.layoutOptions.autoBksp;
				fh->layoutOptions.eat = fh14.layoutOptions.eat;
				fh->layoutOptions.posBased = fh14.layoutOptions.posBased;
				fh->layoutOptions.rightAlt = true; // 1.4 dont have this option
			}
			else if (fh->minorVersion == 3) {
				FileHeader_1_3 fh13;
				fseek(hFile, 0, SEEK_SET);
				// read the header back
				fread(&fh13, sizeof(FileHeader_1_3), 1, hFile);
				// backward compability
				fh->stringCount = fh13.stringCount;
				fh->ruleCount = fh13.ruleCount;
				
				fh->layoutOptions.trackCaps = fh13.layoutOptions.trackCaps;
				fh->layoutOptions.autoBksp = fh13.layoutOptions.autoBksp;
				fh->layoutOptions.eat = fh13.layoutOptions.eat;
				fh->layoutOptions.posBased = fh13.layoutOptions.posBased;
				fh->layoutOptions.rightAlt = true; // 1.3 dont have this option
				
				fh->infoCount = 0; // 1.3 dont have infos, so set it to 0
			}
		}

		return true;
	}
Beispiel #21
0
void state_probability_queue::QueueEmptyFault()
{
#if (DBG > 0)
  fprintf(stderr, "\nQueueEmptyFault(sfq): ");
#endif
#ifndef SPLITFILE
  size_t read =
      fread(&stateArray[head_begin], sizeof(state_and_probability_pair),
	    min(global_front, head_size),
	    paging_file_top);
#else
  //make sure we do not read garbage after the states
  size_t read = paging_file_top->read(&stateArray[head_begin],
				      sizeof(state_and_probability_pair),
				      min(global_front, head_size));
#endif

  if (read > 0) {		//ok, some states are swapped in

    num_elts_head = read;
    global_front -= read;
#if (DBG > 0)
    fprintf(stderr, " read %d states from bottom", read);
#endif

  } else if (global_rear > 0) {	//paging_file_top is empty, but paging_file_bottom is not

#ifndef SPLITFILE
    fclose(paging_file_top);

    paging_file_top = paging_file_bottom;
    fseek(paging_file_top, 0, SEEK_SET);	//move to the beginning of the queue
    global_front = global_rear;

    if ((paging_file_bottom = tmpfile()) == NULL) {
      Error.Notrace("Internal: Error creating bottom paging file.");
    }
    global_rear = 0;		//bottom file is empty

    size_t read = fread(&stateArray[head_begin], sizeof(state), head_size,
			paging_file_top);

    num_elts_head = read;
    global_front -= read;
#else
    splitFile *fswap;

    //swap files
#if (DBG > 0)
    fprintf(stderr, " swapping top with bottom");
#endif
    fswap = paging_file_top;
    paging_file_top = paging_file_bottom;

    paging_file_bottom = fswap;

    paging_file_top->seek(0, SEEK_SET);	//move to the beginning of the queue
    paging_file_bottom->seek(0, SEEK_SET);	//reset bottom queue

    global_front = global_rear;
    global_rear = 0;		//bottom file is empty

    //now bottom entries are top entries and bottom file is empty. Reload a block!
    size_t read = paging_file_top->read(&stateArray[head_begin],
					sizeof(state_and_probability_pair),
					min(global_front, head_size));
#if (DBG > 0)
    fprintf(stderr, " read %d states from disk", read);
#endif

    num_elts_head = read;
    global_front -= read;
#endif

  } else if (num_elts_tail > 0) {	//paging_file_top AND paging_file_bottom are empty

#if (DBG > 0)
    fprintf(stderr, " using memory tail...");
#endif

    /* the disk queue is ended. this means that the only states we have
       to explore are the ones in the current tail window */
    unsigned long swap = tail_begin;
    tail_begin = head_begin;
    head_begin = swap;

    swap = tail_size;
    tail_size = head_size;
    head_size = swap;

    num_elts_head = num_elts_tail;
    num_elts_tail = 0;
    rear = 0;
  } else {			//no more states in both swap files, and the memory is empty: why do we call again?
    Error.Notrace("Internal: Attempt to read an empty state queue.");
  }

  front = 0;
}
Beispiel #22
0
void FsFile::jumpToCursor()
{
	fseek(fh, cursor, SEEK_SET);
}
Beispiel #23
0
static int gf_load_font(DviParams *unused, DviFont *font)
{
    int    i;
    int    n;
    int    loc;
    int    hic;
    FILE    *p;
    Int32    word;
    int    op;
    long    alpha, beta, z;
#ifndef NODEBUG
    char    s[256];
#endif

    p = font->in;

    /* check preamble */
    loc = fuget1(p); hic = fuget1(p);
    if(loc != GF_PRE || hic != GF_ID)
        goto badgf;
    loc = fuget1(p);
#ifndef NODEBUG
    for(i = 0; i < loc; i++)
        s[i] = fuget1(p);
    s[i] = 0;
    DEBUG((DBG_FONTS, "(gf) %s: %s\n", font->fontname, s));
#else
    fseek(p, (long)loc, SEEK_CUR);
#endif
    /* now read character locators in postamble */
    if(fseek(p, (long)-1, SEEK_END) == -1)
        return -1;
    
    n = 0;
    while((op = fuget1(p)) == GF_TRAILER) {
        if(fseek(p, (long)-2, SEEK_CUR) < 0)
            break;
        n++;
    }
    if(op != GF_ID || n < 4)
        goto badgf;
    /* get the pointer to the postamble */
    fseek(p, (long)-5, SEEK_CUR);
    op = fuget4(p);
    /* jump to it */
    fseek(p, (long)op, SEEK_SET);
    if(fuget1(p) != GF_POST)
        goto badgf;
    /* skip pointer to last EOC */
    fuget4(p);
    /* get the design size */
    font->design = fuget4(p);
    /* the checksum */
    word = fuget4(p);
    if(word && font->checksum && font->checksum != word) {
        mdvi_warning(_("%s: bad checksum (expected %u, found %u)\n"),
                 font->fontname, font->checksum, word);
    } else if(!font->checksum)
        font->checksum = word;
    /* skip pixels per point ratio */
    fuget4(p);
    fuget4(p);
    font->chars = xnalloc(DviFontChar, 256);
    for(loc = 0; loc < 256; loc++)
        font->chars[loc].offset = 0;
    /* skip glyph "bounding box" */
    fseek(p, (long)16, SEEK_CUR);
    loc = 256;
    hic = -1;
    TFMPREPARE(font->scale, z, alpha, beta);
    while((op = fuget1(p)) != GF_POST_POST) {
        DviFontChar *ch;
        int    cc;

        /* get the character code */        
        cc = fuget1(p);
        if(cc < loc)
            loc = cc;
        if(cc > hic)
            hic = cc;
        ch = &font->chars[cc];
        switch(op) {
        case GF_LOC:
            fsget4(p); /* skip dx */
            fsget4(p); /* skip dy */
            break;
        case GF_LOC0:
            fuget1(p); /* skip dx */
                       /* dy assumed 0 */
            break;
        default:
            mdvi_error(_("%s: junk in postamble\n"), font->fontname);
            goto error;
        }
        ch->code = cc;
        ch->tfmwidth = fuget4(p);
        ch->tfmwidth = TFMSCALE(ch->tfmwidth, z, alpha, beta);
        ch->offset = fuget4(p);
        if(ch->offset == -1)
            ch->offset = 0;
        /* initialize the rest of the glyph information */
        ch->x = 0;
        ch->y = 0;
        ch->width = 0;
        ch->height = 0;
        ch->glyph.data = NULL;
        ch->shrunk.data = NULL;
        ch->grey.data = NULL;
        ch->flags = 0;
        ch->loaded = 0;
    }    

    if(op != GF_POST_POST)
        goto badgf;
    
    if(loc > 0 || hic < 255) {
        /* shrink to optimal size */
        memmove(font->chars, font->chars + loc,
            (hic - loc + 1) * sizeof(DviFontChar));
        font->chars = xresize(font->chars,
            DviFontChar, hic - loc + 1);
    }
    font->loc = loc;
    font->hic = hic;

    return 0;

badgf:
    mdvi_error(_("%s: File corrupted, or not a GF file\n"), font->fontname);
error:
    if(font->chars) {
        mdvi_free(font->chars);
        font->chars = NULL;
    }
    font->loc = font->hic = 0;
    return -1;
}
Beispiel #24
0
int main(int argc, char *argv[])
{
    int i;

    printf(" __  __                         __   _  _   ____  _             \n");  
    printf("|  \\/  |_   _ _ __   ___ _ __  / /_ | || | |  _ \\| |_   _ ___ \n");
    printf("| |\\/| | | | | '_ \\ / _ \\ '_ \\| '_ \\| || |_| |_) | | | | / __|  \n");
    printf("| |  | | |_| | |_) |  __/ | | | (_) |__   _|  __/| | |_| \\__ \\  \n");
    printf("|_|  |_|\\__,_| .__/ \\___|_| |_|\\___/   |_| |_|   |_|\\__,_|___/  \n");
    printf("             |_|         https://mupen64plus.org/               \n");
    printf("%s Version %i.%i.%i\n\n", CONSOLE_UI_NAME, VERSION_PRINTF_SPLIT(CONSOLE_UI_VERSION));

    /* bootstrap some special parameters from the command line */
    if (ParseCommandLineInitial(argc, (const char **) argv) != 0)
        return 1;

    /* load the Mupen64Plus core library */
    if (AttachCoreLib(l_CoreLibPath) != M64ERR_SUCCESS)
        return 2;

    /* start the Mupen64Plus core library, load the configuration file */
    m64p_error rval = (*CoreStartup)(CORE_API_VERSION, l_ConfigDirPath, l_DataDirPath, "Core", DebugCallback, NULL, CALLBACK_FUNC);
    if (rval != M64ERR_SUCCESS)
    {
        DebugMessage(M64MSG_ERROR, "couldn't start Mupen64Plus core library.");
        DetachCoreLib();
        return 3;
    }

#ifdef VIDEXT_HEADER
    rval = CoreOverrideVidExt(&vidExtFunctions);
    if (rval != M64ERR_SUCCESS)
    {
        DebugMessage(M64MSG_ERROR, "couldn't start VidExt library.");
        DetachCoreLib();
        return 14;
    }
#endif

    /* Open configuration sections */
    rval = OpenConfigurationHandles();
    if (rval != M64ERR_SUCCESS)
    {
        (*CoreShutdown)();
        DetachCoreLib();
        return 4;
    }

    /* parse command-line options */
    rval = ParseCommandLineFinal(argc, (const char **) argv);
    if (rval != M64ERR_SUCCESS)
    {
        (*CoreShutdown)();
        DetachCoreLib();
        return 5;
    }

    /* Ensure that the core supports comparison feature if necessary */
    if (l_CoreCompareMode != 0 && !(g_CoreCapabilities & M64CAPS_CORE_COMPARE))
    {
        DebugMessage(M64MSG_ERROR, "can't use --core-compare feature with this Mupen64Plus core library.");
        DetachCoreLib();
        return 6;
    }
    compare_core_init(l_CoreCompareMode);
    
    /* Ensure that the core supports the debugger if necessary */
    if (l_LaunchDebugger && !(g_CoreCapabilities & M64CAPS_DEBUGGER))
    {
        DebugMessage(M64MSG_ERROR, "can't use --debug feature with this Mupen64Plus core library.");
        DetachCoreLib();
        return 6;
    }

    /* save the given command-line options in configuration file if requested */
    if (l_SaveOptions)
        SaveConfigurationOptions();

    /* load ROM image */
    FILE *fPtr = fopen(l_ROMFilepath, "rb");
    if (fPtr == NULL)
    {
        DebugMessage(M64MSG_ERROR, "couldn't open ROM file '%s' for reading.", l_ROMFilepath);
        (*CoreShutdown)();
        DetachCoreLib();
        return 7;
    }

    /* get the length of the ROM, allocate memory buffer, load it from disk */
    long romlength = 0;
    fseek(fPtr, 0L, SEEK_END);
    romlength = ftell(fPtr);
    fseek(fPtr, 0L, SEEK_SET);
    unsigned char *ROM_buffer = (unsigned char *) malloc(romlength);
    if (ROM_buffer == NULL)
    {
        DebugMessage(M64MSG_ERROR, "couldn't allocate %li-byte buffer for ROM image file '%s'.", romlength, l_ROMFilepath);
        fclose(fPtr);
        (*CoreShutdown)();
        DetachCoreLib();
        return 8;
    }
    else if (fread(ROM_buffer, 1, romlength, fPtr) != romlength)
    {
        DebugMessage(M64MSG_ERROR, "couldn't read %li bytes from ROM image file '%s'.", romlength, l_ROMFilepath);
        free(ROM_buffer);
        fclose(fPtr);
        (*CoreShutdown)();
        DetachCoreLib();
        return 9;
    }
    fclose(fPtr);

    /* Try to load the ROM image into the core */
    if ((*CoreDoCommand)(M64CMD_ROM_OPEN, (int) romlength, ROM_buffer) != M64ERR_SUCCESS)
    {
        DebugMessage(M64MSG_ERROR, "core failed to open ROM image file '%s'.", l_ROMFilepath);
        free(ROM_buffer);
        (*CoreShutdown)();
        DetachCoreLib();
        return 10;
    }
    free(ROM_buffer); /* the core copies the ROM image, so we can release this buffer immediately */

    /* handle the cheat codes */
    CheatStart(l_CheatMode, l_CheatNumList);
    if (l_CheatMode == CHEAT_SHOW_LIST)
    {
        (*CoreDoCommand)(M64CMD_ROM_CLOSE, 0, NULL);
        (*CoreShutdown)();
        DetachCoreLib();
        return 11;
    }

    /* search for and load plugins */
    rval = PluginSearchLoad(l_ConfigUI);
    if (rval != M64ERR_SUCCESS)
    {
        (*CoreDoCommand)(M64CMD_ROM_CLOSE, 0, NULL);
        (*CoreShutdown)();
        DetachCoreLib();
        return 12;
    }

    /* attach plugins to core */
    for (i = 0; i < 4; i++)
    {
        if ((*CoreAttachPlugin)(g_PluginMap[i].type, g_PluginMap[i].handle) != M64ERR_SUCCESS)
        {
            DebugMessage(M64MSG_ERROR, "core error while attaching %s plugin.", g_PluginMap[i].name);
            (*CoreDoCommand)(M64CMD_ROM_CLOSE, 0, NULL);
            (*CoreShutdown)();
            DetachCoreLib();
            return 13;
        }
    }

    /* set up Frame Callback if --testshots is enabled */
    if (l_TestShotList != NULL)
    {
        if ((*CoreDoCommand)(M64CMD_SET_FRAME_CALLBACK, 0, FrameCallback) != M64ERR_SUCCESS)
        {
            DebugMessage(M64MSG_WARNING, "couldn't set frame callback, --testshots will not work.");
        }
    }

    /* set gb cart loader */
    if ((*CoreDoCommand)(M64CMD_SET_MEDIA_LOADER, sizeof(l_media_loader), &l_media_loader) != M64ERR_SUCCESS)
    {
        DebugMessage(M64MSG_WARNING, "Couldn't set media loader, transferpak and GB carts will not work.");
    }

    /* load savestate at startup */
    if (l_SaveStatePath != NULL)
    {
        if ((*CoreDoCommand)(M64CMD_STATE_LOAD, 0, (void *) l_SaveStatePath) != M64ERR_SUCCESS)
        {
            DebugMessage(M64MSG_WARNING, "couldn't load state, rom will run normally.");
        }
    }

    /* Setup debugger */
    if (l_LaunchDebugger)
    {
        if (debugger_setup_callbacks())
        {
            DebugMessage(M64MSG_ERROR, "couldn't setup debugger callbacks.");
            (*CoreDoCommand)(M64CMD_ROM_CLOSE, 0, NULL);
            (*CoreShutdown)();
            DetachCoreLib();
            return 14;
        }
        /* Set Core config parameter to enable debugger */
        int bEnableDebugger = 1;
        (*ConfigSetParameter)(l_ConfigCore, "EnableDebugger", M64TYPE_BOOL, &bEnableDebugger);
        /* Fork the debugger input thread. */
#if SDL_VERSION_ATLEAST(2,0,0)
        SDL_CreateThread(debugger_loop, "DebugLoop", NULL);
#else
        SDL_CreateThread(debugger_loop, NULL);
#endif
    }

    /* run the game */
    (*CoreDoCommand)(M64CMD_EXECUTE, 0, NULL);

    /* detach plugins from core and unload them */
    for (i = 0; i < 4; i++)
        (*CoreDetachPlugin)(g_PluginMap[i].type);
    PluginUnload();

    /* close the ROM image */
    (*CoreDoCommand)(M64CMD_ROM_CLOSE, 0, NULL);

    /* save the configuration file again if --nosaveoptions was not specified, to keep any updated parameters from the core/plugins */
    if (l_SaveOptions)
        SaveConfigurationOptions();

    /* Shut down and release the Core library */
    (*CoreShutdown)();
    DetachCoreLib();

    /* free allocated memory */
    if (l_TestShotList != NULL)
        free(l_TestShotList);

    return 0;
}
Beispiel #25
0
/*!
 * Write one PET frame from IMG data struct into Analyze 7.5 database file.
 *  This function can be called repeatedly to write all frames one at a time
 *  to conserve memory. This function does not write SIF.
 *
 * @param dbname name of file where IMG contents will be written.
 *  If file does not exist, it is created.
 *  Make sure to delete existing file, unless you want to add data
 * @param frame_to_write PET frame number (1..frameNr) which will be written:
 *  If set to 0, frame data will be written to an existing or new PET file as
 *  a new frame, never overwriting existing data.
 *  If >0, then frame data is written as specified frame number, overwriting
 *  any data existing with the same frame number
 * @param img pointer to the IMG data struct
 * @param frame_index IMG frame index (0..dimt-1) which will be written
 * @param fmin minimum pixel value in all frames that will be written;
 *  used only when writing the first frame
 * @param fmax maximum pixel value in all frames that will be written;
 *  used only when writing the first frame
 * @return errstatus, which is STATUS_OK (0) when call was successful,
 * and >0 in case of an error.
 */
int imgWriteAnalyzeFrame(
  const char *dbname, int frame_to_write, IMG *img, int frame_index,
  float fmin, float fmax
) {
  IMG test_img;
  int ret=0, pxlNr, zi, xi, yi, little;
  FILE *fp;
  short int *sdata=NULL, *sptr;
  char datfile[FILENAME_MAX], hdrfile[FILENAME_MAX], siffile[FILENAME_MAX];
  ANALYZE_DSR dsr;
  float scale_factor=1.0;


  if(IMG_TEST) printf("\nimgWriteAnalyzeFrame(%s, %d, *img, %d, %g, %g)\n",
    dbname, frame_to_write, frame_index, fmin, fmax);

  /*
   *  Check the input 
   */
  if(dbname==NULL) return STATUS_FAULT;
  if(img==NULL) return STATUS_FAULT;
  if(img->status!=IMG_STATUS_OCCUPIED) return STATUS_FAULT;
  if(frame_to_write<0) return STATUS_FAULT;
  if(frame_index<0 || frame_index>=img->dimt) return STATUS_FAULT;
  if(img->_fileFormat!=IMG_ANA_L && img->_fileFormat!=IMG_ANA)
    return STATUS_FAULT;

  /*
   *  If database does not exist, then create it with new header,
   *  and if it does exist, then read and check header information.
   *  Create or edit header to contain correct frame nr.
   *  Determine the global scaling factor.   
   */
  imgInit(&test_img);
  if(anaDatabaseExists(dbname, hdrfile, datfile, siffile)==0) { // not existing

    /* Create database filenames */
    sprintf(hdrfile, "%s.hdr", dbname);
    sprintf(datfile, "%s.img", dbname);
    sprintf(siffile, "%s.sif", dbname);

    /* Set main header */
    imgSetAnalyzeHeader(img, dbname, &dsr, fmin, fmax);
    if(frame_to_write==0) frame_to_write=1;
    dsr.dime.dim[4]=frame_to_write;
    scale_factor=dsr.dime.funused1;
    if(fabs(scale_factor)>1.0E-20) scale_factor=1.0/scale_factor;

    /* Write Analyze header */
    ret=anaWriteHeader(hdrfile, &dsr);
    if(ret && IMG_TEST) printf("anaWriteHeader() := %d\n", ret);
    if(ret) return STATUS_CANTWRITEHEADERFILE;

    /* Remove datafile if necessary */
    if(access(datfile, 0) != -1) remove(datfile);

  } else { /* database does exist */
  
    /* Read header information for checking */
    ret=imgReadAnalyzeHeader(dbname, &test_img); if(ret!=0) return ret;
    /* Check that file format is the same */
    if(img->_fileFormat!=test_img._fileFormat || img->type!=test_img.type)
      return STATUS_WRONGFILETYPE;
    /* Check that matrix sizes are the same */
    if(img->dimz!=test_img.dimz || img->dimx!=test_img.dimx ||
       img->dimy!=test_img.dimy)
      return STATUS_VARMATSIZE;
    imgEmpty(&test_img);

    /* Read the header, set new frame number, and write it back */
    /* Get also the scale factor */
    if((ret=anaReadHeader(hdrfile, &dsr))!=0) return STATUS_NOMAINHEADER;
    scale_factor=1.0/dsr.dime.funused1;
    if(frame_to_write==0) frame_to_write=dsr.dime.dim[4]+1;
    if(dsr.dime.dim[4]<frame_to_write) {
      if(dsr.dime.dim[4]+1<frame_to_write) return STATUS_MISSINGMATRIX;
      dsr.dime.dim[4]=frame_to_write;
    }
    if((ret=anaWriteHeader(hdrfile, &dsr))!=0) return STATUS_NOWRITEPERM;
  }
  if(IMG_TEST>2) {
    printf("frame_to_write := %d\n", frame_to_write);
    printf("hdrfile := %s\n", hdrfile);
    printf("datfile := %s\n", datfile);
    printf("siffile := %s\n", siffile);
  }

  /* Allocate memory for matrix short int data (one plane) */
  pxlNr=img->dimx*img->dimy;
  sdata=(short int*)malloc(pxlNr*sizeof(short int));
  if(sdata==NULL) return STATUS_NOMEMORY;

  /* Open datafile, not removing possible old contents */
  if(frame_to_write==1) fp=fopen(datfile, "wb"); else fp=fopen(datfile, "r+b");
  if(fp==NULL) {free(sdata); return STATUS_CANTWRITEIMGFILE;}
  /* Move file pointer to the place of current frame */
  if(fseek(fp, (frame_to_write-1)*pxlNr*img->dimz*sizeof(short int),
           SEEK_SET)!=0) {
    free(sdata); fclose(fp); return STATUS_MISSINGMATRIX;}
  little=little_endian();
  /* Copy, scale and write data plane-by-plane */
  if(anaFlipping()==0) {
    for(zi=0; zi<img->dimz; zi++) {
      sptr=sdata;
     /*printf("plane := %d\n  scale_factor := %g\n", zi+1, scale_factor);*/
      for(yi=img->dimy-1; yi>=0; yi--) for(xi=img->dimx-1; xi>=0; xi--) {
        *sptr=temp_roundf(scale_factor*img->m[zi][yi][xi][frame_index]); sptr++;
      }
      /* Change byte order if necessary */
      sptr=sdata; if(little!=dsr.little) swabip(sptr, pxlNr*sizeof(short int));
      /* Write image data */
      sptr=sdata;
      if(fwrite(sptr, sizeof(short int), pxlNr, fp) != pxlNr) {
        free(sdata); fclose(fp); return STATUS_CANTWRITEIMGFILE;
      }
    }
  } else {
    for(zi=img->dimz-1; zi>=0; zi--) {
      sptr=sdata;
      for(yi=img->dimy-1; yi>=0; yi--) for(xi=img->dimx-1; xi>=0; xi--) {
        *sptr=temp_roundf(scale_factor*img->m[zi][yi][xi][frame_index]); sptr++;
      }
      /* Change byte order if necessary */
      sptr=sdata; if(little!=dsr.little) swabip(sptr, pxlNr*sizeof(short int));
      /* Write image data */
      sptr=sdata;
      if(fwrite(sptr, sizeof(short int), pxlNr, fp) != pxlNr) {
        free(sdata); fclose(fp); return STATUS_CANTWRITEIMGFILE;
      }
    }
  }
  free(sdata);
  fclose(fp);

  return STATUS_OK;
}
Beispiel #26
0
int puts(const char *s) {
    // Get libc syscall function pointer & offset in image
    libc_func(puts, int, const char *);

    if (plr_checkInsidePLR()) {
        // If already inside PLR code, just call original syscall & return
        return _puts(s);
    } else {
        plr_setInsidePLR();
        plrlog(LOG_SYSCALL, "[%d:puts] Write '%s' to stdout\n", getpid(), s);

        syscallArgs_t args = {
            .addr = _off_puts,
            .arg[0] = crc32(0, s, strlen(s)),
        };
        plr_checkSyscallArgs(&args);

        // Nested function actually performed by master process only
        int ret;
        putsShmData_t shmDat;
        int masterAct() {
            // Call original libc function
            ret = _puts(s);

            // Flush/sync data to disk to help other processes see it
            fflush(stdout);
            fsync(fileno(stdout));

            // Use ftell to get new file offset
            shmDat.err = errno;
            shmDat.ret = ret;
            shmDat.offs = ftell(stdout);
            shmDat.eof = feof(stdout);
            shmDat.ferr = ferror(stdout);

            // Store return value in shared memory for slave processes
            plr_copyToShm(&shmDat, sizeof(shmDat), 0);

            if (shmDat.ferr) {
                // Not sure how to handle passing ferror's to slaves yet, no way
                // to manually set error state
                plrlog(LOG_ERROR, "[%d:puts] ERROR: ferror (%d) occurred\n", getpid(), shmDat.ferr);
                exit(1);
            }

            return 0;
        }
        // All processes call plr_masterAction() to synchronize at this point
        plr_masterAction(masterAct);

        if (!plr_isMasterProcess()) {
            // Slaves copy return values from shared memory
            plr_copyFromShm(&shmDat, sizeof(shmDat), 0);

            // Slaves seek to new fd offset
            // Can't use SEEK_CUR and advance by ret because the slave processes
            // may have been forked from each other after the fd was opened, in which
            // case the fd & its offset are shared, and that would advance more than needed
            fseek(stdout, shmDat.offs, SEEK_SET);

            // Necessary to manually reset EOF flag because fseek clears it
            if (shmDat.eof) {
                // fgetc at EOF to set feof indicator
                int c;
                if ((c = fgetc(stdout)) != EOF) {
                    const char *fmt = "[%d:puts] ERROR: fgetc to cause EOF actually got data (%c %d), ftell = %d, feof = %d\n";
                    plrlog(LOG_ERROR, fmt, getpid(), c, c, ftell(stdout), feof(stdout));
                    exit(1);
                }
            }
            if (shmDat.ferr) {
                plrlog(LOG_ERROR, "[%d:puts] ERROR: ferror (%d) from master\n", getpid(), shmDat.ferr);
                exit(1);
            }
        }

        // TEMPORARY
        // Slave processes sometimes end up with the wrong file offset, even after SEEK_SET
        // Compare file state at exit to make sure everything is consistent
        // Piggybacking off checkSyscallArgs mechanism to do this
        syscallArgs_t exitState = {
            .arg[0] = ftell(stdout),
            .arg[1] = feof(stdout),
            .arg[2] = ferror(stdout),
        };
        plr_checkSyscallArgs(&exitState);

        // All procs return same value & errno
        ret = shmDat.ret;
        errno = shmDat.err;

        plr_clearInsidePLR();
        return ret;
    }
}
Beispiel #27
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
	if ( !file ) 
	{
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// Delete the existing data:
	Clear();
	location.Clear();

	// Get the file size, so we can pre-allocate the string. HUGE speed impact.
	long length = 0;
	fseek( file, 0, SEEK_END );
	length = ftell( file );
	fseek( file, 0, SEEK_SET );

	// Strange case, but good to handle up front.
	if ( length == 0 )
	{
		SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	// If we have a file, assume it is all one big XML file, and read it in.
	// The document parser may decide the document ends sooner than the entire file, however.
	TIXML_STRING data;
	data.reserve( length );

	// Subtle bug here. TinyXml did use fgets. But from the XML spec:
	// 2.11 End-of-Line Handling
	// <snip>
	// <quote>
	// ...the XML processor MUST behave as if it normalized all line breaks in external 
	// parsed entities (including the document entity) on input, before parsing, by translating 
	// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to 
	// a single #xA character.
	// </quote>
	//
	// It is not clear fgets does that, and certainly isn't clear it works cross platform. 
	// Generally, you expect fgets to translate from the convention of the OS to the c/unix
	// convention, and not work generally.

	/*
	while( fgets( buf, sizeof(buf), file ) )
	{
		data += buf;
	}
	*/

	char* buf = new char[ length+1 ];
	buf[0] = 0;

	if ( fread( buf, length, 1, file ) != 1 ) {
		delete [] buf;
		SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
		return false;
	}

	const char* lastPos = buf;
	const char* p = buf;

	buf[length] = 0;
	while( *p ) {
		assert( p < (buf+length) );
		if ( *p == 0xa ) {
			// Newline character. No special rules for this. Append all the characters
			// since the last string, and include the newline.
			data.append( lastPos, (p-lastPos+1) );	// append, include the newline
			++p;									// move past the newline
			lastPos = p;							// and point to the new buffer (may be 0)
			assert( p <= (buf+length) );
		}
		else if ( *p == 0xd ) {
			// Carriage return. Append what we have so far, then
			// handle moving forward in the buffer.
			if ( (p-lastPos) > 0 ) {
				data.append( lastPos, p-lastPos );	// do not add the CR
			}
			data += (char)0xa;						// a proper newline

			if ( *(p+1) == 0xa ) {
				// Carriage return - new line sequence
				p += 2;
				lastPos = p;
				assert( p <= (buf+length) );
			}
			else {
				// it was followed by something else...that is presumably characters again.
				++p;
				lastPos = p;
				assert( p <= (buf+length) );
			}
		}
		else {
			++p;
		}
	}
	// Handle any left over characters.
	if ( p-lastPos ) {
		data.append( lastPos, p-lastPos );
	}		
	delete [] buf;
	buf = 0;

	Parse( data.c_str(), 0, encoding );

	if (  Error() )
        return false;
    else
		return true;
}
Beispiel #28
0
/**
 * process_raw_volumes - writes the raw sections of the PFI data
 * @pfi		PFI data file pointer
 * @pfi_raws	list of PFI raw headers
 * @rawdev	device to use to write raw data
 *
 * Error handling:
 *	when early EOF in PFI data
 *	- returns -PFIFLASH_ERR_EOF, err_buf matches text to err
 *	when file I/O error
 *	- returns -PFIFLASH_ERR_FIO, err_buf matches text to err
 *	when CRC check fails
 *	- returns -PFIFLASH_ERR_CRC_CHECK, err_buf matches text to err
 *	when opening MTD device fails
 *	- reutrns -PFIFLASH_ERR_MTD_OPEN, err_buf matches text to err
 *	when closing MTD device fails
 *	- returns -PFIFLASH_ERR_MTD_CLOSE, err_buf matches text to err
 **/
static int
process_raw_volumes(FILE* pfi, list_t pfi_raws, const char* rawdev,
		    char* err_buf, size_t err_buf_size)
{
	int rc;
	char *pfi_data;
	void *i;
	uint32_t crc, crc32_table[256];
	size_t j, k;
	FILE* mtd = NULL;
	list_t ptr;

	if (is_empty(pfi_raws))
		return 0;

	if (rawdev == NULL)
		return 0;

	rc = 0;

	pfi_data = NULL;

	log_msg("[ rawupdate dev=%s", rawdev);

	crc = UBI_CRC32_INIT;
	init_crc32_table(crc32_table);

	/* most likely only one element in list, but just in case */
	foreach(i, ptr, pfi_raws) {
		pfi_raw_t r = (pfi_raw_t)i;

		/* read in pfi data */
		if (pfi_data != NULL)
			free(pfi_data);
		pfi_data = malloc(r->data_size * sizeof(char));
		for (j = 0; j < r->data_size; j++) {
			int c = fgetc(pfi);
			if (c == EOF) {
				rc = -PFIFLASH_ERR_EOF;
				EBUF(PFIFLASH_ERRSTR[-rc]);
				goto err;
			} else if (ferror(pfi)) {
				rc = -PFIFLASH_ERR_FIO;
				EBUF(PFIFLASH_ERRSTR[-rc]);
				goto err;
			}
			pfi_data[j] = (char)c;
		}
		crc = clc_crc32(crc32_table, crc, pfi_data, r->data_size);

		/* check crc */
		if (crc != r->crc) {
			rc = -PFIFLASH_ERR_CRC_CHECK;
			EBUF(PFIFLASH_ERRSTR[-rc], r->crc, crc);
			goto err;
		}

		/* open device */
		mtd = fopen(rawdev, "r+");
		if (mtd == NULL) {
			rc = -PFIFLASH_ERR_MTD_OPEN;
			EBUF(PFIFLASH_ERRSTR[-rc], rawdev);
			goto err;
		}

		for (j = 0; j < r->starts_size; j++) {
			rc = erase_mtd_region(mtd, r->starts[j], r->data_size);
			if (rc) {
				EBUF(PFIFLASH_ERRSTR[-rc]);
				goto err;
			}

			fseek(mtd, r->starts[j], SEEK_SET);
			for (k = 0; k < r->data_size; k++) {
				int c = fputc((int)pfi_data[k], mtd);
				if (c == EOF) {
					fclose(mtd);
					rc = -PFIFLASH_ERR_EOF;
					EBUF(PFIFLASH_ERRSTR[-rc]);
					goto err;
				}
				if ((char)c != pfi_data[k]) {
					fclose(mtd);
					rc = -1;
					goto err;
				}
			}
		}
		rc = fclose(mtd);
		mtd = NULL;
		if (rc != 0) {
			rc = -PFIFLASH_ERR_MTD_CLOSE;
			EBUF(PFIFLASH_ERRSTR[-rc], rawdev);
			goto err;
		}
	}
Beispiel #29
0
int fileSeek(FILE *fp, int offset, int origin)
{
	return fseek(fp, offset, origin);
}
Beispiel #30
0
bool TiXmlDocument::LoadFile( FILE* file, TiXmlEncoding encoding )
{
    if ( !file )
    {
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Delete the existing data:
    Clear();
    location.Clear();

    // Get the file size, so we can pre-allocate the string. HUGE speed impact.
    long length = 0;
    fseek( file, 0, SEEK_END );
    length = ftell( file );
    fseek( file, 0, SEEK_SET );

    // Strange case, but good to handle up front.
    if ( length <= 0 )
    {
        SetError( TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Subtle bug here. TinyXml did use fgets. But from the XML spec:
    // 2.11 End-of-Line Handling
    // <snip>
    // <quote>
    // ...the XML processor MUST behave as if it normalized all line breaks in external
    // parsed entities (including the document entity) on input, before parsing, by translating
    // both the two-character sequence #xD #xA and any #xD that is not followed by #xA to
    // a single #xA character.
    // </quote>
    //
    // It is not clear fgets does that, and certainly isn't clear it works cross platform.
    // Generally, you expect fgets to translate from the convention of the OS to the c/unix
    // convention, and not work generally.

    /*
    while( fgets( buf, sizeof(buf), file ) )
    {
    	data += buf;
    }
    */

    char* buf = new char[ length+1 ];
    buf[0] = 0;

    if ( fread( buf, length, 1, file ) != 1 )
    {
        delete [] buf;
        SetError( TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
        return false;
    }

    // Process the buffer in place to normalize new lines. (See comment above.)
    // Copies from the 'p' to 'q' pointer, where p can advance faster if
    // a newline-carriage return is hit.
    //
    // Wikipedia:
    // Systems based on ASCII or a compatible character set use either LF  (Line feed, '\n', 0x0A, 10 in decimal) or
    // CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)...
    //		* LF:    Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others
    //		* CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS
    //		* CR:    Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9

    const char* p = buf;	// the read head
    char* q = buf;			// the write head
    const char CR = 0x0d;
    const char LF = 0x0a;

    buf[length] = 0;
    while( *p )
    {
        assert( p < (buf+length) );
        assert( q <= (buf+length) );
        assert( q <= p );

        if ( *p == CR )
        {
            *q++ = LF;
            p++;
            if ( *p == LF )  		// check for CR+LF (and skip LF)
            {
                p++;
            }
        }
        else
        {
            *q++ = *p++;
        }
    }
    assert( q <= (buf+length) );
    *q = 0;

    Parse( buf, 0, encoding );

    delete [] buf;
    return !Error();
}