Exemplo n.º 1
0
void *CDataFileReader::GetDataImpl(int Index, int Swap)
{
	if(!m_pDataFile) { return 0; }

	// load it if needed
	if(!m_pDataFile->m_ppDataPtrs[Index])
	{
		// fetch the data size
		int DataSize = GetDataSize(Index);
#if defined(CONF_ARCH_ENDIAN_BIG)
		int SwapSize = DataSize;
#endif

		if(m_pDataFile->m_Header.m_Version == 4)
		{
			// v4 has compressed data
			void *pTemp = (char *)mem_alloc(DataSize, 1);
			unsigned long UncompressedSize = m_pDataFile->m_Info.m_pDataSizes[Index];
			unsigned long s;

			dbg_msg("datafile", "loading data index=%d size=%d uncompressed=%d", Index, DataSize, (int)UncompressedSize);
			m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(UncompressedSize, 1);

			// read the compressed data
			io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
			io_read(m_pDataFile->m_File, pTemp, DataSize);

			// decompress the data, TODO: check for errors
			s = UncompressedSize;
			uncompress((Bytef*)m_pDataFile->m_ppDataPtrs[Index], &s, (Bytef*)pTemp, DataSize); // ignore_convention
#if defined(CONF_ARCH_ENDIAN_BIG)
			SwapSize = s;
#endif

			// clean up the temporary buffers
			mem_free(pTemp);
		}
		else
		{
			// load the data
			dbg_msg("datafile", "loading data index=%d size=%d", Index, DataSize);
			m_pDataFile->m_ppDataPtrs[Index] = (char *)mem_alloc(DataSize, 1);
			io_seek(m_pDataFile->m_File, m_pDataFile->m_DataStartOffset+m_pDataFile->m_Info.m_pDataOffsets[Index], IOSEEK_START);
			io_read(m_pDataFile->m_File, m_pDataFile->m_ppDataPtrs[Index], DataSize);
		}

#if defined(CONF_ARCH_ENDIAN_BIG)
		if(Swap && SwapSize)
			swap_endian(m_pDataFile->m_ppDataPtrs[Index], sizeof(int), SwapSize/sizeof(int));
#endif
	}

	return m_pDataFile->m_ppDataPtrs[Index];
}
Exemplo n.º 2
0
/*-------------------------------------------------------------------------
 * Function:    lite_PD_get_file_length
 *
 * Purpose:     Return current file size 
 *
 * Programmer:  Adapted from PACT, Mark C. Miller, 26Feb08
 *
 *-------------------------------------------------------------------------
 */
long  lite_PD_get_file_length(PDBfile *file) {
    off_t caddr, flen;

    caddr = io_tell(file->stream);
    io_seek(file->stream, 0, SEEK_END);

    flen = io_tell(file->stream);
    io_seek(file->stream, caddr, SEEK_SET);

    return((long)flen);
}
Exemplo n.º 3
0
int avi_close(avi_Context* AVI)
{
    int res = 0;
    int n, nb_frames;
    int64_t file_size;

    avi_RIFF* riff = avi_get_last_riff(AVI);

    if (riff->id == 1)
    {
        avi_close_tag(AVI, riff->movi_list);
        fprintf(stderr, "AVI: (%" PRIu64 ") close movi tag\n",io_get_offset(AVI->writer));
        res = avi_write_idx1(AVI, riff);
        avi_close_tag(AVI, riff->riff_start);
    }
    else
    {
        avi_write_ix(AVI);
        avi_close_tag(AVI, riff->movi_list);
        avi_close_tag(AVI, riff->riff_start);

        file_size = io_get_offset(AVI->writer);
        io_seek(AVI->writer, AVI->odml_list - 8);
        io_write_4cc(AVI->writer, "LIST"); /* Making this AVI OpenDML one */
        io_skip(AVI->writer, 16);

        for (n=nb_frames=0;n<AVI->stream_list_size;n++)
        {
            io_Stream *stream = get_stream(AVI->stream_list, n);

            if (stream->type == STREAM_TYPE_VIDEO)
            {
                if (nb_frames < stream->packet_count)
                        nb_frames = stream->packet_count;
            }
            else
            {
                if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3)
                        nb_frames += stream->packet_count;
            }
        }
        io_write_wl32(AVI->writer, nb_frames);
        io_seek(AVI->writer, file_size);

        avi_write_counters(AVI, riff);
    }

	clean_indexes(AVI);

    return res;
}
Exemplo n.º 4
0
static void *datafile_get_data_impl(DATAFILE *df, int index, int swap)
{
	/* load it if needed */
	if(!df->data_ptrs[index])
	{
		/* fetch the data size */
		int datasize = datafile_get_datasize(df, index);
		int swapsize = datasize;
		
		if(df->header.version == 4)
		{
			/* v4 has compressed data */
			void *temp = (char *)mem_alloc(datasize, 1);
			unsigned long uncompressed_size = df->info.data_sizes[index];
			unsigned long s;

			dbg_msg("datafile", "loading data index=%d size=%d uncompressed=%d", index, datasize, uncompressed_size);
			df->data_ptrs[index] = (char *)mem_alloc(uncompressed_size, 1);
			
			/* read the compressed data */
			io_seek(df->file, df->data_start_offset+df->info.data_offsets[index], IOSEEK_START);
			io_read(df->file, temp, datasize);

			/* decompress the data, TODO: check for errors */
			s = uncompressed_size;
			uncompress((Bytef*)df->data_ptrs[index], &s, (Bytef*)temp, datasize);
			swapsize = s;

			/* clean up the temporary buffers */
			mem_free(temp);
		}
		else
		{
			/* load the data */
			dbg_msg("datafile", "loading data index=%d size=%d", index, datasize);
			df->data_ptrs[index] = (char *)mem_alloc(datasize, 1);
			io_seek(df->file, df->data_start_offset+df->info.data_offsets[index], IOSEEK_START);
			io_read(df->file, df->data_ptrs[index], datasize);
		}

#if defined(CONF_ARCH_ENDIAN_BIG)
		if(swap && swapsize)
			swap_endian(df->data_ptrs[index], sizeof(int), swapsize/sizeof(int));
#endif
	}
	
	return df->data_ptrs[index];
}
Exemplo n.º 5
0
static int seek_cb (void *datasource, ogg_int64_t offset, int whence)
{
	debug ("Seek request to %"PRId64" (%s)", offset,
			whence == SEEK_SET ? "SEEK_SET"
			: (whence == SEEK_CUR ? "SEEK_CUR" : "SEEK_END"));
	return io_seek (datasource, offset, whence) == -1 ? -1 : 0;
}
Exemplo n.º 6
0
/*
 * Load the first sector that carries MBR header.
 * The MBR boot signature should be always valid whether it's MBR or GPT.
 */
