Ejemplo n.º 1
0
void savestates_save()
{ 
  gzFile f;
	char *filename, buf[1024];
  int len, i;
	
  /* fix the filename to %s.st%d format */
  filename = malloc(1024);
  sprintf(filename, "%s%s%s%s.st%d",(saveStateDevice==SAVESTATEDEVICE_USB)?"usb:":"sd:",
                           statespath, ROM_SETTINGS.goodname, saveregionstr(),savestates_slot);

	f = gzopen(filename, "wb");
  free(filename);
   	
  if(!f) {
  	return;
	}
  if(stop) {
	  pauseRemovalThread();
  }
  else {
    pauseAudio();
  }  
  gzwrite(f, &rdram_register, sizeof(RDRAM_register));
	gzwrite(f, &MI_register, sizeof(mips_register));
	gzwrite(f, &pi_register, sizeof(PI_register));
	gzwrite(f, &sp_register, sizeof(SP_register));
	gzwrite(f, &rsp_register, sizeof(RSP_register));
	gzwrite(f, &si_register, sizeof(SI_register));
	gzwrite(f, &vi_register, sizeof(VI_register));
	gzwrite(f, &ri_register, sizeof(RI_register));
	gzwrite(f, &ai_register, sizeof(AI_register));
	gzwrite(f, &dpc_register, sizeof(DPC_register));
	gzwrite(f, &dps_register, sizeof(DPS_register));
#ifdef USE_EXPANSION
	gzwrite(f, rdram, 0x800000);
#else
  gzwrite(f, rdram, 0x400000);
#endif
	gzwrite(f, SP_DMEM, 0x1000);
	gzwrite(f, SP_IMEM, 0x1000);
	gzwrite(f, PIF_RAM, 0x40);
	
	save_flashram_infos(buf);
	gzwrite(f, buf, 24);
#ifndef USE_TLB_CACHE
	gzwrite(f, tlb_LUT_r, 0x100000);		
	gzwrite(f, tlb_LUT_w, 0x100000);
#else
	//Traverse the TLB cache hash	and dump it
  TLBCache_dump_r(f);
	TLBCache_dump_w(f);
#endif

	gzwrite(f, &llbit, 4);
	gzwrite(f, reg, 32*8);
	for (i=0; i<32; i++) gzwrite(f, reg_cop0+i, 8); // *8 for compatibility with old versions purpose
	gzwrite(f, &lo, 8);
	gzwrite(f, &hi, 8);

	if ((Status & 0x04000000) == 0)
	{   // FR bit == 0 means 32-bit (MIPS I) FGR mode
		shuffle_fpr_data(0, 0x04000000);  // shuffle data into 64-bit register format for storage
		gzwrite(f, reg_cop1_fgr_64, 32*8);
		shuffle_fpr_data(0x04000000, 0);  // put it back in 32-bit mode
	}
	else
	{
		gzwrite(f, reg_cop1_fgr_64, 32*8);
	}

	gzwrite(f, &FCR0, 4);
	gzwrite(f, &FCR31, 4);
	gzwrite(f, tlb_e, 32*sizeof(tlb));
	gzwrite(f, &interp_addr, 4);    //Dynarec should be ok with just this

	gzwrite(f, &next_interupt, 4);
	gzwrite(f, &next_vi, 4);
	gzwrite(f, &vi_field, 4);
	
	len = save_eventqueue_infos(buf);
	gzwrite(f, buf, len);
	
	gzclose(f);
	if(stop) {
	  continueRemovalThread();
  }
  else {
    resumeAudio();
  }
}
Ejemplo n.º 2
0
/* Compresses a file `f_src' and saves it as `f_target'.
 */
static int compress_to_file(char *f_src, char *f_target, int mode_num)
{
  char buf[BUFLEN], mode[5];
  FILE *fin, *fout;
  int len;

  adjust_mode_num(&mode_num);
  egg_snprintf(mode, sizeof mode, "wb%d", mode_num);

  if (!is_file(f_src)) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': not a file.", f_src);
    return COMPF_ERROR;
  }
  fin = fopen(f_src, "rb");
  if (!fin) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': open failed: %s.",
           f_src, strerror(errno));
    return COMPF_ERROR;
  }

  fout = gzopen(f_target, mode);
  if (!fout) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': gzopen failed.",
           f_src);
    return COMPF_ERROR;
  }

#ifdef HAVE_MMAP
  if (compress_to_file_mmap(fout, fin) == COMPF_SUCCESS) {
    compressed_files++;
    return COMPF_SUCCESS;
  } else {
    /* To be on the safe side, close the file before attempting
     * to write again.
     */
    gzclose(fout);
    fout = gzopen(f_target, mode);
  }
