Exemple #1
0
void stop_recording(
	void)
{
	if (replay.game_is_being_recorded)
	{
		short player_index;
		long count;
		long total_length;
		FileError error;

		assert(replay.valid);
		for (player_index= 0; player_index<dynamic_world->player_count; player_index++)
		{
			save_recording_queue_chunk(player_index);
		}

		replay.game_is_being_recorded = FALSE;
		
		/* Rewrite the header, since it has the new length */
		set_fpos(replay.recording_file_refnum, 0l); 
		count= sizeof(struct recording_header);
		error= write_file(replay.recording_file_refnum, count, &replay.header);
		assert(!error);

		total_length= get_file_length(replay.recording_file_refnum);
		assert(total_length==replay.header.length);
		
		close_file(replay.recording_file_refnum);
	}

	replay.valid= FALSE;
	
	return;
}
Exemple #2
0
int main()
{
	const char* file_path = "../example.json";

	long length = get_file_length(file_path);
	if (length == -1)
	{
		exit(1);
	}

	char* buffer = (char*) malloc(length);

	int ret_val = read_json_file_into_string(file_path, length, buffer);
	if (ret_val == -1)
	{
		exit(1);
	}

	JSON_Obj* base_obj = parse_JSON(buffer, length);

	printf("Items after parse:\n");
	printf("==================\n\n");
	for (int i = 0; i < base_obj->item_count; i++)
	{
		printf("Item %d name: %s\n", (i + 1), base_obj->items[i]->name);
	}

	return 0;
}
Exemple #3
0
int		read_file(const t_hs filename, t_glist_hs *lines)
{
  char		*data;
  int		fd;
  ssize_t	file_length;
  t_hs		ths;
  t_glist_hs	new_lines;

  if ((file_length = get_file_length(filename)) == -1)
    return (-1);
  if ((fd = open_file(filename, O_RDONLY)) == -1)
    return (-1);
  data = egc_malloc_atomic(file_length + 1);
  if (read(fd, data, file_length) == -1)
    {
      close(fd);
      return (-1);
    }
  close(fd);
  ths = hs(data);
  if ((int)hs_length(ths) != file_length)
    return (-1);
  new_lines = hs_split(ths, hs("\n"));
  glist_hs_append_all(lines, &new_lines);
  return (0);
}
struct dsc *loader_arch_load_dsc(const char *name)
{
	char *loadaddr;
	struct dsc_hdr *dschdr;
	int length;

	/* get length of file */
	length = get_file_length(name);
	if (length==0)
		return NULL;

	/* allocate memory */
	loadaddr = malloc(length);
	if (loadaddr==NULL)
		return NULL;

	/* load the file */
	load_file(name, loadaddr);
	
	dschdr = (struct dsc_hdr *)loadaddr;
	/* relocate it */
	relocate(dschdr->relocatedata, loadaddr);

	return &dschdr->dscdata;
}
unsigned char loader_arch_load(const char *name, char *arg)
{
	char *loadaddr;	
	struct prg_hdr *prghdr;
	int length;

	/* get length of file */
	length = get_file_length(name);
	if (length==0)
		return LOADER_ERR_OPEN;

	/* allocate memory */
	loadaddr = malloc(length);
	if (loadaddr==NULL)
		return LOADER_ERR_MEM;
	
	/* load the file */
	load_file(name,loadaddr);

	prghdr = (struct prg_hdr *)loadaddr;

	/* relocate it */
	relocate(prghdr->relocatedata,loadaddr);

	((void (*)(char *))prghdr->initfunc)(arg);

	return LOADER_OK;
}
Exemple #6
0
int update_user_name(char* user_name)
{
	strncpy(g_user_name, user_name, USER_NAME_LENGTH - 1);
	
	strncpy(g_statistics_header.user_name, user_name, USER_NAME_LENGTH - 1);
	g_statistics_header_offset = get_file_length(g_statistics_path);
	if (g_statistics_header_offset < 0)
		return STATUS_FAILED;
	if (append_to_file(g_statistics_path, &g_statistics_header, sizeof(statistics_header_t)) != STATUS_OK)
		return STATUS_FAILED;

	strncpy(g_history_values_header.user_name, user_name, USER_NAME_LENGTH - 1);
	g_history_values_header_offset = get_file_length(g_history_path);
	if (g_history_values_header_offset < 0)
		return STATUS_FAILED;
	if (append_to_file(g_history_path, &g_history_values_header, sizeof(history_values_header_t)) != STATUS_OK)
		return STATUS_FAILED;
		
	return STATUS_OK;
}
Exemple #7
0
int update_data_group(int data_group)
{
	g_data_group = data_group;
	
	g_statistics_header.data_group =  data_group;
	g_statistics_header_offset = get_file_length(g_statistics_path);
	if (g_statistics_header_offset < 0)
		return STATUS_FAILED;
	if (append_to_file(g_statistics_path, &g_statistics_header, sizeof(statistics_header_t)) != STATUS_OK)
		return STATUS_FAILED;

	g_history_values_header.data_group =  data_group;
	g_history_values_header_offset = get_file_length(g_history_path);
	if (g_history_values_header_offset < 0)
		return STATUS_FAILED;
	if (append_to_file(g_history_path, &g_history_values_header, sizeof(history_values_header_t)) != STATUS_OK)
		return STATUS_FAILED;
		
	return STATUS_OK;
}
Exemple #8
0
// Initializes values for a file
// @param file a pointer to the file variable
// @param client a pointer to the client variable
// @param p a linked list node with the file
static void initialize_file(file_info *file, client_info *client, csv_record *p) {
    
    file->path = build_path(p, client->dir);
    file->file_length = get_file_length(file->path);
    file->transfer_threshold = file->file_length * TRANSFER_THRESHOLD_PERCENT;
    file->file_count = 0;
    file->packets_in_buffer = 0;
    file->bytes_sent = 0;
    file->file_buffer_size = 0;
    
} //end initialize_file
Exemple #9
0
uint32_t load_data(uint8_t **loadMe, char *name)
{
        uint32_t length;
        FILE *temp = fopen(name, "rb");

        length = get_file_length(temp);

        *loadMe = (uint8_t *) malloc(sizeof(uint8_t) * (length + 1));
        fread(*loadMe, sizeof(uint8_t), length, temp);
        fclose(temp);
        return length;
}
Exemple #10
0
/* Returns the content of a given file */
char* read_from_file(const char* filename) {
	FILE *ifp;
	unsigned long size;
	char* buffer;
	ifp = fopen(filename, "r");
	if (!ifp) {
		printf("ERROR: FILE equals NULL\n");
		exit(1);
	}
	size = get_file_length(ifp);
	buffer = allocate_strlen(size);
	fread(buffer, 1, size, ifp);
	fclose(ifp);
	return buffer;
}
void CompressFile( FILE *input, BIT_FILE *output, int argc, char *argv[] ){
/*FILE *input;
BIT_FILE *output;
int argc;
char *argv[];
{
*/
    int compress[ 256 ];
    int steps;
    int bits;
    int value;
    int i;
    int j;
    int c;
/*
* The first section of code determines the number of bits to use
* for output codes, then writes it to the compressed file. The
* length of the input file is also written out.
*/
    if ( argc-- > 0 )
        bits = atoi( *argv );
    else
        bits = 4;
    printf( "Compressing using %d bits per sample...\n", bits );
    steps = ( 1 << ( bits - 1 ) );
    OutputBits( output, (unsigned long) bits, 8 );
    OutputBits( output, (unsigned long) get_file_length( input), 32 );
/*
* The compression table is built here. Each input code maps to
* a single output code. There are "steps" codes to be used in
* the output space. This builds an exponential output function.
*/
    for ( i = steps ; i > 0; i-- ) {
        value = 128.0 * ( pow( 2.0, (double) i / steps ) - 1.0 ) + 0.5;
        for ( j = value ; j > 0 ; j-- ) {
            compress[ j + 127 ] = i + steps - 1;
            compress[ 128 - j ] = steps - i;
        }
    }
/*
* The actual compression takes place here.
*/
    while ( ( c = getc( input ) ) != EOF )
        OutputBits( output, (unsigned long) compress[ c ], bits ); }