static int load_mbr_header(uintptr_t image_handle, mbr_entry_t *mbr_entry)
{
	size_t bytes_read;
	uintptr_t offset;
	int result;

	assert(mbr_entry != NULL);
	/* MBR partition table is in LBA0. */
	result = io_seek(image_handle, IO_SEEK_SET, MBR_OFFSET);
	if (result != 0) {
		WARN("Failed to seek (%i)\n", result);
		return result;
	}
	result = io_read(image_handle, (uintptr_t)&mbr_sector,
			 PARTITION_BLOCK_SIZE, &bytes_read);
	if (result != 0) {
		WARN("Failed to read data (%i)\n", result);
		return result;
	}

	/* Check MBR boot signature. */
	if ((mbr_sector[PARTITION_BLOCK_SIZE - 2] != MBR_SIGNATURE_FIRST) ||
	    (mbr_sector[PARTITION_BLOCK_SIZE - 1] != MBR_SIGNATURE_SECOND)) {
		return -ENOENT;
	}
	offset = (uintptr_t)&mbr_sector + MBR_PRIMARY_ENTRY_OFFSET;
	memcpy(mbr_entry, (void *)offset, sizeof(mbr_entry_t));
	return 0;
}
Exemplo n.º 7
0
/*
 * Load GPT header and check the GPT signature.
 * If partiton numbers could be found, check & update it.
 */
static int load_gpt_header(uintptr_t image_handle)
{
	gpt_header_t header;
	size_t bytes_read;
	int result;

	result = io_seek(image_handle, IO_SEEK_SET, GPT_HEADER_OFFSET);
	if (result != 0) {
		return result;
	}
	result = io_read(image_handle, (uintptr_t)&header,
			 sizeof(gpt_header_t), &bytes_read);
	if ((result != 0) || (sizeof(gpt_header_t) != bytes_read)) {
		return result;
	}
	if (memcmp(header.signature, GPT_SIGNATURE,
		   sizeof(header.signature)) != 0) {
		return -EINVAL;
	}

	/* partition numbers can't exceed PLAT_PARTITION_MAX_ENTRIES */
	list.entry_count = header.list_num;
	if (list.entry_count > PLAT_PARTITION_MAX_ENTRIES) {
		list.entry_count = PLAT_PARTITION_MAX_ENTRIES;
	}
	return 0;
}
Exemplo n.º 8
0
Arquivo: cmd.c Projeto: radare/ired
static int cmd_write(const char *arg) {
	ut8 *barg;
	int len;
	SKIPSPACES(arg);
	if(*arg=='"') {
		barg = (ut8*)strdup (arg+1);
		len = strlen(++arg)-1;
		// TODO: ensure last char is "
		barg[len] = '\0';
	} else {
		barg = (ut8*)strdup (arg);
		len = hexstr2raw(barg);
	}
	if (len<2)  {
		printf ("Invalid hexpair\n");
		return 2;
	}
	io_seek(curseek, SEEK_SET);
	if(len<1 || io_write(barg, len)<len) {
		perror("io_write");
		return -1;
	}
	//free ((void*)arg);
	return 1;
}
Exemplo n.º 9
0
static int seek_callback (void *datasource, ogg_int64_t offset, int whence)
{
	debug ("Seek request to %ld (%s)", (long)offset,
			whence == SEEK_SET ? "SEEK_SET"
			: (whence == SEEK_CUR ? "SEEK_CUR" : "SEEK_END"));
	return io_seek (datasource, offset, whence);
}
Exemplo n.º 10
0
Arquivo: cmd.c Projeto: radare/ired
static int cmd_seek(char *arg) {
	if(!*arg) printf("%"LLF"d\n", curseek);
	else if(*arg=='+') curseek += str2ut64(arg+1);
	else if(*arg=='-') curseek -= str2ut64(arg+1);
	else curseek = str2ut64(arg);
	io_seek((oldseek=curseek), 0);
	return 1;
}
Exemplo n.º 11
0
static struct mp3_data *mp3_open_internal (const char *file,
		const int buffered)
{
	struct mp3_data *data;

	data = (struct mp3_data *)xmalloc (sizeof(struct mp3_data));
	data->ok = 0;
	decoder_error_init (&data->error);

	/* Reset information about the file */
	data->freq = 0;
	data->channels = 0;
	data->skip_frames = 0;
	data->bitrate = -1;
	data->avg_bitrate = -1;

	/* Open the file */
	data->io_stream = io_open (file, buffered);
	if (io_ok(data->io_stream)) {
		data->ok = 1;
		
		data->size = io_file_size (data->io_stream);

		mad_stream_init (&data->stream);
		mad_frame_init (&data->frame);
		mad_synth_init (&data->synth);

		if (options_get_int("Mp3IgnoreCRCErrors"))
				mad_stream_options (&data->stream,
					MAD_OPTION_IGNORECRC);
		
		data->duration = count_time_internal (data);
		mad_frame_mute (&data->frame);
		data->stream.next_frame = NULL;
		data->stream.sync = 0;
		data->stream.error = MAD_ERROR_NONE;

		if (io_seek(data->io_stream, SEEK_SET, 0) == (off_t)-1) {
			decoder_error (&data->error, ERROR_FATAL, 0,
						"seek failed");
			io_close (data->io_stream);
			mad_stream_finish (&data->stream);
			mad_frame_finish (&data->frame);
			mad_synth_finish (&data->synth);
			data->ok = 0;
		}

		data->stream.error = MAD_ERROR_BUFLEN;
	}
	else {
		decoder_error (&data->error, ERROR_FATAL, 0, "Can't open: %s",
				io_strerror(data->io_stream));
		io_close (data->io_stream);
	}

	return data;
}
Exemplo n.º 12
0
/*
 * returns length of a file (if filept points to a file)
 * reads the last 128 bytes information into buffer
 * ... that is not totally safe...
 */
static off_t get_fileinfo(mpg123_handle *fr)
{
	off_t len;

	if((len=io_seek(&fr->rdat,0,SEEK_END)) < 0)	return -1;

	if(io_seek(&fr->rdat,-128,SEEK_END) < 0) return -1;

	if(fr->rd->fullread(fr,(unsigned char *)fr->id3buf,128) != 128)	return -1;

	if(!strncmp((char*)fr->id3buf,"TAG",3))	len -= 128;

	if(io_seek(&fr->rdat,0,SEEK_SET) < 0)	return -1;

	if(len <= 0)	return -1;

	return len;
}
Exemplo n.º 13
0
/* This should be called with a unique decoder instance as the seeking
 * it does triggers an FAAD bug which results in distorted audio due to
 * retained state being corrupted.  (One suspects NeAACDecPostSeekReset()
 * should resolve the problem but experimentation suggests not and no
 * documentation exists describing its use.) */