#endif /* HAVE_MMAP */

  while (1) {
    len = fread(buf, 1, sizeof(buf), fin);
    if (ferror(fin)) {
      putlog(LOG_MISC, "*", "Failed to compress file `%s': fread failed: %s",
             f_src, strerror(errno));
      return COMPF_ERROR;
    }
    if (!len)
      break;
    if (gzwrite(fout, buf, (unsigned int) len) != len) {
      putlog(LOG_MISC, "*", "Failed to compress file `%s': gzwrite failed.",
             f_src);
      return COMPF_ERROR;
    }
  }
  fclose(fin);
  if (gzclose(fout) != Z_OK) {
    putlog(LOG_MISC, "*", "Failed to compress file `%s': gzclose failed.",
           f_src);
    return COMPF_ERROR;
  }
  compressed_files++;
  return COMPF_SUCCESS;
}
Ejemplo n.º 3
0
static ssize_t libtar_gzwrite(void* call_data, const void* buf, size_t count)
{
  struct gzStruct* gzf = (struct gzStruct*)call_data;
  return gzwrite(gzf->GZFile, (void*)buf, (unsigned int)count);
}
Ejemplo n.º 4
0
boolean
TxCache::save(const wchar_t *path, const wchar_t *filename, int config)
{
  if (!_cache.empty()) {
    /* dump cache to disk */
    char cbuf[MAX_PATH];

    boost::filesystem::wpath cachepath(path);
    boost::filesystem::create_directory(cachepath);

    /* Ugly hack to enable fopen/gzopen in Win9x */
#ifdef BOOST_WINDOWS_API
    wchar_t curpath[MAX_PATH];
    GETCWD(MAX_PATH, curpath);
    CHDIR(cachepath.wstring().c_str());
#else
    char curpath[MAX_PATH];
    wcstombs(cbuf, cachepath.wstring().c_str(), MAX_PATH);
    GETCWD(MAX_PATH, curpath);
    CHDIR(cbuf);
#endif

    wcstombs(cbuf, filename, MAX_PATH);

    gzFile gzfp = gzopen(cbuf, "wb1");
    DBG_INFO(80, L"gzfp:%x file:%ls\n", gzfp, filename);
    if (gzfp) {
      /* write header to determine config match */
      gzwrite(gzfp, &config, 4);

      std::map<uint64, TXCACHE*>::iterator itMap = _cache.begin();
      while (itMap != _cache.end()) {
        uint8 *dest    = (*itMap).second->info.data;
        uint32 destLen = (*itMap).second->size;
        uint16 format  = (*itMap).second->info.format;

        /* to keep things simple, we save the texture data in a zlib uncompressed state. */
        /* sigh... for those who cannot wait the extra few seconds. changed to keep
         * texture data in a zlib compressed state. if the GZ_TEXCACHE or GZ_HIRESTEXCACHE
         * option is toggled, the cache will need to be rebuilt.
         */
        /*if (format & GR_TEXFMT_GZ) {
          dest = _gzdest0;
          destLen = _gzdestLen;
          if (dest && destLen) {
            if (uncompress(dest, &destLen, (*itMap).second->info.data, (*itMap).second->size) != Z_OK) {
              dest = NULL;
              destLen = 0;
            }
            format &= ~GR_TEXFMT_GZ;
          }
        }*/

        if (dest && destLen) {
          /* texture checksum */
          gzwrite(gzfp, &((*itMap).first), 8);

          /* other texture info */
          gzwrite(gzfp, &((*itMap).second->info.width), 4);
          gzwrite(gzfp, &((*itMap).second->info.height), 4);
          gzwrite(gzfp, &format, 2);

          gzwrite(gzfp, &((*itMap).second->info.smallLodLog2), 4);
          gzwrite(gzfp, &((*itMap).second->info.largeLodLog2), 4);
          gzwrite(gzfp, &((*itMap).second->info.aspectRatioLog2), 4);

          gzwrite(gzfp, &((*itMap).second->info.tiles), 4);
          gzwrite(gzfp, &((*itMap).second->info.untiled_width), 4);
          gzwrite(gzfp, &((*itMap).second->info.untiled_height), 4);

          gzwrite(gzfp, &((*itMap).second->info.is_hires_tex), 1);

          gzwrite(gzfp, &destLen, 4);
          gzwrite(gzfp, dest, destLen);
        }

        itMap++;

        /* not ready yet */
        /*if (_callback)
          (*_callback)(L"Total textures saved to HDD: %d\n", std::distance(itMap, _cache.begin()));*/
      }
      gzclose(gzfp);
    }

    CHDIR(curpath);
  }

  return _cache.empty();
}
Ejemplo n.º 5
0
// [[Rcpp::export]]
void write_vcf_body_gz( Rcpp::DataFrame fix, Rcpp::DataFrame gt, std::string filename , int mask=0 ) {
  // http://stackoverflow.com/a/5649224
  
  // fix DataFrame
  Rcpp::StringVector chrom  = fix["CHROM"];
  Rcpp::StringVector pos    = fix["POS"];
  Rcpp::StringVector id     = fix["ID"];
  Rcpp::StringVector ref    = fix["REF"];
  Rcpp::StringVector alt    = fix["ALT"];
  Rcpp::StringVector qual   = fix["QUAL"];
  Rcpp::StringVector filter = fix["FILTER"];
  Rcpp::StringVector info   = fix["INFO"];
  
  // gt DataFrame
  Rcpp::StringMatrix gt_cm = DataFrame_to_StringMatrix(gt);
  Rcpp::StringVector column_names(gt.size());
  column_names = gt.attr("names");
  
  int i = 0;
  int j = 0;
  
  gzFile *fi = (gzFile *)gzopen(filename.c_str(),"ab");
//  gzFile *fi = (gzFile *)gzopen(filename.c_str(),"abw");
  for(i=0; i<chrom.size(); i++){
    Rcpp::checkUserInterrupt();
    if(mask == 1 && filter(i) != "PASS" ){
      // Don't print variant.
    } else {
      std::string tmpstring;
      tmpstring = chrom(i);
      tmpstring = tmpstring + "\t" + pos(i) + "\t";
      if(id(i) == NA_STRING){
        tmpstring = tmpstring + ".";
      } else {
        tmpstring = tmpstring + id(i);
      }
      tmpstring = tmpstring + "\t" + ref(i) + "\t" + alt(i) + "\t";
      if(qual(i) == NA_STRING){
        tmpstring = tmpstring + "." + "\t";
      } else {
        tmpstring = tmpstring + qual(i) + "\t";
      }
      if(filter(i) == NA_STRING){
        tmpstring = tmpstring + "." + "\t";
      } else {
        tmpstring = tmpstring + filter(i) + "\t";
      }
      tmpstring = tmpstring + info(i);

      // gt portion
      for(j=0; j<column_names.size(); j++){
        if(gt_cm(i, j) == NA_STRING){
          tmpstring = tmpstring + "\t" + "./.";
        } else {
          tmpstring = tmpstring + "\t" + gt_cm(i, j);
        }
      }


//      gzwrite(fi,"my decompressed data",strlen("my decompressed data"));
//      gzwrite(fi,"\n",strlen("\n"));
//      std::string tmpstring = "test string\n";
      gzwrite(fi, (char *)tmpstring.c_str(), tmpstring.size());
      
      gzwrite(fi,"\n",strlen("\n"));
    }
  }
  gzclose(fi);
  
  
  return;
}
Ejemplo n.º 6
0
static int
xgzwrite(void *cookie, const char *data, int size)
{
    return gzwrite(cookie, (void*)data, size);
}
Ejemplo n.º 7
0
// Donuts are a tasty treat and delicious with powdered sugar.
void MDFNMOV_AddJoy(void *donutdata, uint32 donutlen)
{
    gzFile fp;

    if(!current) return;	/* Not playback nor recording. */
    if(current < 0)	/* Playback */
    {
        int t;

        fp = slots[-1 - current];

        while((t = gzgetc(fp)) >= 0 && t)
        {
            if(t == MDFNNPCMD_LOADSTATE)
            {
                uint32 len;
                StateMem sm;
                len = gzgetc(fp);
                len |= gzgetc(fp) << 8;
                len |= gzgetc(fp) << 16;
                len |= gzgetc(fp) << 24;
                if(len >= 5 * 1024 * 1024) // A sanity limit of 5MiB
                {
                    StopPlayback();
                    return;
                }
                memset(&sm, 0, sizeof(StateMem));
                sm.len = len;
                sm.data = (uint8 *)malloc(len);
                if(gzread(fp, sm.data, len) != len)
                {
                    StopPlayback();
                    return;
                }
                if(!MDFNSS_LoadSM(&sm, 0, 0))
                {
                    StopPlayback();
                    return;
                }
            }
            else
                MDFN_DoSimpleCommand(t);
        }
        if(t < 0)
        {
            StopPlayback();
            return;
        }

        if(gzread(fp, donutdata, donutlen) != donutlen)
        {
            StopPlayback();
            return;
        }
    }
    else			/* Recording */
    {
        if(MDFN_StateEvilIsRunning())
        {
            smem_putc(&RewindBuffer, 0);
            smem_write(&RewindBuffer, donutdata, donutlen);
        }
        else
        {
            fp = slots[current - 1];
            gzputc(fp, 0);
            gzwrite(fp, donutdata, donutlen);
        }
    }
}
Ejemplo n.º 8
0
int64_t ZipFile::writeImpl(const char *buffer, int64_t length) {
  assert(m_gzFile);
  return gzwrite(m_gzFile, buffer, length);
}
Ejemplo n.º 9
0
int vfsGzFileWrite(const void *ptr, size_t size, size_t n, VIRTUAL_FILE* f)			{
	return gzwrite(_file_, ptr, size * n);
}
Ejemplo n.º 10
0
size64 CTarArcFile_GZip::write(void *buf, size64 size)
{
	return gzwrite(m_gzFile, buf, (size_t)size);	//TODO:size lost
}
Ejemplo n.º 11
0
/*
 * Receive a tar format file from the connection to the server, and write
 * the data from this file directly into a tar file. If compression is
 * enabled, the data will be compressed while written to the file.
 *
 * The file will be named base.tar[.gz] if it's for the main data directory
 * or <tablespaceoid>.tar[.gz] if it's for another tablespace.
 *
 * No attempt to inspect or validate the contents of the file is done.
 */
static void
ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
{
	char		filename[MAXPGPATH];
	char	   *copybuf = NULL;
	FILE	   *tarfile = NULL;

#ifdef HAVE_LIBZ
	gzFile		ztarfile = NULL;
#endif

	if (PQgetisnull(res, rownum, 0))
	{
		/*
		 * Base tablespaces
		 */
		if (strcmp(basedir, "-") == 0)
		{
#ifdef HAVE_LIBZ
			if (compresslevel != 0)
			{
				ztarfile = gzdopen(dup(fileno(stdout)), "wb");
				if (gzsetparams(ztarfile, compresslevel,
								Z_DEFAULT_STRATEGY) != Z_OK)
				{
					fprintf(stderr,
							_("%s: could not set compression level %d: %s\n"),
							progname, compresslevel, get_gz_error(ztarfile));
					disconnect_and_exit(1);
				}
			}
			else
#endif
				tarfile = stdout;
		}
		else
		{
#ifdef HAVE_LIBZ
			if (compresslevel != 0)
			{
				snprintf(filename, sizeof(filename), "%s/base.tar.gz", basedir);
				ztarfile = gzopen(filename, "wb");
				if (gzsetparams(ztarfile, compresslevel,
								Z_DEFAULT_STRATEGY) != Z_OK)
				{
					fprintf(stderr,
							_("%s: could not set compression level %d: %s\n"),
							progname, compresslevel, get_gz_error(ztarfile));
					disconnect_and_exit(1);
				}
			}
			else
#endif
			{
				snprintf(filename, sizeof(filename), "%s/base.tar", basedir);
				tarfile = fopen(filename, "wb");
			}
		}
	}
	else
	{
		/*
		 * Specific tablespace
		 */
#ifdef HAVE_LIBZ
		if (compresslevel != 0)
		{
			snprintf(filename, sizeof(filename), "%s/%s.tar.gz", basedir,
					 PQgetvalue(res, rownum, 0));
			ztarfile = gzopen(filename, "wb");
			if (gzsetparams(ztarfile, compresslevel,
							Z_DEFAULT_STRATEGY) != Z_OK)
			{
				fprintf(stderr,
						_("%s: could not set compression level %d: %s\n"),
						progname, compresslevel, get_gz_error(ztarfile));
				disconnect_and_exit(1);
			}
		}
		else
#endif
		{
			snprintf(filename, sizeof(filename), "%s/%s.tar", basedir,
					 PQgetvalue(res, rownum, 0));
			tarfile = fopen(filename, "wb");
		}
	}

#ifdef HAVE_LIBZ
	if (compresslevel != 0)
	{
		if (!ztarfile)
		{
			/* Compression is in use */
			fprintf(stderr,
					_("%s: could not create compressed file \"%s\": %s\n"),
					progname, filename, get_gz_error(ztarfile));
			disconnect_and_exit(1);
		}
	}
	else
#endif
	{
		/* Either no zlib support, or zlib support but compresslevel = 0 */
		if (!tarfile)
		{
			fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
					progname, filename, strerror(errno));
			disconnect_and_exit(1);
		}
	}

	/*
	 * Get the COPY data stream
	 */
	res = PQgetResult(conn);
	if (PQresultStatus(res) != PGRES_COPY_OUT)
	{
		fprintf(stderr, _("%s: could not get COPY data stream: %s"),
				progname, PQerrorMessage(conn));
		disconnect_and_exit(1);
	}

	while (1)
	{
		int			r;

		if (copybuf != NULL)
		{
			PQfreemem(copybuf);
			copybuf = NULL;
		}

		r = PQgetCopyData(conn, &copybuf, 0);
		if (r == -1)
		{
			/*
			 * End of chunk. Close file (but not stdout).
			 *
			 * Also, write two completely empty blocks at the end of the tar
			 * file, as required by some tar programs.
			 */
			char		zerobuf[1024];

			MemSet(zerobuf, 0, sizeof(zerobuf));
#ifdef HAVE_LIBZ
			if (ztarfile != NULL)
			{
				if (gzwrite(ztarfile, zerobuf, sizeof(zerobuf)) !=
					sizeof(zerobuf))
				{
					fprintf(stderr,
					_("%s: could not write to compressed file \"%s\": %s\n"),
							progname, filename, get_gz_error(ztarfile));
					disconnect_and_exit(1);
				}
			}
			else
#endif
			{
				if (fwrite(zerobuf, sizeof(zerobuf), 1, tarfile) != 1)
				{
					fprintf(stderr,
							_("%s: could not write to file \"%s\": %s\n"),
							progname, filename, strerror(errno));
					disconnect_and_exit(1);
				}
			}

#ifdef HAVE_LIBZ
			if (ztarfile != NULL)
			{
				if (gzclose(ztarfile) != 0)
				{
					fprintf(stderr,
					   _("%s: could not close compressed file \"%s\": %s\n"),
							progname, filename, get_gz_error(ztarfile));
					disconnect_and_exit(1);
				}
			}
			else
#endif
			{
				if (strcmp(basedir, "-") != 0)
				{
					if (fclose(tarfile) != 0)
					{
						fprintf(stderr,
								_("%s: could not close file \"%s\": %s\n"),
								progname, filename, strerror(errno));
						disconnect_and_exit(1);
					}
				}
			}

			break;
		}
		else if (r == -2)
		{
			fprintf(stderr, _("%s: could not read COPY data: %s"),
					progname, PQerrorMessage(conn));
			disconnect_and_exit(1);
		}

#ifdef HAVE_LIBZ
		if (ztarfile != NULL)
		{
			if (gzwrite(ztarfile, copybuf, r) != r)
			{
				fprintf(stderr,
					_("%s: could not write to compressed file \"%s\": %s\n"),
						progname, filename, get_gz_error(ztarfile));
				disconnect_and_exit(1);
			}
		}
		else
#endif
		{
			if (fwrite(copybuf, r, 1, tarfile) != 1)
			{
				fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
						progname, filename, strerror(errno));
				disconnect_and_exit(1);
			}
		}
		totaldone += r;
		if (showprogress)
			progress_report(rownum, filename);
	}							/* while (1) */

	if (copybuf != NULL)
		PQfreemem(copybuf);
}
Ejemplo n.º 12
0
 void insert (const Item* items, size_t length)
 {
     gzwrite(_gzfile,items,sizeof(Item)*length);
 }