Exemple #12
0
static int check_version()
{
    unsigned long handle;
    UINT8 back_saved;
    UINT8* ftpurl;
    UINT32 bufflen = 521;
    CHUNK_HEADER* sw_version;
    CHUNK_HEADER* bootload_version;
    downloadbuff = MALLOC(bufflen);
    ftpurl       = MALLOC(bufflen);
    if( NULL == downloadbuff || NULL == ftpurl)
    {
        libc_printf("Get memorey for download file faild!\n");
        return -1;
    }
    get_updata_url(ftpurl);
    strcat(ftpurl, DEFULT_CONFIG_FILE);
    
    //libc_printf("The servicer addr is %s\n",ftpurl);

    //get system software version
    get_system_version_info();
    if(NULL == (sw_version=get_sw_version()))
        return -1;
    if(NULL == (bootload_version = get_bootloader_version()))
        return -1;
    
     handle = libnet_download_to_mem_thread_save(ftpurl, downloadbuff, bufflen, 0, rstcb);
     osal_task_sleep(20000);
     
    // LIBNET_DEBUG("outfile size is %ld\n",(get_file_length(handle)));
     //libc_printf("system sw version is %s\n",sw_version->version);
     //LIBNET_DEBUG("netservicer sw version is %s\n",downloadbuff);
     
     if(1 == check_netupgrade_configfile(downloadbuff,get_file_length(handle)
                                            ,bootload_version,sw_version))
     {
        free(downloadbuff);
        return 1;//have new version
     }
     free(downloadbuff);
     return 0;
}
Exemple #13
0
/** Allocate a buffer for the contents of a file and read the file into it. */
static inline byte* file_to_buffer(wchar_t* sPath, size_t* size)
{
	FILE* fp;
	byte* buffer = NULL;
	fp = _wfopen((const wchar_t*)sPath, L"rb");
	if (fp == NULL) {
		fatal(1, L"Could not read file: %s", sPath);
	}
	
	*size = get_file_length(fp);
	if(*size == -1) {
		fatal(1, L"Could not get size of file: %s", sPath);
	}
	
	if(!(buffer = (byte*)xalloc(*size, 1))) {
		fatal(1, L"Could not allocate %d bytes of memory for the contents of file: %s", *size, sPath);
	}
	ZeroMemory(buffer, *size);
	fread(buffer, 1, *size, fp);
	fclose(fp);
	return buffer;
}
Exemple #14
0
hw_string* create_response_file_header_buffer(hw_http_response* response, const char *file)
{
    http_response* resp = (http_response*)response;
    hw_string* response_string = malloc(sizeof(hw_string));
    hw_string* cached_entry = get_cached_request(resp->status_code.value);
    hw_string content_length;
	int file_length = get_file_length(file);

    int i = 0;
    response_string->value = calloc(1024 * 1024, 1);
    response_string->length = 0;
    append_string(response_string, cached_entry);
    
    for (i=0; i< resp->number_of_headers; i++)
    {
        http_header header = resp->headers[i];
        append_string(response_string, &header.name);
        APPENDSTRING(response_string, ": ");
        append_string(response_string, &header.value);
        APPENDSTRING(response_string, CRLF);
    }
    
    /* Add the body */
    APPENDSTRING(response_string, "Content-Length: ");
    
    //string_from_int(&content_length, file_length, 10);
	string_from_int_10base(&content_length, file_length);
    append_string(response_string, &content_length);
    APPENDSTRING(response_string, CRLF CRLF);
    
    //if (resp->body.length > 0)
    //{
    //    append_string(response_string, &resp->body);
    //}
    //APPENDSTRING(response_string, CRLF);
    return response_string;
}
Exemple #15
0
//at the moment only set up for log-binned angular weights.
angwgt readangwgt(char *filename1pw) {

  angwgt awgt;

  FILE *ifpw;
  int headertot, linestot,i;
  if(!(ifpw = open_file_read(filename1pw))) {
    exit(1);
    //return NULL;
    }
  get_file_length(ifpw,&headertot,&linestot);
  assert(headertot==0);

  awgt.ntheta = linestot;
  awgt.thetacen = (real *) malloc(sizeof(real)*awgt.ntheta);
  awgt.thetamin = (real *) malloc(sizeof(real)*awgt.ntheta);
  awgt.thetamax = (real *) malloc(sizeof(real)*awgt.ntheta);
  awgt.angweight = (real *) malloc(sizeof(real)*awgt.ntheta);

  for(i=0;i<awgt.ntheta;i++) {
    #ifdef REALFLOAT
    fscanf(ifpw,"%e %e %e %e\n",&(awgt.thetacen[i]), &(awgt.thetamin[i]), &(awgt.thetamax[i]), &(awgt.angweight[i]));
    #else
    fscanf(ifpw,"%le %le %le %le\n",&(awgt.thetacen[i]), &(awgt.thetamin[i]), &(awgt.thetamax[i]), &(awgt.angweight[i]));
    #endif
    if(i==0) {
      awgt.dlog10theta = log10(awgt.thetamax[i]/awgt.thetamin[i]);
      }
    else {
      assert(fabs(log10(awgt.thetamax[i]/awgt.thetamin[i]) - awgt.dlog10theta) < 2.0e-6);
      assert(fabs(log10(awgt.thetacen[i]/awgt.thetacen[i-1]) - awgt.dlog10theta) < 2.0e-6);
      }
    }
  fclose(ifpw);
  awgt.log10thetamin = log10(awgt.thetamin[0]);
  return awgt;
  }
Exemple #16
0
/*	Pass the path to the zipfile and the name of the file within the zipfile.
	buf will be set to point to the uncompressed image of that zipped file.
	length will be set to the length of the uncompressed data. */