static int aac_count_time (struct aac_data *data)
{
	NeAACDecFrameInfo frame_info;
	int samples = 0, bytes = 0, frames = 0;
	off_t file_size;
	int16_t *sample_buf;

	file_size = io_file_size (data->stream);
	if (file_size == -1)
		return -1;

	if (io_seek(data->stream, file_size / 2, SEEK_SET) == -1)
		return -1;
	buffer_flush (data);

	/* Guess track length by decoding the middle 50 frames which have
	 * more than 25% of samples having absolute values greater than 16. */
	while (frames < 50) {
		if (buffer_fill_frame (data) <= 0)
			break;

		sample_buf = NeAACDecDecode (data->decoder, &frame_info,
		                             buffer_data (data), buffer_length (data));

		if (frame_info.error == 0 && frame_info.samples > 0) {
			unsigned int ix, zeroes = 0;

			for (ix = 0; ix < frame_info.samples; ix += 1) {
				if (RANGE(-16, sample_buf[ix], 16))
					zeroes += 1;
			}

			if (zeroes * 4 < frame_info.samples) {
				samples += frame_info.samples;
				bytes += frame_info.bytesconsumed;
				frames += 1;
			}
		}

		if (frame_info.bytesconsumed == 0)
			break;

		buffer_consume (data, frame_info.bytesconsumed);
	}

	if (frames == 0)
		return -1;

	samples /= frames;
	samples /= data->channels;
	bytes /= frames;

	return ((file_size / bytes) * samples) / data->sample_rate;
}
Exemplo n.º 14
0
static off_t stream_lseek(mpg123_handle *fr, off_t pos, int whence)
{
	off_t ret;
	ret = io_seek(&fr->rdat, pos, whence);
	if (ret >= 0)	fr->rdat.filepos = ret;
	else
	{
		fr->err = MPG123_LSEEK_FAILED;
		ret = READER_ERROR; /* not the original value */
	}
	return ret;
}
Exemplo n.º 15
0
/* Read data from a file in package */
static int fip_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
			  size_t *length_read)
{
	int result;
	file_state_t *fp;
	size_t file_offset;
	size_t bytes_read;
	uintptr_t backend_handle;

	assert(entity != NULL);
	assert(buffer != (uintptr_t)NULL);
	assert(length_read != NULL);
	assert(entity->info != (uintptr_t)NULL);

	/* Open the backend, attempt to access the blob image */
	result = io_open(backend_dev_handle, backend_image_spec,
			 &backend_handle);
	if (result != 0) {
		WARN("Failed to open FIP (%i)\n", result);
		result = -ENOENT;
		goto fip_file_read_exit;
	}

	fp = (file_state_t *)entity->info;

	/* Seek to the position in the FIP where the payload lives */
	file_offset = fp->entry.offset_address + fp->file_pos;
	result = io_seek(backend_handle, IO_SEEK_SET, file_offset);
	if (result != 0) {
		WARN("fip_file_read: failed to seek\n");
		result = -ENOENT;
		goto fip_file_read_close;
	}

	result = io_read(backend_handle, buffer, length, &bytes_read);
	if (result != 0) {
		/* We cannot read our data. Fail. */
		WARN("Failed to read payload (%i)\n", result);
		result = -ENOENT;
		goto fip_file_read_close;
	} else {
		/* Set caller length and new file position. */
		*length_read = bytes_read;
		fp->file_pos += bytes_read;
	}

/* Close the backend. */
 fip_file_read_close:
	io_close(backend_handle);

 fip_file_read_exit:
	return result;
}
Exemplo n.º 16
0
Arquivo: aac.c Projeto: gitkaste/moc
static int aac_count_time (struct aac_data *data)
{
	NeAACDecFrameInfo frame_info;
	int samples = 0, bytes = 0, frames = 0;
	off_t file_size;
	char *sample_buf;
	long saved_pos;

	file_size = io_file_size (data->stream);
	if (file_size == -1)
		return -1;

	saved_pos = io_tell (data->stream);

	/* guess track length by decoding the first 10 frames */
	while (frames < 10) {
		if (buffer_fill_frame(data) <= 0)
			break;

		sample_buf = NeAACDecDecode(data->decoder, &frame_info,
			buffer_data(data), buffer_length(data));
		if (frame_info.error == 0 && frame_info.samples > 0) {
			samples += frame_info.samples;
			bytes += frame_info.bytesconsumed;
			frames++;
		}
		if (frame_info.bytesconsumed == 0)
			break;

		buffer_consume (data, frame_info.bytesconsumed);
	}

	if (io_seek(data->stream, saved_pos, SEEK_SET) == (off_t)-1) {
		logit ("Can't seek after couting time");
		return -1;
	}

	if (frames == 0)
		return -1;

	samples /= frames;
	samples /= data->channels;
	bytes /= frames;

	return ((file_size / bytes) * samples) / data->sample_rate;
}
Exemplo n.º 17
0
static mpg_off_t stream_lseek( mpg123_handle_t *fr, mpg_off_t pos, int whence )
{
	mpg_off_t	ret;

	ret = io_seek( &fr->rdat, pos, whence );

	if( ret >= 0 )
	{
		fr->rdat.filepos = ret;
	}
	else
	{
		fr->err = MPG123_LSEEK_FAILED;
		ret = MPG123_ERR;
	}

	return ret;
}
Exemplo n.º 18
0
Arquivo: cmd.c Projeto: radare/ired
static int cmd_load(char *file) {
	FILE *fd = fopen(file, "rb");
	if(fd) {
		void *buf = malloc(bsize);
		if(bsize>0 && buf) {
			int len = fread(buf, 1, bsize, fd);
			if(len<bsize)
				perror("fread");
			io_seek (curseek, SEEK_SET);
			if(io_write(buf, len)<len) {
				perror("io_write");
				return -1;
			}
		} else perror("malloc");
		free(buf);
		fclose(fd);
	} else perror("fopen");
	return 1;
}
Exemplo n.º 19
0
Arquivo: speex.c Projeto: gitkaste/moc
static int count_time (struct spx_data *data)
{
	unsigned long last_granulepos = 0;

	/* Seek to somewhere neer the last page */
	if (io_file_size(data->stream) > 10000) {
		debug ("Seeking near the end");
		if (io_seek(data->stream, -10000, SEEK_END) == -1)
			logit ("Seeking failed, scaning whole file");
		ogg_sync_reset (&data->oy);
	}
	
	/* Read granulepos from the last packet */
	while (!io_eof(data->stream)) {

		/* Sync to page and read it */
		while (!io_eof(data->stream)) {
			char *buf;
			int nb_read;

			if (ogg_sync_pageout(&data->oy, &data->og) == 1) {
				debug ("Sync");
				break;
			}
			else if (!io_eof(data->stream)) {
				debug ("Need more data");
				buf = ogg_sync_buffer (&data->oy, 200);
				nb_read = io_read (data->stream, buf, 200);
				ogg_sync_wrote (&data->oy, nb_read);
			}
		}

		/* We have last packet */
		if (io_eof(data->stream))
			break;

		last_granulepos = ogg_page_granulepos (&data->og);
	}

	return last_granulepos / data->rate;
}
Exemplo n.º 20
0
Arquivo: cmd.c Projeto: radare/ired
static int cmd_resize(char *arg) {
	ut8 *buf;
	ut64 tail, n;
	int i, len, ret = 0;
	switch(*arg) {
	case '\0':
		printf("%"LLF"d\n", (ut64)io_seek(0, SEEK_END));
		break;
	case '+': // XXX: needs cleanup
		n = str2ut64(arg+1);
		len = (ut64)io_seek(0, SEEK_END);
		tail = len-curseek;
		if((buf=malloc(tail))) { // XXX: Use block
			io_seek(curseek, SEEK_SET);
			io_read(buf, tail);
			io_seek(curseek+n, SEEK_SET);
			io_write(buf, tail);
			free (buf);
		} else perror("malloc");
		break;
	case '-':
		buf = malloc(bsize);
		if(buf) {
			n = str2ut64(arg+1);
			for(i=0;!ret;i+=len) {
				io_seek(curseek+n+i, SEEK_SET);
				if((len = io_read(buf, bsize))>0) {
					io_seek(curseek+i, SEEK_SET);
					if(io_write(buf, len)<len)
						perror("io_write"),ret=-1;
				} else break; //perror("io_read"), ret=-1;
			}
			free(buf);
			if((ret = io_seek(0, SEEK_END))>n)
				ret = io_truncate(ret-n);
		} else perror("malloc");
		break;
	default:
		ret = io_truncate(str2ut64(arg));
	}
	if(ret<0) perror("truncate");
	return 1;
}
Exemplo n.º 21
0
int load_partition_table(unsigned int image_id)
{
	uintptr_t dev_handle, image_handle, image_spec = 0;
	mbr_entry_t mbr_entry;
	int result;

	result = plat_get_image_source(image_id, &dev_handle, &image_spec);
	if (result != 0) {
		WARN("Failed to obtain reference to image id=%u (%i)\n",
			image_id, result);
		return result;
	}

	result = io_open(dev_handle, image_spec, &image_handle);
	if (result != 0) {
		WARN("Failed to access image id=%u (%i)\n", image_id, result);
		return result;
	}

	result = load_mbr_header(image_handle, &mbr_entry);
	if (result != 0) {
		WARN("Failed to access image id=%u (%i)\n", image_id, result);
		return result;
	}
	if (mbr_entry.type == PARTITION_TYPE_GPT) {
		result = load_gpt_header(image_handle);
		assert(result == 0);
		result = io_seek(image_handle, IO_SEEK_SET, GPT_ENTRY_OFFSET);
		assert(result == 0);
		result = verify_partition_gpt(image_handle);
	} else {
		/* MBR type isn't supported yet. */
		result = -EINVAL;
		goto exit;
	}
exit:
	io_close(image_handle);
	return result;
}
Exemplo n.º 22
0
static int count_time (struct spx_data *data)
{
	ogg_int64_t last_granulepos = 0;

	/* Seek to somewhere near the last page */
	if (io_file_size(data->stream) > 10000) {
		debug ("Seeking near the end");
		if (io_seek(data->stream, -10000, SEEK_END) == -1)
			logit ("Seeking failed, scanning whole file");
		ogg_sync_reset (&data->oy);
	}

	/* Read granulepos from the last packet */
	while (!io_eof(data->stream)) {

		/* Sync to page and read it */
		while (!io_eof(data->stream)) {
			if (ogg_sync_pageout(&data->oy, &data->og) == 1) {
				debug ("Sync");
				break;
			}

			if (!io_eof(data->stream)) {
				debug ("Need more data");
				get_more_data (data);
			}
		}

		/* We have last packet */
		if (io_eof(data->stream))
			break;

		last_granulepos = ogg_page_granulepos (&data->og);
	}

	return last_granulepos / data->rate;
}
Exemplo n.º 23
0
extern char*
mmap_read(const char* filename, size_t* filesize) {
#if WINDOWS_NATIVE
  HANDLE fd, m;
  char* map;
  fd = CreateFileA(filename,
                   GENERIC_READ,
                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
                   0,
                   OPEN_EXISTING,
                   FILE_ATTRIBUTE_NORMAL,
                   0);
  if(fd == INVALID_HANDLE_VALUE)
    return 0;
  m = CreateFileMapping(fd, 0, PAGE_READONLY, 0, 0, NULL);
  map = 0;
  if(m)
    if((map = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0)))
      *filesize = GetFileSize(fd, NULL);
  CloseHandle(m);
  CloseHandle(fd);
  return map;