Ejemplo n.º 13
0
 void insert (const std::vector<Item>& items, size_t length)
 {
     if (length == 0)  { length = items.size(); }
     //_file->fwrite (items.data(), sizeof(Item), length);
     gzwrite(_gzfile,items.data(),sizeof(Item)*length);
 }
Ejemplo n.º 14
0
 /**  \copydoc Bag::insert */
 void insert (const Item& item)  { gzwrite(_gzfile,&item,sizeof(Item)); }
Ejemplo n.º 15
0
static int
rs6000_build_image(char *kernel, char *boot, char *rawdev, char *outname)
{
	unsigned char *elf_img = NULL, *kern_img = NULL;
	int i, ch, tmp, kgzlen, err;
	int elf_fd, rs6000_fd, kern_fd, elf_img_len = 0, elf_pad;
	uint32_t swapped[128];
	off_t lenpos, kstart, kend;
	unsigned long length;
	long flength;
	gzFile gzf;
	struct stat kern_stat;
	Elf32_External_Phdr phdr;

	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
	kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
	kern_len = kern_stat.st_size + RS6000_MAGICSIZE + KERNLENSIZE;

	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
			SEEK_SET);
		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
			errx(3, "Can't read input '%s' phdr : %s", boot,
			    strerror(errno));

		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
		    !(ELFGET32(phdr.p_flags) & PF_X))
			continue;

		fstat(elf_fd, &elf_stat);
		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
		elf_pad = ELFGET32(phdr.p_memsz) - ELFGET32(phdr.p_filesz);
		if (verboseflag)
			printf("Padding %d\n", elf_pad);
		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);

		break;
	}
	if ((rs6000_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
		/* we couldn't open it, it must be new */
		rs6000_fd = creat(outname, 0644);
		if (rs6000_fd < 0)
			errx(2, "Can't open output '%s': %s", outname,
			    strerror(errno));
	}

	/* Set file pos. to 2nd sector where image will be written */
	lseek(rs6000_fd, 0x400, SEEK_SET);

	/* Copy boot image */
	elf_img = malloc(elf_img_len);
	if (!elf_img)
		errx(3, "Can't malloc: %s", strerror(errno));
	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));

	write(rs6000_fd, elf_img, elf_img_len);
	free(elf_img);

	/* now dump in the padding space for the BSS */
	elf_pad += 100; /* just a little extra for good luck */
	lseek(rs6000_fd, elf_pad, SEEK_CUR);

	/* Copy kernel */
	kern_img = malloc(kern_stat.st_size);

	if (kern_img == NULL)
		errx(3, "Can't malloc: %s", strerror(errno));

	/* we need to jump back after having read the headers */
	lseek(kern_fd, 0, SEEK_SET);
	if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
	    kern_stat.st_size)
		errx(3, "Can't read kernel '%s' : %s", kernel, strerror(errno));

	gzf = gzdopen(dup(rs6000_fd), "a");
	if (gzf == NULL)
		errx(3, "Can't init compression: %s", strerror(errno));
	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
		errx(3, "%s", gzerror(gzf, &err));

	/* write a magic number and size before the kernel */
	write(rs6000_fd, (void *)rs6000_magic, RS6000_MAGICSIZE);
	lenpos = lseek(rs6000_fd, 0, SEEK_CUR);
	if (verboseflag)
		printf("wrote magic at pos 0x%lx\n", (unsigned long)lenpos);
	tmp = sa_htobe32(0);
	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);

	/* write in the compressed kernel */
	kstart = lseek(rs6000_fd, 0, SEEK_CUR);
	if (verboseflag)
		printf("kernel start at pos 0x%lx\n", (unsigned long)kstart);
	kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
	gzclose(gzf);
	kend = lseek(rs6000_fd, 0, SEEK_CUR);
	if (verboseflag)
		printf("kernel end at pos 0x%lx\n", (unsigned long)kend);

	/* jump back to the length position now that we know the length */
	lseek(rs6000_fd, lenpos, SEEK_SET);
	kgzlen = kend - kstart;
	tmp = sa_htobe32(kgzlen);
	if (verboseflag)
		printf("kernel len = 0x%x tmp = 0x%x\n", kgzlen, tmp);
	write(rs6000_fd, (void *)&tmp, KERNLENSIZE);

#if 0
	lseek(rs6000_fd, sizeof(boot_record_t) + sizeof(config_record_t),
	    SEEK_SET);
	/* set entry and length */
	length = sa_htole32(0x400);
	write(rs6000_fd, &length, sizeof(length));
	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
	write(rs6000_fd, &length, sizeof(length));
#endif

	/* generate the header now that we know the kernel length */
	if (verboseflag)
		printf("building records\n");
	rs6000_build_records(elf_img_len + 8 + kgzlen);
	lseek(rs6000_fd, 0, SEEK_SET);
	/* ROM wants it byteswapped in 32bit chunks */
	if (verboseflag)
		printf("writing records\n");
	memcpy(swapped, &bootrec, sizeof(rs6000_boot_record_t));
	for (i=0; i < 128; i++)
		swapped[i] = htonl(swapped[i]);
	write(rs6000_fd, swapped, sizeof(rs6000_boot_record_t));
	memcpy(swapped, &confrec, sizeof(rs6000_config_record_t));
	for (i=0; i < 128; i++)
		swapped[i] = htonl(swapped[i]);
	write(rs6000_fd, swapped, sizeof(rs6000_config_record_t));

	free(kern_img);
	close(kern_fd);
	close(rs6000_fd);
	close(elf_fd);

	return 0;
}
/**
 * \brief    Save a pearl in backup file
 * \details  --
 * \param    gzFile backup_file
 * \param    pearl& p
 * \return   \e void
 */