int /* error */ load_zipped_file (const char *zipfile, const char *filename,
	unsigned char **buf, int *length)
{
	FILE 				*fp = NULL;
	t_end_of_cent_dir	ecd;
	t_central_dir_ent	cd;
	t_local_file_hdr	lfh;
	unsigned char		*inbuf = 0, *outbuf = 0;
	char				filenameUpper[32], *p;
	int 				err;

	/* open zipfile for binary read */
	if ((fp = fopen (zipfile,"rb")) != NULL)
	{
		/* determine length of zip file */
		err = get_file_length (fp, &gZipLen);
		if (err!=0)
		{
			ERRORMSG ("Error in zipfile: get_file_length() failed\n");
			goto bail;
		}

		/* read end-of-central-directory */
		err = read_end_of_cent_dir (fp, &ecd);
		if (err!=0)
		{
			ERRORMSG ("Error reading 'end of central directory'\n");
			goto bail;
		}

		/* verify that we can work with this zipfile (no disk spanning allowed) */
		if ((ecd.number_of_this_disk != ecd.number_of_disk_start_cent_dir) ||
			(ecd.total_entries_cent_dir_this_disk != ecd.total_entries_cent_dir) ||
			(ecd.total_entries_cent_dir < 1))
		{
			err = -1;
			ERRORMSG ("Unsupported zipfile: zipfile cannot span disks\n");
			goto bail;
		}

		/* find matching file in central directory (force upper case) */
		for (p=filenameUpper; (*p++ = toupper(*filename++)) != '\0';){};

		err = find_matching_cd_entry (fp, filenameUpper, &ecd, &cd);
		if (err!=0)
		{
			ERRORMSG("Could not find %s in zipfile %s\n", filenameUpper, zipfile);
			goto bail;
		}

		/* read in local file header */
		err = read_local_file_header (fp, &cd, &lfh);
		if (err!=0)
		{
			ERRORMSG ("Error reading 'local file header'\n");
			goto bail;
		}

		/* extract file based on compression method */
		if (lfh.compression_method == 0x0000)
		{
			/* file is not compressed, simply stored -- copy directly to output buffer */
			err = create_input_buffer (fp, &cd, &lfh, &outbuf);
			if (err!=0)
				ERRORMSG ("Couldn't extract uncompressed file\n");
		}
		else if (lfh.compression_method == 0x0008)
		{
			/* file is compressed using "Deflate" method */

			/* create input and output buffers */
			err = create_input_buffer (fp, &cd, &lfh, &inbuf);
			if (err==0)
			{
				g_nextbyte = inbuf;
				outbuf = malloc (lfh.uncompressed_size);
				if (outbuf!=0)
					g_outbuf = outbuf;
				else
				{
					ERRORMSG ("Couldn't allocate %d bytes for output buffer\n",
						lfh.uncompressed_size);
					err = -1;
				}
			}
			else
			{
				ERRORMSG ("Could not create input buffer\n");
			}

			/* create sliding window for inflate() */
			if (err==0)
			{
				slide = malloc (0x8000);
				if (slide==0)
				{
					ERRORMSG ("Could not create 32K sliding window\n");
					err = -1;
				}
			}

			/* inflate the compressed file (now in memory) */
			if (err==0)
			{
				err = zip_inflate ();
				if (err!=0)
				{
					ERRORMSG ("Error inflating compressed file: %d", err);
				}
			}
		}

		/* return pointer to uncompressed data */
		if (err==0)
		{
			*buf = outbuf;
			*length = lfh.uncompressed_size;
			outbuf = 0;		/* prevent data from being freed() */
		}
	}
	else
	{
		ERRORMSG ("Could not open zipfile %s\n", zipfile);
		err = -1;
	}

bail:
	if (fp) fclose (fp);
	if (inbuf) free (inbuf);
	if (outbuf) free (outbuf);
	if (slide)
	{
		free (slide);
		slide = 0;
	}
	return err;
}
Exemple #17
0
void check_file_length(uint16_t cluster, uint8_t *image_buf, struct bpb33* bpb)
{
    struct direntry *dirent;
    int d, i;
    dirent = (struct direntry*) cluster_to_addr(cluster, image_buf, bpb);
    int clust_size = bpb->bpbBytesPerSec * bpb->bpbSecPerClust;

    while (1) {
        for (d = 0; d < clust_size; d += sizeof(struct direntry)) {
            char name[9];
            char extension[4];
            uint32_t size;
            uint16_t file_cluster;
            name[8] = ' ';
            extension[3] = ' ';
            memcpy(name, &(dirent->deName[0]), 8);
            memcpy(extension, dirent->deExtension, 3);

            if (name[0] == SLOT_EMPTY)
                return;

            /* skip over deleted entries */
            if (((uint8_t)name[0]) == SLOT_DELETED)
                continue;

            /* names are space padded - remove the spaces */
            for (i = 8; i > 0; i--) {
                if (name[i] == ' ')
                    name[i] = '\0';
                else
                    break;
            }

            /* remove the spaces from extensions */
            for (i = 3; i > 0; i--) {
                if (extension[i] == ' ')
                    extension[i] = '\0';
                else
                    break;
            }

            /* don't print "." or ".." directories */
            if (strcmp(name, ".") == 0) {
                dirent++;
                continue;
            }
            if (strcmp(name, "..") == 0) {
                dirent++;
                continue;
            }

            if ((dirent->deAttributes & ATTR_VOLUME) != 0) {
                continue;
            } else if ((dirent->deAttributes & ATTR_DIRECTORY) != 0) {
                file_cluster = getushort(dirent->deStartCluster);
                check_file_length(file_cluster, image_buf, bpb);
            } else {
                size = getulong(dirent->deFileSize);
                file_cluster = getushort(dirent->deStartCluster);
                uint16_t fat_size_clusters = get_file_length(file_cluster, image_buf, bpb);

                uint32_t size_clusters = (size + (clust_size - 1)) / clust_size;
                uint32_t fat_size = fat_size_clusters * clust_size;
                if (size_clusters != fat_size_clusters) {
                    printf("%s.%s %u %u\n", name, extension, size, fat_size);

                    uint16_t begin_cluster = file_cluster + size_clusters - 1;
                    uint16_t end_cluster = file_cluster + fat_size_clusters;
                    free_clusters(begin_cluster, end_cluster, image_buf, bpb);
                }
            }

            dirent++;
        }

        /* We've reached the end of the cluster for this directory. Where's the next cluster? */
        if (cluster == 0) {
            // root dir is special
            dirent++;
        } else {
            cluster = get_fat_entry(cluster, image_buf, bpb);
            dirent = (struct direntry*) cluster_to_addr(cluster, image_buf, bpb);
        }
    }
}
Exemple #18
0
int main(int argc, char* argv[])
{
	char* output;
	char* input;
	FILE* fwork;
	size_t output_length;
	size_t input_length;
	size_t execlen = 0;
	int result = 0;
	char* cflags = NULL;
	char* exec_cmd = NULL;
	char rc_cmd[128] = "\0";
	bool no_compression = false;
	bool exec_temp = false;
	int i = 0;
	
	if(_access("obj", 00) != 0) {
		if(_mkdir("obj") != 0) {
			fatal("Could not create intermediate folder.");
		}
	}
	
	for(i = 1; i < argc; i++) {
		if((_stricmp(argv[i], "--no-compression") == 0) || (_stricmp(argv[i], "-n") == 0)){
			no_compression = true;
		} else if((_stricmp(argv[i], "--no-local") == 0) || (_stricmp(argv[i], "-l") == 0)) {
			exec_temp = true;
		} else if((_stricmp(argv[i], "--help") == 0)||(_stricmp(argv[i], "-h") == 0)) {
			out("Usage: %s [--no-compression|-n] [--no-local|-l] [-h|--help]\n", argv[0]);
			exit(0);
		}
	}
	
	if(_access(STUB_OUT, 00) == 0) _unlink(STUB_OUT);
	
	if((fwork = fopen(STUB_IN, "rb")) == NULL) {
		fatal("Failed to open input file.");
	}
	
	if((input_length = get_file_length(fwork)) == -1) {
		fatal("Could not get filesize of " STUB_IN ".");
	}
	
	input = (char*)malloc((input_length+1)*sizeof(char));
	memset((void*)input, 0, (input_length+1)*sizeof(char));
	if(input == NULL) {
		fatal("Could not allocate buffer for uncompressed data.");
	}
	
	if(!fread((void*)input, sizeof(char), input_length, fwork)) {
		free(input);
		fatal("Failed to read input file.");
	}
	
	fclose(fwork);
	output_length = snappy_max_compressed_length(input_length);
	output = (char*)malloc(output_length);
	if(output == NULL) {
		free(input);
		fatal("Could not allocate buffer for compressed data.");
	}
	
	if (snappy_compress(input, input_length, output, &output_length) == SNAPPY_OK) {
		free(input);
		outl("Compressed data.");
		if((fwork = fopen(STUB_OUT, "wb")) == NULL) {
			fatal("Failed to open output file.");
		}
		if(!fwrite((const void*)output, sizeof(char), output_length / sizeof(char), fwork)) {
			fatal("Failed to write to output file.");
		}
		fclose(fwork);
	} else {
		free(input);
		free(output);
		fatal("Failed to compress stub file.");
	}
	free(output);

	if(_access(STUB_OBJ, 00) == 0) _unlink(STUB_OBJ);
	if(_access(EDIT_OBJ, 00) == 0) _unlink(EDIT_OBJ);
	if(_access(STUB_RES, 00) == 0) _unlink(STUB_RES);
	if(_access(EDIT_RES, 00) == 0) _unlink(EDIT_RES);
	
	// Compile stub.rc
	outl("\nCompiling resource file.");
	strcpy(rc_cmd, RC_CMD);
	if(!exec_temp) strcat(rc_cmd, RC_EXEC_LOCAL);
	if(no_compression) strcat(rc_cmd, RC_NO_COMPRESS);
	strcat(rc_cmd, STUB_RC);
	
	if((result = system(rc_cmd)) != EXIT_SUCCESS) {
		fatal("Failed to compile " STUB_RC "\n\nrc.exe returned code %d", result);
	}
	
	
	// cl.exe -Foobj\stub.obj src\stub.c obj\stub.res -link -LTCG -OPT:REF -OPT:ICF\0
	execlen = strlen(CL_CMD CL_END);
	if((cflags = getenv("CFLAGS")) != NULL) {
		execlen += lstrlenA(cflags) + 1;
	}
	
	if(!exec_temp) execlen += 15;
	if(no_compression) execlen += 19;
	
	exec_cmd = (char*)malloc(sizeof(char) * execlen);
	if(exec_cmd == NULL) {
		fatal("Could not allocate buffer for command-line.");
	}
	
	memset((void*)exec_cmd, 0, sizeof(char) * execlen);
	strcpy(exec_cmd, CL_CMD);
	if(cflags != NULL) {
		strcat(exec_cmd, cflags);
		strcat(exec_cmd, " ");
	}
	if(!exec_temp) {
		out("Enabling local-exec.\n");
		strcat(exec_cmd, CL_EXEC_LOCAL);
	}
	if(no_compression) {
		out("Enabling resource compression.\n");
		strcat(exec_cmd, CL_NO_COMPRESS);
	}
	
	strcat(exec_cmd, CL_END);

	outl("Compiling source files.\n");
	if((result = system(exec_cmd)) != EXIT_SUCCESS) {
		free(exec_cmd);
		fatal("Failed to compile stub.c\n\ncl.exe returned code %d", result);
	}
	free(exec_cmd);
	
	// Compile bat2exe.rc
	strcpy(rc_cmd, "");
	outl("\nCompiling resource file.");
	strcpy(rc_cmd, RC_EDIT_CMD);
	if(!exec_temp) strcat(rc_cmd, RC_EXEC_LOCAL);
	if(no_compression) strcat(rc_cmd, RC_NO_COMPRESS);
	strcat(rc_cmd, EDIT_RC);
	
	if((result = system(rc_cmd)) != EXIT_SUCCESS) {
		fatal("Failed to compile " EDIT_RC "\n\nrc.exe returned code %d", result);
	}
	
	// cl.exe %CFLAGS% -Foobj\bat2exe.obj src\bat2exe.c obj\bat2exe.res -link -LTCG -OPT:REF -OPT:ICF\0
	execlen = strlen(CL_EDIT_CMD CL_EDIT_END);
	if((cflags = getenv("CFLAGS")) != NULL) {
		execlen += lstrlenA(cflags) + 1;
	}
	
	if(!exec_temp) execlen += 15;
	if(no_compression) execlen += 19;
	
	exec_cmd = (char*)malloc(sizeof(char) * execlen);
	if(exec_cmd == NULL) {
		fatal("Could not allocate buffer for command-line.");
	}
	memset((void*)exec_cmd, 0, sizeof(char) * execlen);
	strcpy(exec_cmd, CL_EDIT_CMD);
	if(cflags != NULL) {
		strcat(exec_cmd, cflags);
		strcat(exec_cmd, " ");
	}
	if(!exec_temp) {
		out("Enabling local-exec.\n");
		strcat(exec_cmd, CL_EXEC_LOCAL);
	}
	if(no_compression) {
		out("Enabling resource compression.\n");
		strcat(exec_cmd, CL_NO_COMPRESS);
	}
	strcat(exec_cmd, CL_EDIT_END);
	if((result = system(exec_cmd)) != EXIT_SUCCESS) {
		free(exec_cmd);
		fatal("Failed to compile batcompile.c\n\ncl.exe returned code %d", result);
	}
	free(exec_cmd);
	return 0;
}
Exemple #19
0
int main(int argc, char *argv[])
{
    int clientsockfd, portno, n, optval, plaintextfd;
    struct sockaddr_in serv_addr;
    struct hostent *server;
	 FILE *fp;
	 const char hostname[] = "localhost";
	 
    char buffer[100000];
    bzero(buffer,100000);
    if (argc != 4) {
       fprintf(stderr,"usage %s <inputfile> <key> <port>\n", argv[0]);
       exit(1);
    }
    portno = atoi(argv[3]);
    clientsockfd = socket(AF_INET, SOCK_STREAM, 0); //create socket
    if (clientsockfd < 0) {
        perror("ERROR opening socket");
        exit(1);
    }
    server = gethostbyname(hostname); //look up server
    if (server == NULL) {
        perror("ERROR, no such host");
        exit(1);
    }
    optval = 1;
    setsockopt(clientsockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int)); //allow reuse of port
    
    bzero((char *) &serv_addr, sizeof(serv_addr)); //clear address
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);

    if (connect(clientsockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ //connect to server socket
        perror("ERROR connecting");
        exit(1);
    }
    
    char auth[]="dec_bs";
    write(clientsockfd, auth, sizeof(auth));
    read(clientsockfd, buffer, sizeof(buffer));
    if (strcmp(buffer, "dec_d_bs") != 0) {
        fprintf(stderr, "unable to contact otp_enc_d on given port\n");
        exit(2);
    }
    
    //check that key is at least as long as message
    long infilelength = get_file_length(argv[1]);
    long keylength = get_file_length(argv[2]);    
    if (infilelength > keylength){
    	 fprintf(stderr, "key is too short\n");
    	 exit(1); 
    }
    
	 //send plaintextfile
    sendFile(argv[1], clientsockfd, infilelength);
    //send key
	 sendFile(argv[2], clientsockfd, keylength);

    n = read(clientsockfd,buffer,sizeof(buffer));
    if (n < 0){
         perror("ERROR reading from socket");
         exit(1);
    }
    printf("%s\n",buffer);
    close(clientsockfd);
    return 0;
}
Exemple #20
0
int main(int argc, char** argv)
{
    uint8_t *image_buf;
    int fd;
    struct bpb33* bpb;
    if (argc != 2) {
        usage();
    }

    image_buf = mmap_file(argv[1], &fd);
    bpb = check_bootsector(image_buf);

    int total_clusters = bpb->bpbSectors / bpb->bpbSecPerClust;
    int clust_size = bpb->bpbSecPerClust * bpb->bpbBytesPerSec;
    int used_clusters[total_clusters];
    check_lost_files(used_clusters, 0, image_buf, bpb);

    int i;
    int shownPrefix = 0;
    for (i = 2; i < total_clusters; i++) {
        if (used_clusters[i] == 0 && get_fat_entry(i, image_buf, bpb) != CLUST_FREE) {
            if (!shownPrefix) {
                printf("Unreferenced:");
                shownPrefix = 1;
            }
            printf(" %i", i);
        }

        if (i == total_clusters - 1 && shownPrefix) {
            printf("\n");
        }
    }

    int foundCount = 1;
    shownPrefix = 0;
    for (i = 2; i < total_clusters; i++) {
        if (used_clusters[i] == 0 && get_fat_entry(i, image_buf, bpb) != CLUST_FREE) {
            if (!shownPrefix) {
                printf("Lost File: ");
            }

            uint16_t size = get_file_length(i, image_buf, bpb);
            printf("%i %i\n", i, size);

            struct direntry *dirent = (struct direntry*) cluster_to_addr(0, image_buf, bpb);
            uint32_t size_bytes = size * clust_size;

            const char base[] = "found";
            const char extension[] = ".dat";
            char filename [13];
            sprintf(filename, "%s%i%s", base, foundCount++, extension);

            create_dirent(dirent, filename, i, size_bytes, image_buf, bpb);

            check_lost_files(used_clusters, 0, image_buf, bpb);
        }

        if (i == total_clusters - 1 && shownPrefix) {
            printf("\n");
        }
    }

    check_file_length(0, image_buf, bpb);

    close(fd);
    exit(0);
}
Exemple #21
0
static int tee_enc_fs_open(const char *file, int flags, ...)
{
	int fd, open_flags, res = -1;
	size_t encrypted_data_len, file_len;
	size_t file_header_len = tee_enc_fs_get_file_header_size();
	void *encrypted_data;
	struct tee_fs_fd *fdp;
	struct tee_enc_fs_private *priv;
	TEE_Result ret;

	DMSG("open, file=%s, flags=%x", file, flags);
	open_flags = TEE_FS_O_RDWR;
	if (flags & TEE_FS_O_CREATE)
		open_flags |= TEE_FS_O_CREATE;

	fd = tee_fs_common_open(file, open_flags);
	if (fd < 0)
		goto exit;

	fdp = tee_fs_fd_lookup(fd);
	if (!fdp)
		goto exit;

	priv = (struct tee_enc_fs_private *)
		malloc(sizeof(struct tee_enc_fs_private));
	if (!priv)
		goto exit;
	tee_fs_fd_priv(fdp) = priv;

	if (fdp->is_new_file) {
		priv->len = 0;
		priv->pos = 0;
		priv->data = NULL;
		return fd;
	}

	res = get_file_length(fdp, &encrypted_data_len);
	if (res < 0) {
		res = -1;
		goto exit_close_file;
	}

	/*
	 * The file stored on normal world filesystem is encrypted data
	 * with an additional file header
	 */
	TEE_ASSERT(encrypted_data_len > file_header_len);
	file_len = encrypted_data_len - file_header_len;

	/* allocate buffer to hold encrypted file context + header */
	encrypted_data = malloc(encrypted_data_len);
	if (!encrypted_data) {
		res = -1;
		goto exit_close_file;
	}

	/*
	 * init internal status, also allocate buffer for
	 * decrypted file content
	 */
	priv->pos = 0;
	priv->len = file_len;
	priv->data = malloc(file_len);
	if (!priv->data) {
		res = -1;
		goto exit_free_encrypted_data;
	}

	/* read encrypted file content */
	res = tee_fs_common_read(fdp, encrypted_data, encrypted_data_len);
	if (res != (int)encrypted_data_len) {
		res = -1;
		goto exit_free_decrypted_data;
	}
	DMSG("%d bytes read", res);

	/* decrypt and authenticate the file content */
	ret = tee_enc_fs_file_decryption(encrypted_data, encrypted_data_len,
			priv->data, &file_len);
	if (ret != TEE_SUCCESS) {
		res = -1;
		goto exit_free_decrypted_data;
	}
	res = fd;

exit_free_decrypted_data:
	if (res < 0)
		free(priv->data);
exit_free_encrypted_data:
	free(encrypted_data);
exit_close_file:
	if (res < 0 && fd >= 0)
		tee_fs_common_close(fdp);
exit:
	return res;
}
Exemple #22
0
int main(void){
	int web_server_welcome_socket = open_welcome_socket_TCP(2080, false);

	while(1) {
		int web_server_connected_socket = accept_connection_from_client_TCP(web_server_welcome_socket);


		if (web_server_connected_socket >= 0){
			int len = get_file_length() + 1350;
			char content_length[100];

			sprintf(content_length, "Content-Length: %d", len);

			send_string_line_TCP(web_server_connected_socket, "HTTP/1.1 200 OK");
			send_string_line_TCP(web_server_connected_socket, "Connection: close");

			send_string_line_TCP(web_server_connected_socket, "Content-Type: application/vnd.google-earth.kml+xml");
			send_string_line_TCP(web_server_connected_socket, content_length); 
			/*send_string_line_TCP(web_server_connected_socket, "Content-Length: 1437");*/
			send_string_line_TCP(web_server_connected_socket, "Server: Indy/DevSnapshot");
			send_string_line_TCP(web_server_connected_socket, "");

			kml_header(web_server_connected_socket);
			/*send_string_line_TCP(web_server_connected_socket, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			send_string_line_TCP(web_server_connected_socket, "<kml xmlns=\"http://earth.google.com/kml/2.0\">");
			*/
			send_string_line_TCP(web_server_connected_socket, "  <Folder>");
			send_string_line_TCP(web_server_connected_socket, "  <Placemark>");
			send_string_line_TCP(web_server_connected_socket, "    <name>Aircraft</name>");
			send_string_line_TCP(web_server_connected_socket, "    <description>Marks current aircraft position (MyFsGoogleEarth)</description>");
			send_string_line_TCP(web_server_connected_socket, "    <visibility>1</visibility>");
			send_string_line_TCP(web_server_connected_socket, "    <styleUrl>root://styles#default+icon=0x307</styleUrl>");
			send_string_line_TCP(web_server_connected_socket, "    <Style>");
			send_string_line_TCP(web_server_connected_socket, "<labelColor>ff00ffff</labelColor>");
			send_string_line_TCP(web_server_connected_socket, "      <IconStyle>");
			send_string_line_TCP(web_server_connected_socket, "        <Icon>");
			send_string_line_TCP(web_server_connected_socket, "          <href>root://icons/palette-2.png</href>");
			send_string_line_TCP(web_server_connected_socket, "          <w>32</w>");
			send_string_line_TCP(web_server_connected_socket, "          <h>32</h>");
			send_string_line_TCP(web_server_connected_socket, "        </Icon>");
			send_string_line_TCP(web_server_connected_socket, "      </IconStyle>");
			send_string_line_TCP(web_server_connected_socket, "    </Style>");
			send_string_line_TCP(web_server_connected_socket, "    <Point>");
			send_string_line_TCP(web_server_connected_socket, "      <extrude>1</extrude> <altitudeMode>absolute</altitudeMode>");
			send_string_line_TCP(web_server_connected_socket, "      <coordinates>0.00000000,0.00000000,0.00000000</coordinates>");
			send_string_line_TCP(web_server_connected_socket, "    </Point>");
			send_string_line_TCP(web_server_connected_socket, "  </Placemark>");
			send_string_line_TCP(web_server_connected_socket, "  <Placemark>");
			send_string_line_TCP(web_server_connected_socket, "    <name>Aircraft (+1 min.)</name>");
			send_string_line_TCP(web_server_connected_socket, "    <description>Marks estimated aircraft position in 1 minute (MyFsGoogleEarth)</description>");
			send_string_line_TCP(web_server_connected_socket, "    <visibility>1</visibility>");
			send_string_line_TCP(web_server_connected_socket, "    <styleUrl>root://styles#default+icon=0x307</styleUrl>");
			send_string_line_TCP(web_server_connected_socket, "    <Style>");
			send_string_line_TCP(web_server_connected_socket, "<labelScale>0.75</labelScale><labelColor>ff00ffff</labelColor>");
			send_string_line_TCP(web_server_connected_socket, "      <IconStyle>");
			send_string_line_TCP(web_server_connected_socket, "        <Icon>");
			send_string_line_TCP(web_server_connected_socket, "          <href>root://icons/palette-2.png</href>");
			send_string_line_TCP(web_server_connected_socket, "          <w>32</w>");
			send_string_line_TCP(web_server_connected_socket, "          <h>32</h>");
			send_string_line_TCP(web_server_connected_socket, "        </Icon>");
			send_string_line_TCP(web_server_connected_socket, "        <scale>0.6</scale>");
			send_string_line_TCP(web_server_connected_socket, "      </IconStyle>");
			send_string_line_TCP(web_server_connected_socket, "    </Style>");
			send_string_line_TCP(web_server_connected_socket, "    <Point>");
			send_string_line_TCP(web_server_connected_socket, "      <extrude>1</extrude> <altitudeMode>absolute</altitudeMode>");
			send_string_line_TCP(web_server_connected_socket, "      <coordinates>0.00000000,0.00000000,0.00000000</coordinates>");
			send_string_line_TCP(web_server_connected_socket, "    </Point>");
			send_string_line_TCP(web_server_connected_socket, "  </Placemark>");
			send_string_line_TCP(web_server_connected_socket, "  </Folder>");
			send_string_line_TCP(web_server_connected_socket, "</kml>");

		}
	}
}
Exemple #23
0
void *recv_thrd(void *arg)   /* server for client */
{
    int sock_fd, index;
    int rec_bytes, left;
    Client *cli_ptr = NULL;
    char *ptr = NULL;
    char filename[128], res[128];
    int total_bytes;
    FILE *fp = NULL;

    cli_ptr = (Client *)arg;
    sock_fd = cli_ptr->con_fd;
    printf("thread nick: %s\nthread fd: %d\n", cli_ptr->nick, cli_ptr->con_fd);

    while ((rec_bytes = recv(sock_fd, buf, sizeof(buf), 0)) > 0)
    {
        ptr = strstr(buf, "\r\n\r\n");
        index = ptr - buf;
        strncpy(res, buf, index);
        res[index] = '\0';
        get_filename(res, filename);
        total_bytes = get_file_length(res);
        printf("please enter the folder to save \"%s\" (eg:\"./to/\"):", filename);
        //scanf("%s", res);
printf("服务器默认存放在: \"./to/\" 下\r\n");
        strcpy(res, "./to/");
        index = strlen(res);
        if (res[index - 1] != '/')
        {
            strcat(res, "/");
        }
        else
        {
            strcat(res, filename);
        }

        if ((fp = fopen(filename, "r")) != NULL)
        {
            puts("error, file exist!");
            fclose(fp);
            return NULL;
        }

        printf("filename = %s\r\n", filename);
        fp = fopen(filename, "a+");

        left = rec_bytes - (ptr - buf + 4);
        fwrite(ptr + 4, left, 1, fp);
        fflush(fp);
        fclose(fp);
        total_bytes -= left;

        /* initial progress bar */
        init_progress(&bar, total_bytes + left);
        update_progress(&bar, left);
        display_image(&bar);

        save_file(sock_fd, filename, total_bytes);
        printf("file %s saved, bytes = %d\r\n", filename, total_bytes + left);
    }

    close(sock_fd);
    remove_client(sock_fd);
    printf("a client(%d) quit!\n", cli_ptr->con_fd);

    pthread_exit(NULL);
}
Exemple #24
0
int 
main(int argc, char **argv)
{
    XPTArena *arena;
    XPTState *state;
    XPTCursor curs, *cursor = &curs;
    XPTHeader *header;
    XPTInterfaceDirectoryEntry *IDE_array = NULL;
    XPTInterfaceDescriptor *id;
    XPTTypeDescriptor *td;
    XPTAnnotation *ann, *first_ann;
    PRUint32 header_sz, len;
    PRUint32 oldOffset;
    PRUint32 newOffset;
    size_t flen = 0;
    char *head, *data, *whole;
    const char *outFileName;
    FILE *in, *out;
    fixElement *fix_array = NULL;
    int i,j;
    int k = 0;

    if (argc < 3) {
        xpt_link_usage(argv);
        return 1;
    }
        
    arena = XPT_NewArena(1024 * 10, sizeof(double), "main xpt_link arena");
    if (!arena) {
        perror("FAILED: XPT_NewArena");
        return 1;
    }

    first_ann = XPT_NewAnnotation(arena, XPT_ANN_LAST, NULL, NULL);

    /* Check if the "-t version numnber" cmd line arg is present */
    i = 1;
    if (argv[i][0] == '-' && argv[i][1] == 't') {
        /* Parse for "-t version number" */

        /* If -t is the last argument on the command line, we have a problem */
        if (i + 1 == argc) {
            fprintf(stderr, "ERROR: missing version number after -t\n");
            xpt_link_usage(argv);
            return 1;
        }

        /*
         * Assume that the argument after "-t" is the version number string
         * and search for it in our internal list of acceptable version
         * numbers.
         */

        switch (XPT_ParseVersionString(argv[++i], &major_version, 
                                       &minor_version)) {
          case XPT_VERSION_CURRENT:            
          case XPT_VERSION_OLD: 
            break; 
          case XPT_VERSION_UNSUPPORTED: 
            fprintf(stderr, "ERROR: version \"%s\" not supported.\n", 
                    argv[i]);
            xpt_link_usage(argv);
            return 1;          
          case XPT_VERSION_UNKNOWN: 
          default:
            fprintf(stderr, "ERROR: version \"%s\" not recognised.\n", 
                    argv[i]);
            xpt_link_usage(argv);
            return 1;          
        }
            
        /* Hang onto the output file name. It's needed later. */
        outFileName = argv[++i];

        /* Increment i to the cmd line arg after outFileName */
        i++;
    }
    else {        
        outFileName = argv[1];
        i = 2;
    }

    for ( /* use i from earlier */ ; i < argc; i++) {
        char *name = argv[i];

        flen = get_file_length(name);
        if (!flen) {
            fprintf(stderr, "ERROR: file %s is zero length\n", name);
            return 1;
        }

        in = fopen(name, "rb");
        if (!in) {
            perror("FAILED: fopen");
            return 1;
        }

        whole = XPT_MALLOC(arena, flen);
        if (!whole) {
            perror("FAILED: XPT_MALLOC for whole");
            return 1;
        }
        
        if (flen > 0) {
            size_t rv = fread(whole, 1, flen, in);
            if (rv < flen) {
                fprintf(stderr, "short read (%zd vs %zd)! ouch!\n", rv, flen);
                return 1;
            }
            if (ferror(in) != 0 || fclose(in) != 0) {
                perror("FAILED: Unable to read typelib file.\n");
                return 1;
            }
            
            state = XPT_NewXDRState(XPT_DECODE, whole, flen);
            if (!XPT_MakeCursor(state, XPT_HEADER, 0, cursor)) {
                fprintf(stdout, "XPT_MakeCursor failed for %s\n", name);
                return 1;
            }
            if (!XPT_DoHeader(arena, cursor, &header)) {
                fprintf(stdout,
                        "DoHeader failed for %s.  Is %s a valid .xpt file?\n",
                        name, name);
                return 1;
            }
            
            /*
             * Make sure that the version of the typelib file is less than or
             * equal to the version specified in the -t cmd line arg.
             */

            if (header &&
                (header->major_version > major_version ||
                (header->major_version == major_version &&
                 header->minor_version > minor_version))) { 
                fprintf(stderr, "FAILED: %s's version, %d.%d, is newer than "
                                "the version (%d.%d) specified in the -t "
                                "command line argument.\n", 
                                name, header->major_version, header->minor_version,
                                major_version, minor_version);
                return 1;
            }
            
            oldTotalNumberOfInterfaces = totalNumberOfInterfaces;
            totalNumberOfInterfaces += header->num_interfaces;
            if (header->num_interfaces > 0) {
                XPTInterfaceDirectoryEntry *newIDE;
                fixElement *newFix;
  
                newIDE = (XPTInterfaceDirectoryEntry *)
                    XPT_MALLOC(arena, totalNumberOfInterfaces * 
                               sizeof(XPTInterfaceDirectoryEntry));
                if (!newIDE) {
                    perror("FAILED: XPT_MALLOC of IDE_array");
                    return 1;
                }

                if (IDE_array) {
                    if (oldTotalNumberOfInterfaces)
                        memcpy(newIDE, IDE_array,
                               oldTotalNumberOfInterfaces * 
                               sizeof(XPTInterfaceDirectoryEntry));
                    XPT_FREE(arena, IDE_array);
                }
                IDE_array = newIDE;


                newFix = (fixElement *)
                    XPT_MALLOC(arena, 
                               totalNumberOfInterfaces * sizeof(fixElement));
                if (!newFix) {
                    perror("FAILED: XPT_MALLOC of fix_array");
                    return 1;
                }

                if (fix_array) {
                    if (oldTotalNumberOfInterfaces)
                        memcpy(newFix, fix_array,
                               oldTotalNumberOfInterfaces * 
                               sizeof(fixElement));
                    XPT_FREE(arena, fix_array);
                }
                fix_array = newFix;
            
                for (j=0; j<header->num_interfaces; j++) {
                    if (!copy_IDE(&header->interface_directory[j], 
                                  &IDE_array[k])) {
                        perror("FAILED: 1st copying of IDE");
                        return 1;
                    }
                    fix_array[k].iid = IDE_array[k].iid;
                    fix_array[k].name = IDE_array[k].name;
                    fix_array[k].file_num = i-2;
                    fix_array[k].interface_num = j+1;
                    fix_array[k].is_deleted = PR_FALSE;
                    fix_array[k].maps_to_file_num = i-2;
                    fix_array[k].maps_to_interface_num = j+1;

                    k++;
                }
            }
            
            /* Copy the annotations if they are not 'empty'
             */
            if (header->annotations != NULL &&
                header->annotations->flags != XPT_ANN_LAST) {
                ann = first_ann;
                while (ann->next != NULL) {
                    ann = ann->next;
                }
                ann->next = header->annotations;
            }
            
            XPT_FREEIF(arena, header);
            if (state)
                XPT_DestroyXDRState(state);
            XPT_FREE(arena, whole);
            flen = 0;            

        } else {
            fclose(in);
            perror("FAILED: file length <= 0");
            return 1;
        }
    }

    /* Make sure the last annotation is the only one marked as XP_ANN_LAST.
     */
    ann = first_ann;
    while (ann->next != NULL) {
        ann->flags &= ~XPT_ANN_LAST;
        ann = ann->next;
    }    
    ann->flags |= XPT_ANN_LAST;

    /* Sort both IDE_array and fix_array by name so we can check for 
     * name_space::name collisions. 
     */
    qsort(IDE_array, 
          totalNumberOfInterfaces, 
          sizeof(XPTInterfaceDirectoryEntry), 
          compare_IDEs_by_name);

    qsort(fix_array, 
          totalNumberOfInterfaces, 
          sizeof(fixElement), 
          compare_fixElements_by_name);

    /* trueNumberOfInterfaces == number of interfaces left after deletions
     * are made. Initialize it here to be the same as the total number of
     * interfaces we'ce encountered thus far.
     */
    trueNumberOfInterfaces = totalNumberOfInterfaces;

    /* Iterate through the sorted interfaces. Start at one so we don't 
     * accidentally walk off the end of the array.
     */
    i = 1;
    while (i != trueNumberOfInterfaces) {
        
        /* Check for name_space::name collision. 
         */
        if (compare_strings(IDE_array[i-1].name, 
                            IDE_array[i].name) == 0 && 
            compare_strings(IDE_array[i-1].name_space, 
                             IDE_array[i].name_space) == 0) {
            
            /* If one of the interfaces is unresolved, delete that one 
             * preferentailly.
             */
            if (!IDE_array[i-1].interface_descriptor) {
                /* Shrink the IDE_array to delete the duplicate interface.
                 */
                if (!shrink_IDE_array(IDE_array, 
                                      i-1, 
                                      trueNumberOfInterfaces)) {
                    perror("FAILED: shrink_IDE_array");
                    return 1;
                }
                /* Update the fix array. This involves moving the deleted 
                 * entry to the end of the array (rather than deleting it)
                 * and mapping it to the "replacement" element so we can
                 * update interface indices appropriately later.
                 */
                update_fix_array(arena, fix_array, i-1, 
                                 totalNumberOfInterfaces, i);
                /* Decrement the true number of interfaces since we just
                 * deleted one. There's more than one way to get out of
                 * this loop.
                 */
                trueNumberOfInterfaces--;
            } else {
                if (!IDE_array[i].interface_descriptor ||
                    (compare_IIDs(&IDE_array[i-1].iid, &IDE_array[i].iid) == 0))
                {
                    /* Shrink the IDE_array to delete the duplicate interface.
                     */
                    if (!shrink_IDE_array(IDE_array, 
                                          i, 
                                          trueNumberOfInterfaces)) {
                        perror("FAILED: shrink_IDE_array");
                        return 1;
                    }
                    /* Update the fix array. This involves moving the deleted 
                     * entry to the end of the array (rather than deleting it)
                     * and mapping it to the "replacement" element so we can
                     * update interface indices appropriately later.
                     */
                    update_fix_array(arena, fix_array, i, 
                                     totalNumberOfInterfaces, i-1);
                    /* Decrement the true number of interfaces since we just
                     * deleted one. There's more than one way to get out of
                     * this loop.
                     */
                    trueNumberOfInterfaces--;
                } else {
                    /* Found interfaces with duplicate names but different
                     * iids! */
                    char *ns = IDE_array[i].name_space;
                    fprintf(stderr,
                            "ERROR: found duplicate definitions of interface "
                            "%s%s%s with iids \n",
                            ns ? ns : "", ns ? "::" : "", IDE_array[i].name);
                    print_IID(&IDE_array[i].iid, stderr);
                    fprintf(stderr, " and ");
                    print_IID(&IDE_array[i-1].iid, stderr);
                    fprintf(stderr, "\n");
                    return 1;
                }
            }
        } else {
            /* Only increment if there was no name_space::name collision.
             */
            i++;
        }
    }

    /* Sort the IDE_array (put them in their final order) so that updating
     * of indices will be meaningful.
     */
    qsort(IDE_array, 
          trueNumberOfInterfaces, 
          sizeof(XPTInterfaceDirectoryEntry), 
          compare_IDEs_by_IID);

    /* Sort the fix_array to match the IDE_array. 
     */
    qsort(fix_array, 
          trueNumberOfInterfaces, 
          sizeof(fixElement), 
          compare_fixElements_by_IID);

    /* Iterate through the remaining interfaces (those not deleted) 
     * looking for references to interfaces (such as id->parent_interface)
     * which need an updated index number.
     */
    for (i=0; i<trueNumberOfInterfaces; i++) {
        
        /* Define id to save some keystrokes.
         */
        id = IDE_array[i].interface_descriptor;

        /* Check for unresolved interface.
         */
        if (id) {
            
            /* Fix parent_interface first.
             */
            if (id->parent_interface && id->parent_interface != 0) {
                id->parent_interface = 
                    get_new_index(fix_array, totalNumberOfInterfaces,
                                  fix_array[i].file_num, id->parent_interface);
            }
            /* Iterate through the method descriptors looking for params of
             * type TD_INTERFACE_TYPE.
             */
            for (j=0; j<id->num_methods; j++) {
                /* Cycle through the params first.
                 */
                for (k=0; k<id->method_descriptors[j].num_args; k++) {
                    /* Define td to save some keystrokes.
                     */
                    td = &id->method_descriptors[j].params[k].type;

                    while (XPT_TDP_TAG(td->prefix) == TD_ARRAY) {
                        td = &id->additional_types[td->type.additional_type];
                    }

                    if (XPT_TDP_TAG(td->prefix) == TD_INTERFACE_TYPE) {
                        td->type.iface = 
                            get_new_index(fix_array, 
                                          totalNumberOfInterfaces,
                                          fix_array[i].file_num, 
                                          td->type.iface);
                    }                                                
                }

                /* Check the result param too. Define td again to save 
                 * some keystrokes.
                 */
                td = &id->method_descriptors[j].result->type;
                if (XPT_TDP_TAG(td->prefix) == TD_INTERFACE_TYPE) {
                    td->type.iface = 
                        get_new_index(fix_array, totalNumberOfInterfaces,
                                      fix_array[i].file_num, 
                                      td->type.iface);
                }                
            }
        } 
    }
    
    /* Iterate through the array quickly looking for duplicate IIDS.
     * This shouldn't happen, i.e. is a failure condition, so bail
     * if we find a duplicate. If we have more than one entry, start 
     * at one so we don't accidentally grep the ether.
     */
    if (trueNumberOfInterfaces>1) {
        for (i=1; i<trueNumberOfInterfaces; i++) {
            /* Only complain if the IIDs are identical and nonzero. */
            if (compare_IIDs(&IDE_array[i-1].iid, &IDE_array[i].iid) == 0 && 
                compare_IDE_with_zero(&IDE_array[i]) != 0) {
                fprintf(stderr, "FATAL ERROR:\n"
                        "Duplicate IID detected (");
                print_IID(&IDE_array[i-1].iid, stderr);
                fprintf(stderr, ") in\n"
                        "interface %s::%s from %s\n"
                        "and\n" 
                        "interface %s::%s from %s\n",
                        IDE_array[i-1].name_space ? 
                        IDE_array[i-1].name_space : "", 
                        IDE_array[i-1].name, 
                        argv[fix_array[i-1].file_num+2],
                        IDE_array[i].name_space ? 
                        IDE_array[i].name_space : "", 
                        IDE_array[i].name, 
                        argv[fix_array[i].file_num+2]);
                return 1;
            }
        }
    }

    header = XPT_NewHeader(arena, (PRUint16)trueNumberOfInterfaces, 
                           major_version, minor_version);

    header->annotations = first_ann;
    for (i=0; i<trueNumberOfInterfaces; i++) {
        if (!copy_IDE(&IDE_array[i], &header->interface_directory[i])) {
            perror("FAILED: 2nd copying of IDE");
            return 1;
        }
    }
    
    header_sz = XPT_SizeOfHeaderBlock(header); 

    state = XPT_NewXDRState(XPT_ENCODE, NULL, 0);
    if (!state) {
        perror("FAILED: error creating XDRState");
        return 1;
    }
    
    XPT_SetDataOffset(state, header_sz);

    if (!XPT_MakeCursor(state, XPT_HEADER, header_sz, cursor)) {
        perror("FAILED: error making cursor");
        return 1;
    }
    oldOffset = cursor->offset;
    if (!XPT_DoHeader(arena, cursor, &header)) {
        perror("FAILED: error doing Header");
        return 1;
    }
    newOffset = cursor->offset;
    XPT_GetXDRDataLength(state, XPT_HEADER, &len);
    header->file_length = len;
    XPT_GetXDRDataLength(state, XPT_DATA, &len);
    header->file_length += len;
    XPT_SeekTo(cursor, oldOffset);
    if (!XPT_DoHeaderPrologue(arena, cursor, &header, NULL)) {
        perror("FAILED: error doing Header");
        return 1;
    }
    XPT_SeekTo(cursor, newOffset);
    out = fopen(outFileName, "wb");
    if (!out) {
        perror("FAILED: fopen");
        return 1;
    }

    XPT_GetXDRData(state, XPT_HEADER, &head, &len);
    fwrite(head, len, 1, out);
 
    XPT_GetXDRData(state, XPT_DATA, &data, &len);
    fwrite(data, len, 1, out);
 
    if (ferror(out) != 0 || fclose(out) != 0) {
        fprintf(stderr, "Error writing file: %s\n", argv[1]);
    } else {
/*        fprintf(stderr, "File written: %s\n", argv[1]); */
    }
 
    if (state)
        XPT_DestroyXDRState(state);
    
    XPT_DestroyArena(arena);

    return 0;        
}
Exemple #25
0
int compile_program(GLuint* program,
                    const std::string vertex_shader_file,
                    const std::string frag_shader_file) {
    std::string vertexSource;
    std::string fragmentSource;
    
    long vertex_shader_length = get_file_length(vertex_shader_file);
    long frag_shader_length = get_file_length(frag_shader_file);
    
    if (vertex_shader_length < 0 || frag_shader_length < 0) {
        printf("Could not find files %s or %s\n", vertex_shader_file.c_str(), frag_shader_file.c_str());
        return 1;
    }
    
    vertexSource.reserve(vertex_shader_length);
    fragmentSource.reserve(frag_shader_length);
    
    //Read our shaders into the appropriate buffers
    load_file(vertexSource, vertex_shader_file); //Get source code for vertex shader.
    load_file(fragmentSource, frag_shader_file); //Get source code for fragment shader.
    
    //Create an empty vertex shader handle
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    
    //Send the vertex shader source code to GL
    //Note that std::string's .c_str is NULL character terminated.
    const GLchar *source = (const GLchar *)vertexSource.c_str();
    glShaderSource(vertexShader, 1, &source, 0);
    
    //Compile the vertex shader
    glCompileShader(vertexShader);
    
    GLint isCompiled = 0;
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isCompiled);
    if(isCompiled == GL_FALSE)
    {
        GLint maxLength = 0;
        //The maxLength includes the NULL character
        glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &maxLength);
        
        GLchar *info_log;
        info_log = (GLchar*)malloc(maxLength);
        glGetShaderInfoLog(vertexShader, maxLength, &maxLength, info_log);
        fprintf(stderr, "Shader compilation failed: %*s\n", maxLength, info_log);
        free(info_log);
        
        //We don't need the shader anymore.
        glDeleteShader(vertexShader);
        return 1;
    }
    
    //Create an empty fragment shader handle
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    
    //Send the fragment shader source code to GL
    //Note that std::string's .c_str is NULL character terminated.
    source = (const GLchar *)fragmentSource.c_str();
    glShaderSource(fragmentShader, 1, &source, 0);
    
    //Compile the fragment shader
    glCompileShader(fragmentShader);
    
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isCompiled);
    if(isCompiled == GL_FALSE)
    {
        GLint maxLength = 0;
        glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &maxLength);
        
        //The maxLength includes the NULL character
        GLchar *info_log;
        info_log = (GLchar*)malloc(maxLength);
        glGetShaderInfoLog(fragmentShader, maxLength, &maxLength, info_log);
        fprintf(stderr, "Shader compilation failed: %*s\n", maxLength, info_log);
        free(info_log);
        
        //We don't need the shader anymore.
        glDeleteShader(fragmentShader);
        //Either of them. Don't leak shaders.
        glDeleteShader(vertexShader);
        return 1;
    }
    
    //Vertex and fragment shaders are successfully compiled.
    //Now time to link them together into a program.
    //Get a program object.
    *program = glCreateProgram();
    
    //Attach our shaders to our program
    glAttachShader(*program, vertexShader);
    glAttachShader(*program, fragmentShader);
    
    //Link our program
    glLinkProgram(*program);
    
    //Note the different functions here: glGetProgram* instead of glGetShader*.
    GLint isLinked = 0;
    glGetProgramiv(*program, GL_LINK_STATUS, (int *)&isLinked);
    if(isLinked == GL_FALSE)
    {
        GLint maxLength = 0;
        glGetProgramiv(*program, GL_INFO_LOG_LENGTH, &maxLength);
        
        //The maxLength includes the NULL character
        GLchar *info_log;
        info_log = (GLchar*)malloc(maxLength);
        glGetProgramInfoLog(*program, maxLength, &maxLength, info_log);
        fprintf(stderr, "Program compilation failed: %*s\n", maxLength, info_log);
        free(info_log);
        
        //We don't need the program anymore.
        glDeleteProgram(*program);
        //Don't leak shaders either.
        glDeleteShader(vertexShader);
        glDeleteShader(fragmentShader);
        return 1;
    }
    //We don't need these anymore
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    
    return 0;
}