#else
  fd_t fd = open_read(filename);
  char* map;
  if(fd >= 0) {
    off_t off = 0;
    *filesize = io_seek(fd, off, SEEK_END);
    map = mmap(0, *filesize, PROT_READ, MAP_SHARED, fd, 0);
    if(map == (char*)-1)
      map = 0;
    close(fd);
    return map;
  }
  return 0;
#endif
}
Exemplo n.º 24
0
void CUpdater::CheckUpdates(CMenus *pMenus)
{
	dbg_msg("autoupdate", "Checking for updates...");
	if (!CHttpDownloader::GetToFile("http://" UPDATES_HOST UPDATES_BASE_PATH UPDATES_MANIFEST_FILE, UPDATES_MANIFEST_FILE))
	{
		dbg_msg("autoupdate", "Error downloading updates manifest :/");
		return;
	}

    Reset();

    IOHANDLE fileAutoUpdate = io_open(UPDATES_MANIFEST_FILE, IOFLAG_READ);
    io_seek(fileAutoUpdate, 0, IOSEEK_END);
    std::streamsize size = io_tell(fileAutoUpdate);
    io_seek(fileAutoUpdate, 0, IOSEEK_START);

    std::vector<char> buffer(size);
    if (io_read(fileAutoUpdate, buffer.data(), size))
    {
        bool needUpdate = false;

        json_settings JsonSettings;
        mem_zero(&JsonSettings, sizeof(JsonSettings));
        char aError[256];
        json_value *pJsonNodeMain = json_parse_ex(&JsonSettings, buffer.data(), size, aError);
        if (pJsonNodeMain == 0)
        {
            dbg_msg("autoupdate", "Error: %s", aError);
            return;
        }

        int verCode = -1;
        for(int j=pJsonNodeMain->u.object.length-1; j>=0; j--) // Ascendent Search: Manifest has descendant order
        {
            sscanf((const char *)pJsonNodeMain->u.object.values[j].name, "%d", &verCode);
            json_value *pNodeCode = pJsonNodeMain->u.object.values[j].value;

            if (verCode <= HCLIENT_VERSION_CODE)
                continue;

            needUpdate = true;

            const json_value &rVersion = (*pNodeCode)["version"];
            str_copy(m_NewVersion, (const char *)rVersion, sizeof(m_NewVersion));

            // Need update client?
            const json_value &rClient = (*pNodeCode)["client"];
            m_NeedUpdateClient = (rClient.u.boolean);

            // Need update server?
            const json_value &rServer = (*pNodeCode)["server"];
            m_NeedUpdateServer = (rServer.u.boolean);

            // Get files to download
            const json_value &rDownload = (*pNodeCode)["download"];
            for(unsigned k = 0; k < rDownload.u.array.length; k++)
                AddFileToDownload((const char *)rDownload[k]);
            // Get files to remove
            const json_value &rRemove = (*pNodeCode)["remove"];
            for(unsigned k = 0; k < rRemove.u.array.length; k++)
                AddFileToRemove((const char *)rRemove[k]);
        }

        if (needUpdate) pMenus->SetPopup(CMenus::POPUP_UPDATER);
        else m_Updated = true;
    }

    io_close(fileAutoUpdate);
    fs_remove(UPDATES_MANIFEST_FILE);
}
Exemplo n.º 25
0
bool CDataFileReader::Open(class IStorage *pStorage, const char *pFilename)
{
	dbg_msg("datafile", "loading. filename='%s'", pFilename);

	IOHANDLE File = pStorage->OpenFile(pFilename, IOFLAG_READ);
	if(!File)
	{
		dbg_msg("datafile", "could not open '%s'", pFilename);
		return false;
	}	
	
	
	// take the CRC of the file and store it
	unsigned Crc = 0;
	{
		enum
		{
			BUFFER_SIZE = 64*1024
		};
		
		unsigned char aBuffer[BUFFER_SIZE];
		
		while(1)
		{
			unsigned Bytes = io_read(File, aBuffer, BUFFER_SIZE);
			if(Bytes <= 0)
				break;
			Crc = crc32(Crc, aBuffer, Bytes); // ignore_convention
		}
		
		io_seek(File, 0, IOSEEK_START);
	}
	
	
	// TODO: change this header
	CDatafileHeader Header;
	io_read(File, &Header, sizeof(Header));
	if(Header.m_aId[0] != 'A' || Header.m_aId[1] != 'T' || Header.m_aId[2] != 'A' || Header.m_aId[3] != 'D')
	{
		if(Header.m_aId[0] != 'D' || Header.m_aId[1] != 'A' || Header.m_aId[2] != 'T' || Header.m_aId[3] != 'A')
		{
			dbg_msg("datafile", "wrong signature. %x %x %x %x", Header.m_aId[0], Header.m_aId[1], Header.m_aId[2], Header.m_aId[3]);
			return 0;
		}
	}

#if defined(CONF_ARCH_ENDIAN_BIG)
	swap_endian(&Header, sizeof(int), sizeof(Header)/sizeof(int));	
#endif
	if(Header.m_Version != 3 && Header.m_Version != 4)
	{
		dbg_msg("datafile", "wrong version. version=%x", Header.m_Version);
		return 0;
	}
	
	// read in the rest except the data
	unsigned Size = 0;
	Size += Header.m_NumItemTypes*sizeof(CDatafileItemType);
	Size += (Header.m_NumItems+Header.m_NumRawData)*sizeof(int);
	if(Header.m_Version == 4)
		Size += Header.m_NumRawData*sizeof(int); // v4 has uncompressed data sizes aswell
	Size += Header.m_ItemSize;
	
	unsigned AllocSize = Size;
	AllocSize += sizeof(CDatafile); // add space for info structure
	AllocSize += Header.m_NumRawData*sizeof(void*); // add space for data pointers

	m_pDataFile = (CDatafile*)mem_alloc(AllocSize, 1);
	m_pDataFile->m_Header = Header;
	m_pDataFile->m_DataStartOffset = sizeof(CDatafileHeader) + Size;
	m_pDataFile->m_ppDataPtrs = (char**)(m_pDataFile+1);
	m_pDataFile->m_pData = (char *)(m_pDataFile+1)+Header.m_NumRawData*sizeof(char *);
	m_pDataFile->m_File = File;
	m_pDataFile->m_Crc = Crc;
	
	// clear the data pointers
	mem_zero(m_pDataFile->m_ppDataPtrs, Header.m_NumRawData*sizeof(void*));
	
	// read types, offsets, sizes and item data
	unsigned ReadSize = io_read(File, m_pDataFile->m_pData, Size);
	if(ReadSize != Size)
	{
		mem_free(m_pDataFile);
		m_pDataFile = 0;
		dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", Size, ReadSize);
		return false;
	}

#if defined(CONF_ARCH_ENDIAN_BIG)
	swap_endian(m_pDataFile->m_pData, sizeof(int), Header.Swaplen / sizeof(int));
#endif

	//if(DEBUG)
	{
		dbg_msg("datafile", "allocsize=%d", AllocSize);
		dbg_msg("datafile", "readsize=%d", ReadSize);
		dbg_msg("datafile", "swaplen=%d", Header.m_Swaplen);
		dbg_msg("datafile", "item_size=%d", m_pDataFile->m_Header.m_ItemSize);
	}
	
	m_pDataFile->m_Info.m_pItemTypes = (CDatafileItemType *)m_pDataFile->m_pData;
	m_pDataFile->m_Info.m_pItemOffsets = (int *)&m_pDataFile->m_Info.m_pItemTypes[m_pDataFile->m_Header.m_NumItemTypes];
	m_pDataFile->m_Info.m_pDataOffsets = (int *)&m_pDataFile->m_Info.m_pItemOffsets[m_pDataFile->m_Header.m_NumItems];
	m_pDataFile->m_Info.m_pDataSizes = (int *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];
	
	if(Header.m_Version == 4)
		m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataSizes[m_pDataFile->m_Header.m_NumRawData];
	else
		m_pDataFile->m_Info.m_pItemStart = (char *)&m_pDataFile->m_Info.m_pDataOffsets[m_pDataFile->m_Header.m_NumRawData];
	m_pDataFile->m_Info.m_pDataStart = m_pDataFile->m_Info.m_pItemStart + m_pDataFile->m_Header.m_ItemSize;

	dbg_msg("datafile", "loading done. datafile='%s'", pFilename);

	if(DEBUG)
	{
		/*
		for(int i = 0; i < m_pDataFile->data.num_raw_data; i++)
		{
			void *p = datafile_get_data(df, i);
			dbg_msg("datafile", "%d %d", (int)((char*)p - (char*)(&m_pDataFile->data)), size);
		}
			
		for(int i = 0; i < datafile_num_items(df); i++)
		{
			int type, id;
			void *data = datafile_get_item(df, i, &type, &id);
			dbg_msg("map", "\t%d: type=%x id=%x p=%p offset=%d", i, type, id, data, m_pDataFile->info.item_offsets[i]);
			int *idata = (int*)data;
			for(int k = 0; k < 3; k++)
				dbg_msg("datafile", "\t\t%d=%d (%x)", k, idata[k], idata[k]);
		}

		for(int i = 0; i < m_pDataFile->data.num_m_aItemTypes; i++)
		{
			dbg_msg("map", "\t%d: type=%x start=%d num=%d", i,
				m_pDataFile->info.m_aItemTypes[i].type,
				m_pDataFile->info.m_aItemTypes[i].start,
				m_pDataFile->info.m_aItemTypes[i].num);
			for(int k = 0; k < m_pDataFile->info.m_aItemTypes[i].num; k++)
			{
				int type, id;
				datafile_get_item(df, m_pDataFile->info.m_aItemTypes[i].start+k, &type, &id);
				if(type != m_pDataFile->info.m_aItemTypes[i].type)
					dbg_msg("map", "\tERROR");
			}
		}
		*/
	}
		
	return true;
}
Exemplo n.º 26
0
/* Open a file for access from package. */
static int fip_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
			 io_entity_t *entity)
{
	int result;
	uintptr_t backend_handle;
	const io_uuid_spec_t *uuid_spec = (io_uuid_spec_t *)spec;
	size_t bytes_read;
	int found_file = 0;

	assert(uuid_spec != NULL);
	assert(entity != NULL);

	/* Can only have one file open at a time for the moment. We need to
	 * track state like file cursor position. We know the header lives at
	 * offset zero, so this entry should never be zero for an active file.
	 * When the system supports dynamic memory allocation we can allow more
	 * than one open file at a time if needed.
	 */
	if (current_file.entry.offset_address != 0) {
		WARN("fip_file_open : Only one open file at a time.\n");
		return -ENOMEM;
	}

	/* Attempt to access the FIP image */
	result = io_open(backend_dev_handle, backend_image_spec,
			 &backend_handle);
	if (result != 0) {
		WARN("Failed to open Firmware Image Package (%i)\n", result);
		result = -ENOENT;
		goto fip_file_open_exit;
	}

	/* Seek past the FIP header into the Table of Contents */
	result = io_seek(backend_handle, IO_SEEK_SET, sizeof(fip_toc_header_t));
	if (result != 0) {
		WARN("fip_file_open: failed to seek\n");
		result = -ENOENT;
		goto fip_file_open_close;
	}

	found_file = 0;
	do {
		result = io_read(backend_handle,
				 (uintptr_t)&current_file.entry,
				 sizeof(current_file.entry),
				 &bytes_read);
		if (result == 0) {
			if (compare_uuids(&current_file.entry.uuid,
					  &uuid_spec->uuid) == 0) {
				found_file = 1;
				break;
			}
		} else {
			WARN("Failed to read FIP (%i)\n", result);
			goto fip_file_open_close;
		}
	} while (compare_uuids(&current_file.entry.uuid, &uuid_null) != 0);

	if (found_file == 1) {
		/* All fine. Update entity info with file state and return. Set
		 * the file position to 0. The 'current_file.entry' holds the
		 * base and size of the file.
		 */
		current_file.file_pos = 0;
		entity->info = (uintptr_t)&current_file;
	} else {
		/* Did not find the file in the FIP. */
		current_file.entry.offset_address = 0;
		result = -ENOENT;
	}

 fip_file_open_close:
	io_close(backend_handle);

 fip_file_open_exit:
	return result;
}
Exemplo n.º 27
0
static syment *
_PD_write (PDBfile *file, char *name, char *intype, char *outtype,
	   lite_SC_byte *vr, dimdes *dims, int appnd) {

   int reset;
   syment *ep;
   long number, addr;
   char bf[MAXLINE], fullpath[MAXLINE], *lname;

   _append_flag = FALSE;

   ep = NULL;

   switch (setjmp(_lite_PD_write_err)) {
   case ABORT    : return(NULL);
   case ERR_FREE : return(ep);
   default       : memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   if (file->mode == PD_OPEN) {
      lite_PD_error("FILE OPENED IN READ-ONLY MODE - _PD_WRITE", PD_WRITE);
   }

   strcpy(fullpath, _lite_PD_fixname(file, name));

   /*
    * Append a new block to an existing entry if TRUE.
    */
   if (appnd) {
      strcpy(bf, fullpath);

      /*
       * Do this so that things such as a[20:20].b work properly
       * NOTE: this also implies that a[20:20].b.c works while
       *       a.b[20:20].c doesn't
       * for now this defines the semantics of append (10/6/93)
       */
      lname = lite_SC_firsttok(bf, ".()[]");

      ep = lite_PD_inquire_entry(file, lname, FALSE, NULL);
      if (ep == NULL) {
	 lite_PD_error("CAN'T APPEND TO NON-EXISTING ENTRY - _PD_WRITE",
		       PD_WRITE);
      }
      _lite_PD_adj_dimensions(file, fullpath, ep);

      /*
       * Extend the syment.
       */
      _lite_PD_add_block(file, ep, dims);
   }

   addr = file->chrtaddr;
   ep   = _lite_PD_effective_ep(file, fullpath, FALSE, NULL);

   if (ep != NULL) {
      /*
       * If the variable already exists use the existing file info.
       */
      addr   = PD_entry_address(ep);
      _lite_PD_rl_dimensions(dims);
      lname  = fullpath;
      reset  = FALSE;
   } else {
      /*
       * If the variable doesn't exist define it to the file.
       */
      number = _lite_PD_comp_num(dims);
      ep     = _lite_PD_mk_syment(outtype, number, addr, NULL, dims);

      strcpy(bf, fullpath);
      lname = lite_SC_firsttok(bf, ".([ ");
      _lite_PD_e_install(lname, ep, file->symtab);

      reset = TRUE;
   }

   if (file->virtual_internal) {
      SC_address ad;

      ad.memaddr = vr;
      ep->blocks->diskaddr = ad.diskaddr;
      lite_SC_mark(vr, 1);
      ep = lite_PD_copy_syment(ep);
   } else {
      if (outtype == NULL) outtype = PD_entry_type(ep);

      if (intype == NULL) intype = outtype;

      /*
       * Go to the correct address.
       */
      if (io_seek(file->stream, addr, SEEK_SET)) {
	 lite_PD_error("FSEEK FAILED TO FIND CURRENT ADDRESS - _PD_WRITE",
		       PD_WRITE);
      }

      /*
       * Do the low level write.
       */
      if (!_lite_PD_hyper_write(file, lname, ep, vr, intype)) {
	 lite_PD_error("CAN'T WRITE VARIABLE - _PD_WRITE", PD_WRITE);
      }

      /*
       * If the variable didn't previously exist we're at the end
       * of the file.
       */
      if (reset) {
	 file->chrtaddr = io_tell(file->stream);
	 if (file->chrtaddr == -1L) {
	    lite_PD_error("CAN'T FIND ADDRESS OF NEXT VARIABLE - _PD_WRITE",
			  PD_WRITE);
	 }

	 /*
	  * Make a releasable copy of the entry
	  * SX depends on this critically!!
	  */
	 ep = lite_PD_copy_syment(ep);
      }
   }

   return(ep);
}
Exemplo n.º 28
0
/*-------------------------------------------------------------------------
 * Function:	lite_PD_open
 *
 * Purpose:	Open an existing PDB file, extract the symbol table and
 *		structure chart.
 *
 * Return:	Success:	Ptr to the PDB file structure
 *
 *		Failure:	NULL
 *
 * Programmer:	Adapted from the PACT PDB library
 *		Mar  4, 1996 10:26 AM EST
 *
 * Modifications:
 *
 * 	Robb Matzke, 4 Mar 1996
 *	Fixed indentation.  Files can only be opened with mode `r'.
 *
 * 	Robb Matzke, 17 Apr 1996
 *	Added write capability back into the function, but it is protected
 *	with #ifdef PDB_WRITE.
 *
 *      Mark C. Miller, Fri Apr 13 22:37:56 PDT 2012
 *      Changed mode string checks to strchr to accomodate wider variety
 *      of mode characters for new hash table size and open modes.
 *
 *      Mark C. Miller, Thu Jun 14 13:25:02 PDT 2012
 *      Remove call to io_close in ABORT case. The file pointer may not
 *      have been properly initialized.
 *-------------------------------------------------------------------------
 */
PDBfile *
lite_PD_open (char *name, char *mode) {

   char		str[MAXLINE], *token;
   PDBfile 	*file=NULL;
   static FILE 	*fp;
   syment 	*ep;

#ifdef PDB_WRITE
   /*
    * If opened in write mode use PD_CREATE instead.
    */
   if (strchr(mode,'w')) return lite_PD_create (name);
#else
   assert (!strchr(mode,'r')) ;
#endif

   switch (setjmp(_lite_PD_open_err)) {
   case ABORT:
      if (fp) io_close(fp);
      return(NULL);
   case ERR_FREE:
      return(file);
   default:
      memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   /*
    * Open the file
    */
   strcpy(str, name);

#ifdef PDB_WRITE
   fp = io_open(str, BINARY_MODE_RPLUS);
   if (fp == NULL) {
      if (strchr(mode,'r')) {
#endif
	 fp = io_open(str, BINARY_MODE_R);
	 if (fp == NULL) {
	    lite_PD_error("CAN'T OPEN FILE IN READ-ONLY MODE - PD_OPEN",
			  PD_OPEN);
	 }
#ifdef PDB_WRITE
      } else if (strchr(mode,'a')) {
	 return lite_PD_create (name);
      } else {
	 lite_PD_error("CAN'T OPEN FILE - PD_OPEN", PD_OPEN);
      }
   }
#endif

   if (lite_PD_buffer_size != -1) {
      if (io_setvbuf(fp, NULL, _IOFBF, (size_t) lite_PD_buffer_size)) {
	 lite_PD_error("CAN'T SET FILE BUFFER - PD_OPEN", PD_OPEN);
      }
   }

   file = _lite_PD_mk_pdb(str, mode);
   if (file == NULL) {
      lite_PD_error("CAN'T ALLOCATE PDBFILE - PD_OPEN", PD_OPEN);
   }
   file->stream = fp;
#ifdef PDB_WRITE
   if (strchr(mode,'a')) file->mode = PD_APPEND;
   else file->mode = PD_OPEN;
#else
   file->mode = PD_OPEN ;
#endif

   /*
    * Attempt to read an ASCII header.
    */
   if (io_seek(fp, 0L, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED TO FIND ORIGIN - PD_OPEN", PD_OPEN);
   }
   if (_lite_PD_rfgets(str, MAXLINE, fp) == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ THE FILE HEADER - PD_OPEN", PD_OPEN);
   }

   /*
    * The first token should be the identifying header token.
    */
   token = strtok(str, " ");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FILE HEADER NOT ASCII - PD_OPEN", PD_OPEN);
   }


   if (strcmp(token, HeadTok) == 0) {
      /*
       * This is a PDB_SYSTEM_VERSION 2 or later file.
       * Read the primitive data type formats which set the standard.
       */
      if (!_lite_PD_rd_format(file)) {
         _lite_PD_rl_pdb(file); 
	 lite_PD_error("FAILED TO READ FORMATS - PD_OPEN", PD_OPEN);
      }
      
   } else if (strcmp(token, OldHeadTok) == 0) {
      /*
       * This is a pre-PDB_SYSTEM_VERSION 2 style file. The second token
       * is the machine type that wrote the file.  Set the file->std for
       * machine type for PD_open the file->std is always the PDBfile standard.
       * Alignment issues are not properly handled before PDB_SYSTEM_VERSION 3
       * but do the best that we can.
       */
      token = strtok(NULL, " ");
      if (token == NULL)
      {
         _lite_PD_rl_pdb(file); 
         lite_PD_error("INCOMPLETE HEADER - PD_OPEN", PD_OPEN);
      }
      switch (atoi(token)) {
      case IEEE_32_64:
	 file->std   = _lite_PD_copy_standard(&lite_IEEEA_STD);
	 file->align = _lite_PD_copy_alignment(&lite_M68000_ALIGNMENT);
	 break;
      case IEEE_32_96:
	 file->std   = _lite_PD_copy_standard(&lite_IEEEB_STD);
	 file->align = _lite_PD_copy_alignment(&lite_M68000_ALIGNMENT);
	 break;
      case INTEL_X86:
	 file->std   = _lite_PD_copy_standard(&lite_INTELA_STD);
	 file->align = _lite_PD_copy_alignment(&lite_INTELA_ALIGNMENT);
	 break;
      case CRAY_64:
	 file->std   = _lite_PD_copy_standard(&lite_CRAY_STD);
	 file->align = _lite_PD_copy_alignment(&lite_UNICOS_ALIGNMENT);
	 break;
      case VAX_11:
	 file->std   = _lite_PD_copy_standard(&lite_VAX_STD);
	 file->align = _lite_PD_copy_alignment(&lite_DEF_ALIGNMENT);
	 break;
      default:
	 file->std   = _lite_PD_copy_standard(&lite_DEF_STD);
	 file->align = _lite_PD_copy_alignment(&lite_DEF_ALIGNMENT);
	 break;
      }

      /*
       * To correctly handle the situation in which many PDBfiles are open
       * at the same time always try to latch on to the file->host_std.
       * Alignment issues are not properly handled before PDB_SYSTEM_VERSION 3
       * but do the best that we can
       */
      if (_lite_PD_compare_std(file->host_std, file->std,
			       file->host_align, file->align)) {
	 _lite_PD_rl_standard(file->std);
	 file->std   = _lite_PD_copy_standard(file->host_std);
	 _lite_PD_rl_alignment(file->align);
	 file->align = _lite_PD_copy_alignment(file->host_align);
      }
   } else {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD FILE HEADER - PD_OPEN", PD_OPEN);
   }

   /*
    * Record the current file position as the location of the symbol table
    * address and sequentially the chart address.
    */
   file->headaddr = io_tell(fp);
   if (file->headaddr == -1L) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_OPEN", PD_OPEN);
   }

   /*
    * Read the address of the symbol table and structure chart.
    */
   if (_lite_PD_rfgets(str, MAXLINE, fp) == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ SYMBOL TABLE ADDRESS - PD_OPEN", PD_OPEN);
   }

   token = strtok(str, "\001");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD STRUCTURE CHART ADDRESS - PD_OPEN", PD_OPEN);
   }
   file->chrtaddr = atol(token);

   token = strtok(NULL, "\001");
   if (token == NULL) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("BAD SYMBOL TABLE ADDRESS - PD_OPEN", PD_OPEN);
   }
   file->symtaddr = atol(token);

   /*
    * Read the symbol table first so that the file pointer is positioned
    * to the "extra" information, then read the "extra's" to get the
    * alignment data, and finish with the structure chart which needs
    * the alignment data
    */

   /*
    * Read the symbol table.
    */
   if (io_seek(fp, file->symtaddr, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED SYMBOL TABLE - PD_OPEN", PD_OPEN);
   }
   if (!_lite_PD_rd_symt(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ SYMBOL TABLE - PD_OPEN", PD_OPEN);
   }

   /*
    * Read the miscellaneous data.
    */
   if (!_lite_PD_rd_extras(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ MISCELLANEOUS DATA - PD_OPEN", PD_OPEN);
   }

   /*
    * Initialize the pdb system defs and structure chart.
    */
   _lite_PD_init_chrt(file);

   /*
    * Read the structure chart.
    */
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("FSEEK FAILED STRUCTURE CHART - PD_OPEN", PD_OPEN);
   }
   if (!_lite_PD_rd_chrt(file)) {
      _lite_PD_rl_pdb(file); 
      lite_PD_error("CAN'T READ STRUCTURE CHART - PD_OPEN", PD_OPEN);
   }

   ep = lite_PD_inquire_entry(file, PDB_ATTRIBUTE_TABLE, TRUE, NULL);
   if (ep != NULL) {
      if (!lite_PD_read(file, PDB_ATTRIBUTE_TABLE, &file->attrtab)) {
	 lite_PD_close(file);
	 lite_PD_error("FAILED TO READ ATTRIBUTE TABLE - PD_OPEN", PD_OPEN);
      }
      _lite_PD_convert_attrtab(file);
      file->chrtaddr = PD_entry_address(ep);
      _lite_PD_rl_syment(ep);
      lite_SC_hash_rem(_lite_PD_fixname(file, PDB_ATTRIBUTE_TABLE),
		       file->symtab);
   } else {
      file->attrtab = NULL;
   }

   /*
    * Position the file pointer to the location of the structure chart.
    */
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      lite_PD_close(file);
      lite_PD_error("FSEEK FAILED CHART - PD_OPEN", PD_OPEN);
   }

   return(file);
}
Exemplo n.º 29
0
int
lite_PD_flush (PDBfile *file) {

   FILE *fp;

   if (file->flushed) return(TRUE);

   if (file->attrtab != NULL) {
      lite_PD_cd(file, NULL);
      if (!lite_PD_write(file, PDB_ATTRIBUTE_TABLE, "HASHTAB *",
			 &file->attrtab)) {
	 return(FALSE);
      }
   }

   switch (setjmp(_lite_PD_write_err)) {
   case ABORT:
      return(FALSE);
   case ERR_FREE:
      return(TRUE);
   default:
      memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   fp = file->stream;
   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED BEFORE CHART - PD_FLUSH", PD_WRITE);
   }

   /*
    * Seek the place to write the structure chart.
    */
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      lite_PD_error("FSEEK FAILED TO FIND CHART  - PD_FLUSH", PD_WRITE);
   }

   /*
    * Write the structure chart.
    */
   file->chrtaddr = _lite_PD_wr_chrt(file);
   if (file->chrtaddr == -1L) {
      lite_PD_error("CAN'T WRITE STRUCTURE CHART - PD_FLUSH", PD_WRITE);
   }

   /*
    * Write the symbol table.
    */
   file->symtaddr = _lite_PD_wr_symt(file);
   if (file->symtaddr == -1L) {
      lite_PD_error("CAN'T WRITE SYMBOL TABLE - PD_FLUSH", PD_WRITE);
   }

   /*
    * Write the extras table.
    */
   if (!_lite_PD_wr_extras(file)) {
      lite_PD_error("CAN'T WRITE MISCELLANEOUS DATA - PD_FLUSH", PD_WRITE);
   }

   if (io_tell(fp) == -1L) {
      lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_FLUSH", PD_WRITE);
   }

   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED AFTER CHART - PD_FLUSH", PD_WRITE);
   }

   /*
    * Update the header.
    */
   if (io_seek(fp, file->headaddr, SEEK_SET)) {
      lite_PD_error("FSEEK FAILED - PD_FLUSH", PD_WRITE);
   }

   if (file->headaddr != io_tell(fp)) {
      lite_PD_error("FSEEK FAILED TO FIND HEADER - PD_FLUSH", PD_WRITE);
   }

   io_printf(fp, "%ld\001%ld\001\n", file->chrtaddr, file->symtaddr);

   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED AFTER HEADER - PD_FLUSH", PD_WRITE);
   }

   file->flushed = TRUE;

   return(TRUE);
}
Exemplo n.º 30
0
PDBfile *
lite_PD_create (char *name) {

   char str[MAXLINE];
   PDBfile *file;
   static FILE *fp;

   file = NULL;

   switch (setjmp(_lite_PD_create_err)) {
   case ABORT:
      if (fp) io_close(fp);
      return(NULL);
   case ERR_FREE:
      return(file);
   default:
      memset(lite_PD_err, 0, MAXLINE);
      break;
   }

   /*
    * Open the file.
    */
   strncpy(str, name, sizeof(str));
   str[sizeof(str)-1] = '\0';
   fp = io_open(str, BINARY_MODE_WPLUS);
   if (!fp) lite_PD_error("CAN'T CREATE FILE - PD_CREATE", PD_CREATE);

   if (lite_PD_buffer_size != -1) {
      if (io_setvbuf(fp, NULL, _IOFBF, (size_t) lite_PD_buffer_size)) {
	 lite_PD_error("CAN'T SET FILE BUFFER - PD_CREATE", PD_OPEN);
      }
   }

   /*
    * Make the PDBfile.
    */
   file = _lite_PD_mk_pdb(str, lite_PD_DEF_CREATM);
   if (file == NULL) {
      lite_PD_error("CAN'T ALLOCATE PDBFILE - PD_CREATE", PD_OPEN);
   }

   file->stream = fp;
   file->mode   = PD_CREATE;

   /*
    * Set the file data conversion standard - and yes someone might pick
    * a target standard which is the current standard
    */
   file->std   = _lite_PD_copy_standard(file->host_std);
   file->align = _lite_PD_copy_alignment(file->host_align);
   if (lite_REQ_STANDARD != NULL) {
      if (!_lite_PD_compare_std(lite_REQ_STANDARD, file->std,
				lite_REQ_ALIGNMENT, file->align)) {
	 _lite_PD_rl_standard(file->std);
	 file->std   = _lite_PD_copy_standard(lite_REQ_STANDARD);
	 _lite_PD_rl_alignment(file->align);
	 file->align = _lite_PD_copy_alignment(lite_REQ_ALIGNMENT);
      }
      lite_REQ_STANDARD = NULL;
   }

   /*
    * Write the ASCII header.
    */
   io_printf(fp, "%s\n", HeadTok);
   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED BEFORE HEADER - PD_CREATE", PD_CREATE);
   }

   /*
    * Write the primitive data type formats.
    */
   if (!_lite_PD_wr_format(file)) {
      lite_PD_error("FAILED TO WRITE FORMATS - PD_CREATE", PD_CREATE);
   }

   /*
    * Record the current file position as the location of the symbol table
    * address and sequentially the chart address
    */
   if ((file->headaddr = io_tell(fp)) == -1L) {
      lite_PD_error("CAN'T FIND HEADER ADDRESS - PD_CREATE", PD_CREATE);
   }

   /*
    * Initialize the pdb system defs and structure chart.
    */
   _lite_PD_init_chrt(file);

   if (io_flush(fp)) {
      lite_PD_error("FFLUSH FAILED AFTER HEADER - PD_CREATE", PD_CREATE);
   }

   memset(str, 0, PAD_SIZE);
   if (io_write(str, (size_t) 1, PAD_SIZE, fp) != PAD_SIZE) {
      lite_PD_error("FAILED TO PAD FILE FOR MPW - PD_CREATE", PD_CREATE);
   }

   file->chrtaddr = file->headaddr + 128L;
   if (io_seek(fp, file->chrtaddr, SEEK_SET)) {
      lite_PD_error("FAILED TO FIND START OF DATA - PD_CREATE", PD_CREATE);
   }

   file->system_version = PDB_SYSTEM_VERSION;
   file->date           = lite_SC_date();

   return(file);
}