void InheritedProteins::save_pearl( gzFile backup_file, pearl& p )
{
  /*------------------------------------------------------------------ global attributes */
  
  gzwrite( backup_file, &p.type,              sizeof(p.type) );
  gzwrite( backup_file, &p.identifier,        sizeof(p.identifier) );
  gzwrite( backup_file, &p.parent_identifier, sizeof(p.parent_identifier) );
  
  /*------------------------------------------------------------------ Enzyme type (E) attributes */
  
  gzwrite( backup_file, &p.s,    sizeof(p.s) );
  gzwrite( backup_file, &p.p,    sizeof(p.p) );
  gzwrite( backup_file, &p.km,   sizeof(p.km) );
  gzwrite( backup_file, &p.kcat, sizeof(p.kcat) );
  
  /*------------------------------------------------------------------ Transcription factor type (TF) attributes */
  
  gzwrite( backup_file, &p.BS_tag,         sizeof(p.BS_tag) );
  gzwrite( backup_file, &p.coE_tag,        sizeof(p.coE_tag) );
  gzwrite( backup_file, &p.free_activity,  sizeof(p.free_activity) );
  gzwrite( backup_file, &p.bound_activity, sizeof(p.bound_activity) );
  gzwrite( backup_file, &p.window,         sizeof(p.window));
  
  /*------------------------------------------------------------------ Binding site type (BS) attributes */
  
  gzwrite( backup_file, &p.TF_tag, sizeof(p.TF_tag));
  
  /*------------------------------------------------------------------ Promoter type (P) attributes */
  
  gzwrite( backup_file, &p.basal_expression_level, sizeof(p.basal_expression_level) );
  
  /*------------------------------------------------------------------ Functionality attribute */
  
  gzwrite( backup_file, &p.functional, sizeof(p.functional) );
}
Ejemplo n.º 17
0
static int
bebox_build_image(char *kernel, char *boot, char *rawdev, char *outname)
{
	unsigned char *elf_img = NULL, *kern_img = NULL, *header_img = NULL;
	int i, ch, tmp, kgzlen, err, hsize = BEBOX_HEADER_SIZE;
	int elf_fd, bebox_fd, kern_fd, elf_img_len = 0;
	off_t lenpos, kstart, kend, toff, endoff, flength;
	uint32_t swapped[128];
	int32_t *offset;
	gzFile gzf;
	struct stat kern_stat;
	struct bebox_image_block *p;
	struct timeval tp;
	Elf32_External_Phdr phdr;

	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
	if (inkernflag) {
		kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
		kern_len = kern_stat.st_size + BEBOX_MAGICSIZE + KERNLENSIZE;
	} else
		kern_len = BEBOX_MAGICSIZE + KERNLENSIZE;

	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
			SEEK_SET);
		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
			errx(3, "Can't read input '%s' phdr : %s", boot,
			    strerror(errno));

		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
		    !(ELFGET32(phdr.p_flags) & PF_X))
			continue;

		fstat(elf_fd, &elf_stat);
		elf_img_len = ELFGET32(phdr.p_filesz);
		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);

		break;
	}
	if ((bebox_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
		/* we couldn't open it, it must be new */
		bebox_fd = creat(outname, 0644);
		if (bebox_fd < 0)
			errx(2, "Can't open output '%s': %s", outname,
			    strerror(errno));
	}
	lseek(bebox_fd, hsize, SEEK_SET);

	if (inkernflag) {
		/*
		 * write the header with the wrong values to get the offset
		 * right
		 */
		bebox_write_header(bebox_fd, elf_img_len, kern_stat.st_size);

		/* Copy kernel */
		kern_img = malloc(kern_stat.st_size);

		if (kern_img == NULL)
			errx(3, "Can't malloc: %s", strerror(errno));

		/* we need to jump back after having read the headers */
		lseek(kern_fd, 0, SEEK_SET);
		if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
		    kern_stat.st_size)
			errx(3, "Can't read kernel '%s' : %s",
			    kernel, strerror(errno));

		gzf = gzdopen(dup(bebox_fd), "a");
		if (gzf == NULL)
			errx(3, "Can't init compression: %s", strerror(errno));
		if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) !=
		    Z_OK)
			errx(3, "%s", gzerror(gzf, &err));
	} else
		bebox_write_header(bebox_fd, elf_img_len, 0);

	/* write a magic number and size before the kernel */
	write(bebox_fd, (void *)bebox_magic, BEBOX_MAGICSIZE);
	lenpos = lseek(bebox_fd, 0, SEEK_CUR);
	tmp = sa_htobe32(0);
	write(bebox_fd, (void *)&tmp, KERNLENSIZE);

	if (inkernflag) {
		/* write in the compressed kernel */
		kstart = lseek(bebox_fd, 0, SEEK_CUR);
		kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
		gzclose(gzf);
		kend = lseek(bebox_fd, 0, SEEK_CUR);
		free(kern_img);
	} else {
		kstart = kend = lseek(bebox_fd, 0, SEEK_CUR);
		kgzlen = 0;
	}

	/* jump back to the length position now that we know the length */
	lseek(bebox_fd, lenpos, SEEK_SET);
	kgzlen = kend - kstart;
	tmp = sa_htobe32(kgzlen);
	write(bebox_fd, (void *)&tmp, KERNLENSIZE);

	/* now rewrite the header correctly */
	lseek(bebox_fd, hsize, SEEK_SET);
	tmp = kgzlen + BEBOX_MAGICSIZE + KERNLENSIZE;
	toff = bebox_write_header(bebox_fd, elf_img_len, tmp);

	/* Copy boot image */
	elf_img = malloc(elf_img_len);
	if (!elf_img)
		errx(3, "Can't malloc: %s", strerror(errno));
	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));
	lseek(bebox_fd, toff + hsize, SEEK_SET);
	write(bebox_fd, elf_img, elf_img_len);
	free(elf_img);

	if (inkernflag)
		close(kern_fd);
	close(elf_fd);

	/* Now go back and write in the block header */
	endoff = lseek(bebox_fd, 0, SEEK_END);
	lseek(bebox_fd, 0, SEEK_SET);
	header_img = malloc(BEBOX_HEADER_SIZE);
	if (!header_img)
		errx(3, "Can't malloc: %s", strerror(errno));
	memset(header_img, 0, BEBOX_HEADER_SIZE);

	/* copy the boot image into the buffer */
	for (p = bebox_image_block; p->offset != -1; p++)
		memcpy(header_img + p->offset, p->data, p->size);

	/* fill used block bitmap */
	memset(header_img + BEBOX_FILE_BLOCK_MAP_START, 0xff,
	    BEBOX_FILE_BLOCK_MAP_END - BEBOX_FILE_BLOCK_MAP_START);

	/* fix the file size in the header */
	tmp = endoff - BEBOX_HEADER_SIZE;
	*(int32_t *)(header_img + BEBOX_FILE_SIZE_OFFSET) =
	    (int32_t)sa_htobe32(tmp);
	*(int32_t *)(header_img + BEBOX_FILE_SIZE_ALIGN_OFFSET) =
	    (int32_t)sa_htobe32(roundup(tmp, BEBOX_FILE_BLOCK_SIZE));

	gettimeofday(&tp, 0);
	for (offset = bebox_mtime_offset; *offset != -1; offset++)
		*(int32_t *)(header_img + *offset) =
		    (int32_t)sa_htobe32(tp.tv_sec);

	write(bebox_fd, header_img, BEBOX_HEADER_SIZE);

	/* now pad the end */
	flength = roundup(endoff, BEBOX_BLOCK_SIZE);
	/* refill the header_img with zeros */
	memset(header_img, 0, BEBOX_BLOCK_SIZE * 2);
	lseek(bebox_fd, 0, SEEK_END);
	write(bebox_fd, header_img, flength - endoff);

	close(bebox_fd);
	free(header_img);

	return 0;
}
Ejemplo n.º 18
0
int
cache_write(char *path, int *page_nr, struct SiderHederFormat *final_sider, struct SiderHederFormat *sider_header,
            size_t sider_header_len, struct SiderFormat *sider, size_t sider_len)
{
	gzFile *cache;
	int fd, i, ret, k, len;

	//temp jayde 
	//final_sider->TotaltTreff = 20;
	//final_sider->showabal = 20;
	//sider_len = 20;
	//*page_nr = 20;

	if ((fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644)) == -1) {
		fprintf(stderr,"cache_write: can't open cache file\n");
		perror(path);
		return 0;
	}
	flock(fd, LOCK_EX);
	if ((cache = gzdopen(fd, "w")) == NULL) {
		fprintf(stderr,"cache_write: can't gzdopen\n");
		return 0;
	}

	// Debug: Disable compresion
	//if (gzsetparams(cache,Z_NO_COMPRESSION,Z_DEFAULT_STRATEGY) !=  Z_OK) {
	//	fprintf(stderr,"Cant disable commpresion\n");
	//	exit(-1);
	//}

	ret = 1;
	if (gzwrite(cache, page_nr, sizeof(*page_nr)) != sizeof(*page_nr)) {
		perror("gzwrite(page_nr)");
		goto err;
	}

	if (gzwrite(cache, final_sider, sizeof(*final_sider)) != sizeof(*final_sider)) {
		perror("gzwrite(final_sider)");
		goto err;
	}

	if (gzwrite(cache, sider_header, sizeof(*sider_header)*sider_header_len) != sizeof(*sider_header)*sider_header_len) {
		perror("gzwrite(final_sider)");
		goto err;
	}

	#ifdef ATTRIBUTES
		// wi ownly have one server for no
		for(i=0; i<1 ; i++) {
	
		        if (gzwrite(cache, sider_header[i].navigation_xml, sider_header[i].navigation_xml_len) != sider_header[i].navigation_xml_len) {
		                perror("gzwrite(navigation_xml)");
		                goto err;
		        }

		}
	#endif


	for (i = 0; i < sider_len; i++) {
		if (gzwrite(cache, &sider[i], sizeof(*sider)) != sizeof(*sider)) {
			perror("Unable to write cache");
			goto err;
		}

		#ifdef ATTRIBUTES
		if (gzwrite(cache, sider[i].attributes, sider[i].attributelen) != (sider[i].attributelen)) {
			perror("Unable to write cache attributelen");
			goto err;
		}
            

                for (k = 0; k < sider[i].n_urls; k++) {

			len = strlen(sider[i].urls[k].url);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read url len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].url, len) != (len)) {
				perror("Unable to read url len");
        			goto err;
                	}


			len = strlen(sider[i].urls[k].uri);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read uri len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].uri, len) != (len)) {
				perror("Unable to read uri len");
        			goto err;
                	}


			len = strlen(sider[i].urls[k].fulluri);
			if (gzwrite(cache, &len, sizeof(len)) != (sizeof(len))) {
				perror("Unable to read fulluri len");
        			goto err;
                	}
			if (gzwrite(cache, sider[i].urls[k].fulluri, len) != (len)) {
				perror("Unable to read fulluri len");
        			goto err;
                	}
							

		}



		#endif


	}
	

	goto out;
 err:
	ret = 0;
	unlink(path);
 out:
	gzclose(cache);
	close(fd);
	return ret;
}
Ejemplo n.º 19
0
/*
 * _prop_object_externalize_write_file --
 *	Write an externalized dictionary to the specified file.
 *	The file is written atomically from the caller's perspective,
 *	and the mode set to 0666 modified by the caller's umask.
 *
 *	The 'compress' argument enables gzip (via zlib) compression
 *	for the file to be written.
 */
bool
_prop_object_externalize_write_file(const char *fname, const char *xml,
    size_t len, bool do_compress)
{
	gzFile gzf = NULL;
	char tname[PATH_MAX];
	int fd;
	int save_errno;
	mode_t myumask;

	if (len > SSIZE_MAX) {
		errno = EFBIG;
		return (false);
	}

	/*
	 * Get the directory name where the file is to be written
	 * and create the temporary file.
	 */
	_prop_object_externalize_file_dirname(fname, tname);
#define PLISTTMP "/.plistXXXXXX"
	if (strlen(tname) + strlen(PLISTTMP) >= sizeof(tname)) {
		errno = ENAMETOOLONG;
		return (false);
	}
	strcat(tname, PLISTTMP);
#undef PLISTTMP

	if ((fd = mkstemp(tname)) == -1)
		return (false);

	if (do_compress) {
		if ((gzf = gzdopen(fd, "a")) == NULL)
			goto bad;

		if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY))
			goto bad;

		if (gzwrite(gzf, xml, len) != (ssize_t)len)
			goto bad;
	} else {
		if (write(fd, xml, len) != (ssize_t)len)
			goto bad;
	}

#ifdef HAVE_FDATASYNC
	if (fdatasync(fd) == -1)
#else
	if (fsync(fd) == -1)
#endif
		goto bad;

	myumask = umask(0);
	(void)umask(myumask);
	if (fchmod(fd, 0666 & ~myumask) == -1)
		goto bad;

	if (do_compress)
		(void)gzclose(gzf);
	else
		(void)close(fd);

	fd = -1;

	if (rename(tname, fname) == -1)
		goto bad;

	return (true);

 bad:
	save_errno = errno;
	if (do_compress && gzf != NULL)
		(void)gzclose(gzf);
	else if (fd != -1)
		(void)close(fd);
	(void) unlink(tname);
	errno = save_errno;
	return (false);
}
Ejemplo n.º 20
0
int main(int argc, char **argv)
{
  char header[22];
  unsigned char buf[65535];
  int ret = 0;

  const char *args = "n:h";
  int number = 10000;    /* (n) number per file */

  /* turn off error messages, I'll handle them */
  opterr = 0;
  while (1)
    {
      char c = getopt (argc, argv, args);

      if (c == -1)
        {
          break;
        }
      switch (c)
        {
          case 'n':
            number = atoi(optarg);
            break;

          case 'h':
            fprintf (stderr, "%s", help);
            ret = 1;
            goto cleanup;

          default:
            fprintf (stderr,
                     "WARNING: unrecognized command line option -%c\n",
                     optopt);
        }
    }

  int total_count = 0;
  int current_count = 0;

  unsigned long long start_file_timestamp = 0ULL;
  unsigned long long end_file_timestamp = 0ULL;

  const char *filename = argv[optind];
  const char *tmpfile = "lwes-journal-split-tmp.gz";
  char newfile[PATH_MAX];
  int newfile_idx = 0;
  char *buffer = strdup(filename);
  char *tofree = buffer;
  int file_part_count = 0;
  const char *file_parts[MAX_FILE_PARTS];
  const char *sep = ".";
  const char *empty = "";
  char *part;
  int i;
  for (i = 0; i < MAX_FILE_PARTS; i++)
    {
      file_parts[i] = empty;
    }
  while ((part = strsep (&buffer, sep)) && file_part_count < MAX_FILE_PARTS)
    {
      file_parts[file_part_count++] = part;
    }
  for (i = 0 ; i < file_part_count; i++)
    {
      printf ("part[%d] = %s\n",i,file_parts[i]);
    }
  newfile[newfile_idx] = '\0';
  if (strcmp (file_parts[file_part_count-1],"gz") == 0)
    {
      if (check_num_and_length (file_parts[file_part_count-2], 10)
          && check_num_and_length (file_parts[file_part_count-3], 10))
        {
          for (i = 0; i < (file_part_count-3); i++)
            {
              strcat (newfile, file_parts[i]);
              strcat (newfile, sep);
            }
        }
      else
        {
          fprintf (stderr,
                   "WARNING: journal file name format is non-standard\n");
          for (i = 0; i < (file_part_count-1); i++)
            {
              strcat (newfile, file_parts[i]);
              strcat (newfile, sep);
            }
        }
    }
  else
    {
      fprintf (stderr,
               "ERROR: journal must be a gzip file with .gz extension\n");
      free (tofree);
      ret = 1;
      goto cleanup;
    }
  free (tofree);

  newfile_idx = strlen (newfile);
  fprintf (stderr, "newfile prefix is %s of length %d\n",newfile, newfile_idx);

  gzFile tmp = gzopen (tmpfile, "wb");
  gzFile file = gzopen (filename, "rb");

  /* read a header from the file */
  while (gzread (file, header, 22) == 22)
    {
      unsigned short size = header_payload_length (header);
      unsigned long long cur_file_timestamp =
        (unsigned long long)(header_receipt_time (header));
      if (start_file_timestamp == 0ULL)
        {
          start_file_timestamp = cur_file_timestamp;
        }
      end_file_timestamp = cur_file_timestamp;
      if (gzwrite (tmp, header, 22) != 22)
        {
          fprintf (stderr, "ERROR: failure writing journal\n");
          ret=1;
          break;
        }

      /* read an event from the file */
      if (gzread (file, buf, size) != size)
        {
          fprintf (stderr, "ERROR: failure reading journal\n");
          ret=1;
          break;
        }
      if (gzwrite (tmp, buf, size) != size)
        {
          fprintf (stderr, "ERROR: failure writing journal\n");
          ret=1;
          break;
        }
      current_count++;
      total_count++;
      if (current_count == number) {
        gzclose (tmp);
        fprintf (stderr, "split from %llu to %llu %d\n",
                 start_file_timestamp, end_file_timestamp, current_count);
        char renamedfile[PATH_MAX];
        snprintf (renamedfile, sizeof (renamedfile), "%s%llu.%llu%s",
                  newfile,start_file_timestamp,end_file_timestamp, ".gz");
        if (rename (tmpfile, renamedfile) < 0)
          {
            fprintf (stderr, "ERROR : failed to rename %s to %s\n",
                     tmpfile, renamedfile);
            ret=1;
            break;
          }
        start_file_timestamp = 0ULL;
        current_count = 0;
        tmp = gzopen (tmpfile, "wb");
      }
    }
  gzclose (file);
  gzclose (tmp);
  char renamedfile[PATH_MAX];
  snprintf (renamedfile, sizeof (renamedfile), "%s%llu.%llu%s",
            newfile,start_file_timestamp,end_file_timestamp, ".gz");
  if (rename (tmpfile, renamedfile) < 0)
    {
      fprintf (stderr, "ERROR : failed to rename %s to %s\n",
               tmpfile, renamedfile);
      ret=1;
    }
  fprintf (stderr, "%s has %d events\n", filename, total_count);

cleanup:
  exit (ret);
}
void BridgeClassicToAMBATLM2<BUSWIDTH>::serialize(ostream &os)
{

	std::cout << "SERIALIZING " << sc_core::sc_object::name() << std::endl;

	uint32_t bytesRead;
    gzFile compressedMem;
    std::string filename = std::string(sc_core::sc_object::name()) + ".physmem";

    SERIALIZE_SCALAR(filename);
    //SERIALIZE_SCALAR(_size); //Hard coded 512 MB FIXME
//    _size = 512*1024*1024;

    // write memory file
    std::string thefile = Checkpoint::dir() + "/" + filename.c_str();
    int fd = creat(thefile.c_str(), 0664);
    if (fd < 0) {
        perror("creat");
        fatal("Can't open physical memory checkpoint file '%s'\n", filename);
    }

    compressedMem = gzdopen(fd, "wb");
    if (compressedMem == NULL)
        fatal("Insufficient memory to allocate compression state for %s\n",
                filename);

//    if (gzwrite(compressedMem, pmemAddr, size()) != (int)size()) {
//        fatal("Write failed on physical memory checkpoint file '%s'\n",
//              filename);
//    }

    const uint32_t chunkSize = 16384; //Could be higher, stay below 64kB for nerios mem store
    uint32_t curSize = 0;
    long *tempPage = (long*)malloc(chunkSize);
    if (tempPage == NULL)
        fatal("Unable to malloc memory to write file %s\n", filename);

    /* Only copy bytes that are non-zero, so we don't give the VM system hell */
	 //FIXME REPLACE USING DMI/!!!!
	tlm::tlm_generic_payload trans;
	trans.set_read();
	trans.set_data_length(chunkSize);
	trans.set_data_ptr((unsigned char*)(tempPage));
    while (curSize < size())
    {
		trans.set_address(curSize);
		debug_port->transport_dbg(static_cast<tlm::tlm_generic_payload &>(trans));
        curSize += bytesRead;
        gzwrite(compressedMem, tempPage, chunkSize);
    }

    free(tempPage);


    if (gzclose(compressedMem))
        fatal("Close failed on physical memory checkpoint file '%s'\n",
              filename);

    typename std::list<LockedAddr>::iterator i = lockedAddrList.begin();

    std::vector<Addr> lal_addr;
    std::vector<int> lal_cid;
    while (i != lockedAddrList.end()) {
        lal_addr.push_back(i->addr);
        lal_cid.push_back(i->contextId);
        i++;
    }
    arrayParamOut(os, "lal_addr", lal_addr);
    arrayParamOut(os, "lal_cid", lal_cid);
}
Ejemplo n.º 22
0
static int save(char *outfile,
		char *lang1, char *lang2,
		char *dicfile1, nat_uint32_t *tab1,
		char *dicfile2, nat_uint32_t *tab2,
		wchar_t *string1, nat_uint32_t ptr1, NATCell *cells1, nat_uint32_t size1,
		wchar_t *string2, nat_uint32_t ptr2, NATCell *cells2, nat_uint32_t size2) {
    FILE *out = NULL;
    nat_int_t s;

    Dictionary *dic;

    out = gzopen(outfile, "wb");
    if (!out) return 0;

    // Say this is a NATDict
    gzprintf(out,"!NATDict");

    s = strlen(lang1)+1;
    gzwrite(out, &s, sizeof(nat_int_t));
    gzwrite(out, lang1, s);

    s = strlen(lang2)+1;
    gzwrite(out, &s, sizeof(nat_int_t));
    gzwrite(out, lang2, s);

    // Save first lexicon
    g_message("** Saving source Lexicon **");
    gzwrite(out, &ptr1, sizeof(nat_uint32_t));
    gzwrite(out, string1, ptr1);
    gzwrite(out, &size1, sizeof(nat_uint32_t));
    g_message("\tSize: %u", size1);
    gzwrite(out, cells1, sizeof(NATCell) * size1);

    // Save second lexicon
    g_message("** Saving target Lexicon **");
    gzwrite(out, &ptr2, sizeof(nat_uint32_t));
    gzwrite(out, string2, ptr2);
    gzwrite(out, &size2, sizeof(nat_uint32_t));
    g_message("\tSize: %u", size2);
    gzwrite(out, cells2, sizeof(NATCell)* size2);

    // Load first dictionary
    g_message("** Source -> Target dictionary **");
    g_message("\tLoading...");
    dic = dictionary_open(dicfile1);

    dictionary_remap(tab1, tab2, dic);

    g_message("\tSaving...");
    gzwrite(out, &dic->size, sizeof(nat_uint32_t));
    gzwrite(out, dic->pairs, sizeof(DicPair)*MAXENTRY*(dic->size+1));
    gzwrite(out, dic->occurs, sizeof(nat_uint32_t)*(dic->size+1));
    dictionary_free(dic);

    // Load second dictionary
    g_message("** Target -> Source dictionary **");
    g_message("\tLoading...");
    dic = dictionary_open(dicfile2);

    dictionary_remap(tab2, tab1, dic);

    g_message("\tSaving...");
    gzwrite(out, &dic->size, sizeof(nat_uint32_t));
    gzwrite(out, dic->pairs, sizeof(DicPair)*MAXENTRY*(dic->size+1));
    gzwrite(out, dic->occurs, sizeof(nat_uint32_t)*(dic->size+1));
    dictionary_free(dic);

    // Close the file
    g_message("** DONE **");
    gzclose(out);

    return 1;
}
Ejemplo n.º 23
0
static int zlib_write(void *file, const void *buf, u32 len)
{
	return gzwrite(file, buf, len);
}
Ejemplo n.º 24
0
s32 SaveState(s8 *file) {
	DEBUG_STATES("starting %s", __FUNCTION__);
	gzFile f;
//GPUFREEZE *gpufP;
	GPUFreeze*    gpufP;
	SPUFreeze_t*  spufP;
	s32 Size;
	u8* pMem;
	s8 filePath[256];

	sprintf(filePath, "%s", file);

	DEBUG_STATES("opening file");
	f = gzopen(filePath, "wb");
	if (f == NULL) return -1;

	DEBUG_STATES("writing header");
	gzwrite(f, (void*)PsxHeader, 32);

	DEBUG_STATES("allocating useless memory");
	pMem = (u8 *) malloc(128*96*3);
	if (pMem == NULL) return -1;
//GPU_getScreenPic(pMem);
	gzwrite(f, pMem, 128*96*3);
	free(pMem);

	DEBUG_STATES("writing memory state");
	gzwrite(f, psxM, 0x00200000);
	gzwrite(f, psxR, 0x00080000);
	gzwrite(f, psxH, 0x00010000);

	DEBUG_STATES("writing registers");
	gzwrite(f, (void*)psxRegs, sizeof(psxRegisters));

	// gpu
	DEBUG_STATES("allocating GPU memory");
	gpufP = (GPUFreeze *) malloc(sizeof(GPUFreeze));
	if (!gpufP) {
		DEBUG_STATES("out of memory");
		return -1;
	}
	gpufP->Version = 1;
	GPU_freeze(1, gpufP);
	DEBUG_STATES("writing GPU memory");
	gzwrite(f, gpufP, sizeof(GPUFreeze));
	free(gpufP);

	// spu
	DEBUG_STATES("writing SPU");
	spufP = (SPUFreeze_t *) malloc(16);
	SPU_freeze(2, spufP);
	Size = spufP->ulFreezeSize; gzwrite(f, &Size, 4);
	DEBUG_STATES("SPU size %d, writing at %d", Size, gztell(f));
	free(spufP);
	spufP = (SPUFreeze_t *) malloc(Size);
	SPU_freeze(1, spufP);
	gzwrite(f, spufP, Size);
	free(spufP);

	sioFreeze(f, 1);
	cdrFreeze(f, 1);
	psxHwFreeze(f, 1);
	psxRcntFreeze(f, 1);
	mdecFreeze(f, 1);

	DEBUG_STATES("closing file");
	gzclose(f);

	DEBUG_STATES("ending %s", __FUNCTION__);
	return 0;
}
Ejemplo n.º 25
0
static void gzputv(vec3f &v) { gzwrite(f, &v, sizeof(vec3f)); }
Ejemplo n.º 26
0
/******************************************************************************
 * Only dump time dep. objects to file
 *****************************************************************************/
int ntlBlenderDumper::renderScene( void )
{
    char nrStr[5];								/* nr conversion */
    ntlRenderGlobals *glob = mpGlob;
    ntlScene *scene = mpGlob->getSimScene();
    bool debugOut = false;
    bool debugRender = false;
#if ELBEEM_PLUGIN==1
    debugOut = false;
#endif // ELBEEM_PLUGIN==1

    vector<string> gmName; 	 // gm names
    vector<string> gmMat;    // materials for gm
    int numGMs = 0;					 // no. of .obj models created

    if(debugOut) debMsgStd("ntlBlenderDumper::renderScene",DM_NOTIFY,"Dumping geometry data", 1);
    long startTime = getTime();
    snprintf(nrStr, 5, "%04d", glob->getAniCount() );

    // local scene vars
    vector<ntlTriangle> Triangles;
    vector<ntlVec3Gfx>  Vertices;
    vector<ntlVec3Gfx>  VertNormals;

    // check geo objects
    int idCnt = 0;          // give IDs to objects
    for (vector<ntlGeometryClass*>::iterator iter = scene->getGeoClasses()->begin();
            iter != scene->getGeoClasses()->end(); iter++) {
        if(!(*iter)->getVisible()) continue;
        int tid = (*iter)->getTypeId();

        if(tid & GEOCLASSTID_OBJECT) {
            // normal geom. objects -> ignore
        }
        if(tid & GEOCLASSTID_SHADER) {
            ntlGeometryShader *geoshad = (ntlGeometryShader*)(*iter); //dynamic_cast<ntlGeometryShader*>(*iter);
            string outname = geoshad->getOutFilename();
            if(outname.length()<1) outname = mpGlob->getOutFilename();
            geoshad->notifyShaderOfDump(DUMP_FULLGEOMETRY, glob->getAniCount(),nrStr,outname);

            for (vector<ntlGeometryObject*>::iterator siter = geoshad->getObjectsBegin();
                    siter != geoshad->getObjectsEnd();
                    siter++) {
                if(debugOut) debMsgStd("ntlBlenderDumper::BuildScene",DM_MSG,"added shader geometry "<<(*siter)->getName(), 8);

                (*siter)->notifyOfDump(DUMP_FULLGEOMETRY, glob->getAniCount(),nrStr,outname, this->mSimulationTime);
                bool doDump = false;
                bool isPreview = false;
                // only dump final&preview surface meshes
                if( (*siter)->getName().find( "final" ) != string::npos) {
                    doDump = true;
                } else if( (*siter)->getName().find( "preview" ) != string::npos) {
                    doDump = true;
                    isPreview = true;
                }
                if(!doDump) continue;

                // dont quit, some objects need notifyOfDump call
                if((glob_mpactive) && (glob_mpindex>0)) {
                    continue; //return 0;
                }

                // only dump geo shader objects
                Triangles.clear();
                Vertices.clear();
                VertNormals.clear();
                (*siter)->initialize( mpGlob );
                (*siter)->getTriangles(this->mSimulationTime, &Triangles, &Vertices, &VertNormals, idCnt);
                idCnt ++;

                // WARNING - this is dirty, but simobjs are the only geoshaders right now
                SimulationObject *sim = (SimulationObject *)geoshad;
                LbmSolverInterface *lbm = sim->getSolver();


                // always dump mesh, even empty ones...

                // dump to binary file
                std::ostringstream boutfilename("");
                //boutfilename << ecrpath.str() << outname <<"_"<< (*siter)->getName() <<"_" << nrStr << ".obj";
                boutfilename << outname <<"_"<< (*siter)->getName() <<"_" << nrStr;
                if(debugOut) debMsgStd("ntlBlenderDumper::renderScene",DM_MSG,"B-Dumping: "<< (*siter)->getName()
                                           <<", triangles:"<<Triangles.size()<<", vertices:"<<Vertices.size()<<
                                           " to "<<boutfilename.str() , 7);
                gzFile gzf;

                // output velocities if desired
                if((!isPreview) && (lbm->getDumpVelocities())) {
                    std::ostringstream bvelfilename;
                    bvelfilename << boutfilename.str();
                    bvelfilename << ".bvel.gz";
                    gzf = gzopen(bvelfilename.str().c_str(), "wb9");
                    if(gzf) {
                        int numVerts;
                        if(sizeof(numVerts)!=4) {
                            errMsg("ntlBlenderDumper::renderScene","Invalid int size");
                            return 1;
                        }
                        numVerts = Vertices.size();
                        gzwrite(gzf, &numVerts, sizeof(numVerts));
                        for(size_t i=0; i<Vertices.size(); i++) {
                            // returns smoothed velocity, scaled by frame time
                            ntlVec3Gfx v = lbm->getVelocityAt( Vertices[i][0], Vertices[i][1], Vertices[i][2] );
                            // translation not necessary, test rotation & scaling?
                            for(int j=0; j<3; j++) {
                                float vertp = v[j];
                                //if(i<20) errMsg("ntlBlenderDumper","DUMP_VEL final "<<i<<" = "<<v);
                                gzwrite(gzf, &vertp, sizeof(vertp));
                            }
                        }
                        gzclose( gzf );
                    }
                }

                // compress all bobj's
                boutfilename << ".bobj.gz";
                gzf = gzopen(boutfilename.str().c_str(), "wb1"); // wb9 is slow for large meshes!
                if (!gzf) {
                    errMsg("ntlBlenderDumper::renderScene","Unable to open output '"<<boutfilename<<"' ");
                    return 1;
                }

                // dont transform velocity output, this is handled in blender
                // current transform matrix
                ntlMatrix4x4<gfxReal> *trafo;
                trafo = lbm->getDomainTrafo();
                if(trafo) {
                    // transform into source space
                    for(size_t i=0; i<Vertices.size(); i++) {
                        Vertices[i] = (*trafo) * Vertices[i];
                    }
                }
                // rotate vertnormals
                ntlMatrix4x4<gfxReal> rottrafo;
                rottrafo.initId();
                if(lbm->getDomainTrafo()) {
                    // dont modifiy original!
                    rottrafo = *lbm->getDomainTrafo();
                    ntlVec3Gfx rTrans,rScale,rRot,rShear;
                    rottrafo.decompose(rTrans,rScale,rRot,rShear);
                    rottrafo.initRotationXYZ(rRot[0],rRot[1],rRot[2]);
                    // only rotate here...
                    for(size_t i=0; i<Vertices.size(); i++) {
                        VertNormals[i] = rottrafo * VertNormals[i];
                        normalize(VertNormals[i]); // remove scaling etc.
                    }
                }


                // write to file
                int numVerts;
                if(sizeof(numVerts)!=4) {
                    errMsg("ntlBlenderDumper::renderScene","Invalid int size");
                    return 1;
                }
                numVerts = Vertices.size();
                gzwrite(gzf, &numVerts, sizeof(numVerts));
                for(size_t i=0; i<Vertices.size(); i++) {
                    for(int j=0; j<3; j++) {
                        float vertp = Vertices[i][j];
                        gzwrite(gzf, &vertp, sizeof(vertp));
                    }
                }

                // should be the same as Vertices.size
                if(VertNormals.size() != (size_t)numVerts) {
                    errMsg("ntlBlenderDumper::renderScene","Normals have to have same size as vertices!");
                    VertNormals.resize( Vertices.size() );
                }
                gzwrite(gzf, &numVerts, sizeof(numVerts));
                for(size_t i=0; i<VertNormals.size(); i++) {
                    for(int j=0; j<3; j++) {
                        float normp = VertNormals[i][j];
                        gzwrite(gzf, &normp, sizeof(normp));
                    }
                }

                int numTris = Triangles.size();
                gzwrite(gzf, &numTris, sizeof(numTris));
                for(size_t i=0; i<Triangles.size(); i++) {
                    for(int j=0; j<3; j++) {
                        int triIndex = Triangles[i].getPoints()[j];
                        gzwrite(gzf, &triIndex, sizeof(triIndex));
                    }
                }
                gzclose( gzf );
                debMsgStd("ntlBlenderDumper::renderScene",DM_NOTIFY," Wrote: '"<<boutfilename.str()<<"' ", 2);
                numGMs++;
            }
        }

    }

    // output ecr config file
    if(numGMs>0) {
        if(debugOut) debMsgStd("ntlBlenderDumper::renderScene",DM_MSG,"Objects dumped: "<<numGMs, 10);
    } else {
        if((glob_mpactive) && (glob_mpindex>0)) {
            // ok, nothing to do anyway...
        } else {
            errFatal("ntlBlenderDumper::renderScene","No objects to dump! Aborting...",SIMWORLD_INITERROR);
            return 1;
        }
    }

    // debug timing
    long stopTime = getTime();
    debMsgStd("ntlBlenderDumper::renderScene",DM_MSG,"Scene #"<<nrStr<<" dump time: "<< getTimeString(stopTime-startTime) <<" ", 10);

    // still render for preview...
    if(debugRender) {
        debMsgStd("ntlBlenderDumper::renderScene",DM_NOTIFY,"Performing preliminary render", 1);
        ntlWorld::renderScene();
    }
    else {
        // next frame
        glob->setAniCount( glob->getAniCount() +1 );
    }

    return 0;
}
Ejemplo n.º 27
0
bool
ZfileOutput::open (const std::string &name, const ImageSpec &userspec,
                   OpenMode mode)
{
    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    close ();  // Close any already-opened file
    m_gz = 0;
    m_file = NULL;
    m_spec = userspec;  // Stash the spec

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
               m_spec.width, m_spec.height);
        return false;
    }
    if (m_spec.depth < 1)
        m_spec.depth = 1;
    if (m_spec.depth > 1) {
        error ("%s does not support volume images (depth > 1)", format_name());
        return false;
    }

    if (m_spec.nchannels != 1) {
        error ("Zfile only supports 1 channel, not %d", m_spec.nchannels);
        return false;
    }

    // Force float
    if (m_spec.format != TypeDesc::FLOAT)
        m_spec.format = TypeDesc::FLOAT;

    ZfileHeader header;
    header.magic = zfile_magic;
    header.width = (int)m_spec.width;
    header.height = (int)m_spec.height;

    ParamValue *p;
    static float ident[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
    if ((p = m_spec.find_attribute ("worldtocamera", TypeDesc::TypeMatrix)))
        memcpy (header.worldtocamera, p->data(), 16*sizeof(float));
    else
        memcpy (header.worldtocamera, ident, 16*sizeof(float));
    if ((p = m_spec.find_attribute ("worldtoscreen", TypeDesc::TypeMatrix)))
        memcpy (header.worldtoscreen, p->data(), 16*sizeof(float));
    else
        memcpy (header.worldtoscreen, ident, 16*sizeof(float));

    if (m_spec.get_string_attribute ("compression", "none") != std::string("none")) {
        FILE *fd = Filesystem::fopen (name, "wb");
        if (fd) {
            m_gz = gzdopen (fileno (fd), "wb");
            if (!m_gz)
                fclose (fd);
        }
    }
    else
        m_file = Filesystem::fopen (name, "wb");
    if (! m_file  &&  ! m_gz) {
        error ("Could not open file \"%s\"", name.c_str());
        return false;
    }

    if (m_gz)
        gzwrite (m_gz, &header, sizeof(header));
    else {
    	size_t b = fwrite (&header, sizeof(header), 1, m_file);
    	if (b != 1) {
            error ("Failed write zfile::open (err: %d)", b);
            return false;
    	}
    }

    // If user asked for tiles -- which this format doesn't support, emulate
    // it by buffering the whole image.this form
    if (m_spec.tile_width && m_spec.tile_height)
        m_tilebuffer.resize (m_spec.image_bytes());

    return true;
}
Ejemplo n.º 28
0
static int
prep_build_image(char *kernel, char *boot, char *rawdev, char *outname)
{
	unsigned char *elf_img = NULL, *kern_img = NULL;
	int i, ch, tmp, kgzlen, err;
	int elf_fd, prep_fd, kern_fd, elf_img_len = 0;
	off_t lenpos, kstart, kend;
	unsigned long length;
	long flength;
	gzFile gzf;
	struct stat kern_stat;
	Elf32_External_Phdr phdr;

	elf_fd = open_file("bootloader", boot, &hdr, &elf_stat);
	if (inkernflag) {
		kern_fd = open_file("kernel", kernel, &khdr, &kern_stat);
		kern_len = kern_stat.st_size + PREP_MAGICSIZE + KERNLENSIZE;
	} else
		kern_len = PREP_MAGICSIZE + KERNLENSIZE;

	for (i = 0; i < ELFGET16(hdr.e_phnum); i++) {
		lseek(elf_fd, ELFGET32(hdr.e_phoff) + sizeof(phdr) * i,
			SEEK_SET);
		if (read(elf_fd, &phdr, sizeof(phdr)) != sizeof(phdr))
			errx(3, "Can't read input '%s' phdr : %s", boot,
			    strerror(errno));

		if ((ELFGET32(phdr.p_type) != PT_LOAD) ||
		    !(ELFGET32(phdr.p_flags) & PF_X))
			continue;

		fstat(elf_fd, &elf_stat);
		elf_img_len = elf_stat.st_size - ELFGET32(phdr.p_offset);
		lseek(elf_fd, ELFGET32(phdr.p_offset), SEEK_SET);

		break;
	}
	if ((prep_fd = open(outname, O_RDWR|O_TRUNC, 0)) < 0) {
		/* we couldn't open it, it must be new */
		prep_fd = creat(outname, 0644);
		if (prep_fd < 0)
			errx(2, "Can't open output '%s': %s", outname,
			    strerror(errno));
	}

	prep_check_mbr(prep_fd, rawdev);

	/* Set file pos. to 2nd sector where image will be written */
	lseek(prep_fd, 0x400, SEEK_SET);

	/* Copy boot image */
	elf_img = malloc(elf_img_len);
	if (!elf_img)
		errx(3, "Can't malloc: %s", strerror(errno));
	if (read(elf_fd, elf_img, elf_img_len) != elf_img_len)
		errx(3, "Can't read file '%s' : %s", boot, strerror(errno));

	write(prep_fd, elf_img, elf_img_len);
	free(elf_img);

	if (inkernflag) {
		/* Copy kernel */
		kern_img = malloc(kern_stat.st_size);

		if (kern_img == NULL)
			errx(3, "Can't malloc: %s", strerror(errno));

		/* we need to jump back after having read the headers */
		lseek(kern_fd, 0, SEEK_SET);
		if (read(kern_fd, (void *)kern_img, kern_stat.st_size) !=
		    kern_stat.st_size)
			errx(3, "Can't read kernel '%s' : %s",
			    kernel, strerror(errno));
	}

	gzf = gzdopen(dup(prep_fd), "a");
	if (gzf == NULL)
		errx(3, "Can't init compression: %s", strerror(errno));
	if (gzsetparams(gzf, Z_BEST_COMPRESSION, Z_DEFAULT_STRATEGY) != Z_OK)
		errx(3, "%s", gzerror(gzf, &err));

	/* write a magic number and size before the kernel */
	write(prep_fd, (void *)prep_magic, PREP_MAGICSIZE);
	lenpos = lseek(prep_fd, 0, SEEK_CUR);
	tmp = sa_htobe32(0);
	write(prep_fd, (void *)&tmp, KERNLENSIZE);

	/* write in the compressed kernel */
	kstart = lseek(prep_fd, 0, SEEK_CUR);
	if (inkernflag) {
		kgzlen = gzwrite(gzf, kern_img, kern_stat.st_size);
		gzclose(gzf);
	}
	kend = lseek(prep_fd, 0, SEEK_CUR);

	/* jump back to the length position now that we know the length */
	lseek(prep_fd, lenpos, SEEK_SET);
	kgzlen = kend - kstart;
	tmp = sa_htobe32(kgzlen);
	write(prep_fd, (void *)&tmp, KERNLENSIZE);

	length = sa_htole32(0x400 + elf_img_len + 8 + kgzlen);
	lseek(prep_fd, sizeof(mbr) + 4, SEEK_SET);
	write(prep_fd, &length, sizeof(length));

	flength = 0x400 + elf_img_len + 8 + kgzlen;
	if (lfloppyflag)
		flength -= (5760 * 512);
	else
		flength -= (2880 * 512);
	if (flength > 0 && !saloneflag)
		fprintf(stderr, "%s: Image %s is %ld bytes larger than single"
		    " floppy. Can only be used for netboot.\n", getprogname(),
		    outname, flength);

	if (inkernflag) {
		free(kern_img);
		close(kern_fd);
	}
	close(prep_fd);
	close(elf_fd);

	return 0;
}
Ejemplo n.º 29
0
/**
 * Writes the grid to a BT (Binary Terrain) file.
 * The current BT format version (1.3) is written.
 *
 * \param szFileName		The file name to write to.
 * \param progress_callback If supplied, this function will be called back
 *				with a value of 0 to 100 as the operation progresses.
 * \param bGZip			If true, the data will be compressed with gzip.
 *				If true, you should Use a filename ending with ".gz".
 */
bool vtElevationGrid::SaveToBT(const char *szFileName,
							   bool progress_callback(int), bool bGZip)
{
	int w = m_iColumns;
	int h = m_iRows;
	short zone = (short) m_proj.GetUTMZone();
	short datum = (short) m_proj.GetDatum();
	short isfloat = (short) IsFloatMode();
	short external = 1;		// always true: we always write an external .prj file

	LinearUnits units = m_proj.GetUnits();
	int hunits = (int) units;

	// Latest header, version 1.2
	short datasize = m_bFloatMode ? 4 : 2;
	DataType datatype = m_bFloatMode ? DT_FLOAT : DT_SHORT;

	if (bGZip == false)
	{
		// Use conventional IO
		FILE *fp = vtFileOpen(szFileName, "wb");
		if (!fp)
			return false;

		fwrite("binterr1.3", 10, 1, fp);
		FWrite(&w, DT_INT, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&h, DT_INT, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&datasize, DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&isfloat, DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&hunits,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);	// Horizontal Units (0, 1, 2, 3)
		FWrite(&zone,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);		// UTM zone
		FWrite(&datum,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);	// Datum

		// coordinate extents
		FWrite(&m_EarthExtents.left,	DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&m_EarthExtents.right,	DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&m_EarthExtents.bottom,	DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		FWrite(&m_EarthExtents.top,		DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);

		FWrite(&external, DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);		// External projection specification
		FWrite(&m_fVMeters, DT_FLOAT, 1, fp, BO_LITTLE_ENDIAN);	// Vertical scale factor (meters/units)

		// now write the data: always starts at offset 256
		fseek(fp, 256, SEEK_SET);

#if 0
		// slow way, one heixel at a time
		for (int i = 0; i < w; i++)
		{
			if (progress_callback != NULL) progress_callback(i * 100 / w);
			for (j = 0; j < h; j++)
			{
				if (m_bFloatMode) {
					fvalue = GetFValue(i, j);
					FWrite(&fvalue, datatype, 1, fp, BO_LITTLE_ENDIAN);
				} else {
					svalue = GetValue(i, j);
					FWrite(&svalue, datatype, 1, fp, BO_LITTLE_ENDIAN);
				}
			}
		}
#else
		// fast way, with the assumption that the data is stored column-first in memory
		if (m_bFloatMode)
		{
			for (int i = 0; i < w; i++)
			{
				if (progress_callback != NULL)
				{
					if (progress_callback(i * 100 / w))
					{ fclose(fp); return false; }
				}
				FWrite(m_pFData + (i * m_iRows), DT_FLOAT, m_iRows, fp, BO_LITTLE_ENDIAN);
			}
		}
		else
		{
			for (int i = 0; i < w; i++)
			{
				if (progress_callback != NULL)
				{
					if (progress_callback(i * 100 / w))
					{ fclose(fp); return false; }
				}
				FWrite(m_pData + (i * m_iRows), DT_SHORT, m_iRows, fp, BO_LITTLE_ENDIAN);
			}
		}
#endif
		fclose(fp);
	}
	else
	{
		// Use GZip IO
		gzFile fp = vtGZOpen(szFileName, "wb");
		if (!fp)
			return false;

		gzwrite(fp, (void *)"binterr1.3", 10);
		GZFWrite(&w, DT_INT, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&h, DT_INT, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&datasize,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&isfloat,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&hunits,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);		// Horizontal Units (0, 1, 2, 3)
		GZFWrite(&zone,		DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);		// UTM zone
		GZFWrite(&datum,	DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);		// Datum

		// coordinate extents
		GZFWrite(&m_EarthExtents.left,		DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&m_EarthExtents.right,		DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&m_EarthExtents.bottom,	DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);
		GZFWrite(&m_EarthExtents.top,		DT_DOUBLE, 1, fp, BO_LITTLE_ENDIAN);

		GZFWrite(&external,		DT_SHORT, 1, fp, BO_LITTLE_ENDIAN);	// External projection specification
		GZFWrite(&m_fVMeters,	DT_FLOAT, 1, fp, BO_LITTLE_ENDIAN);	// Vertical scale factor (meters/units)

		// now write the data: always starts at offset 256
		gzseek(fp, 256, SEEK_SET);

		// fast way, with the assumption that the data is stored column-first in memory
		if (m_bFloatMode)
		{
			for (int i = 0; i < w; i++)
			{
				if (progress_callback != NULL)
				{
					if (progress_callback(i * 100 / w))
					{ gzclose(fp); return false; }
				}
				GZFWrite(m_pFData + (i * m_iRows), DT_FLOAT, m_iRows, fp, BO_LITTLE_ENDIAN);
			}
		}
		else
		{
			for (int i = 0; i < w; i++)
			{
				if (progress_callback != NULL)
				{
					if (progress_callback(i * 100 / w))
					{ gzclose(fp); return false; }
				}
				GZFWrite(m_pData + (i * m_iRows), DT_SHORT, m_iRows, fp, BO_LITTLE_ENDIAN);
			}
		}
		gzclose(fp);
	}

	if (external)
	{
		// Write external projection file (.prj)
		char prj_name[256];
		strcpy(prj_name, szFileName);
		int len = strlen(prj_name);
		if (bGZip)
			strcpy(prj_name + len - 6, ".prj"); // overwrite the .bt.gz
		else
			strcpy(prj_name + len - 3, ".prj"); // overwrite the .bt
		m_proj.WriteProjFile(prj_name);
	}

	return true;
}
Ejemplo n.º 30
0
void demo_record_packet(demo *d, ENetPacket *packet)
{
    gzwrite(d->file, packet->data, packet->dataLength);
}