Пример #1
0
	void TLSClient_Impl::handshake_certificate_received(const void *data, int size)
	{
		if (conversation_state != cl_tls_state_receive_certificate)
			throw Exception("TLS Expected certificate");

		uint8_t buffer[3];
		copy_data(buffer, 3, data, size);

		unsigned int certificate_list_size = buffer[0] << 16 | buffer[1] << 8 | buffer[2];
		if ( (size < certificate_list_size) || (certificate_list_size == 0) )
			throw Exception("Invalid certification size");

		while(certificate_list_size > 0)
		{
			if (certificate_list_size < 3)
				throw Exception("Invalid record length");
			copy_data(buffer, 3, data, size);
			certificate_list_size -= 3;

			unsigned int certificate_size = buffer[0] << 16 | buffer[1] << 8 | buffer[2];
			if ( (certificate_list_size < certificate_size) || (certificate_size == 0) )
				throw Exception("Invalid certification size");

			std::vector<unsigned char> cert_buffer;
			cert_buffer.resize(certificate_size);
			copy_data(&cert_buffer[0], certificate_size, data, size);

			inspect_certificate(cert_buffer);

			certificate_list_size -= certificate_size;
		}

		conversation_state = cl_tls_state_receive_server_hello_done;
	}
Пример #2
0
static void
check_ed25519 (const char *fname)
{
  FILE *fp;
  int lineno, ntests;
  char *line;
  int testno;
  char *sk, *pk, *msg, *sig;

  show ("Checking Ed25519.\n");

  fp = fopen (fname, "r");
  if (!fp)
    die ("error opening '%s': %s\n", fname, strerror (errno));

  testno = 0;
  sk = pk = msg = sig = NULL;
  lineno = ntests = 0;
  while ((line = read_textline (fp, &lineno)))
    {
      if (!strncmp (line, "TST:", 4))
        testno = atoi (line+4);
      else if (!strncmp (line, "SK:", 3))
        copy_data (&sk, line, lineno);
      else if (!strncmp (line, "PK:", 3))
        copy_data (&pk, line, lineno);
      else if (!strncmp (line, "MSG:", 4))
        copy_data (&msg, line, lineno);
      else if (!strncmp (line, "SIG:", 4))
        copy_data (&sig, line, lineno);
      else
        fail ("unknown tag at input line %d", lineno);

      xfree (line);
      if (testno && sk && pk && msg && sig)
        {
          hexdowncase (sig);
          one_test (testno, sk, pk, msg, sig);
          ntests++;
          if (!(ntests % 256))
            show_note ("%d of %d tests done\n", ntests, N_TESTS);
          xfree (pk);  pk = NULL;
          xfree (sk);  sk = NULL;
          xfree (msg); msg = NULL;
          xfree (sig); sig = NULL;
        }

    }
  xfree (pk);
  xfree (sk);
  xfree (msg);
  xfree (sig);

  if (ntests != N_TESTS && !custom_data_file)
    fail ("did %d tests but expected %d", ntests, N_TESTS);
  else if ((ntests % 256))
    show_note ("%d tests done\n", ntests);

  fclose (fp);
}
void SharedSurfpackApproxData::
add_sd_to_surfdata(const Pecos::SurrogateDataVars& sdv,
		   const Pecos::SurrogateDataResp& sdr, short fail_code,
		   SurfData& surf_data)
{
  // coarse-grained fault tolerance for now: any failure qualifies for omission
  if (fail_code)
    return;

  // Surfpack's RealArray is std::vector<double>; use DAKOTA copy_data helpers.
  // For DAKOTA's compact mode, any active discrete {int,real} variables could
  // be contained within SDV's continuousVars (see Approximation::add(Real*)),
  // although it depends on eval cache lookups as shown in
  // ApproximationInterface::update_approximation().
  RealArray x; 
  sdv_to_realarray(sdv, x);
  Real f = sdr.response_function();

  // for now only allow builds from exactly 1, 3=1+2, or 7=1+2+4; use
  // different set functions so the SurfPoint data remains empty if
  // not present
  switch (buildDataOrder) {

  case 1:
    surf_data.addPoint(SurfPoint(x, f));
    break;

  case 3: {
    RealArray gradient;
    copy_data(sdr.response_gradient(), gradient);
    surf_data.addPoint(SurfPoint(x, f, gradient));
    break;
  }

  case 7: {
    RealArray gradient;
    copy_data(sdr.response_gradient(), gradient);
    SurfpackMatrix<Real> hessian;
    copy_matrix(sdr.response_hessian(), hessian);
    surf_data.addPoint(SurfPoint(x, f, gradient, hessian));
    break;
  }

  default:
    Cerr << "\nError (SharedSurfpackApproxData): derivative data may only be "
	 << "used if all\nlower-order information is also present. Specified "
	 << "buildDataOrder is " << buildDataOrder << "."  << std::endl; 
    abort_handler(-1);
    break;

  }
}
Пример #4
0
// a convenience function to retrieve a length-encoded domain name from the byte array
int get_domain_name(char *data, int offset, char *buffer) {
   int numBytes = 0;
   int numChars = 0;

   // determine how many characters are in the first block
   int block_size = (int)data[offset];
   numBytes += 1;
   while (block_size > 0) {
      // copy the correct number of bytes into the buffer
      copy_data(data, buffer, offset + numBytes, numChars, block_size);
      numBytes += block_size;
      numChars += block_size;

      // add the . character between blocks
      buffer[numChars] = '.';
      numChars++;

      // determine how many characters are in the next block
      block_size = (int)data[offset + numBytes];
      numBytes += 1;
   }

   if (block_size < 0)
      numBytes++;  // skip special characters that trail 'c0'

   numChars--; // get rid of the trailing '.', replacing it with a null-terminator
   buffer[numChars] = 0;

   return numBytes;
}
Пример #5
0
int insert(int key, int last) {
    int u = ++ node_count, node;
    clear(u);
    step[u] = step[last] + 1;
    for (node = last; node && children[node][key] == 0; node = prev[node]) {
        children[node][key] = u;
    }
    if (node == 0) {
        prev[u] = 1;
    } else {
        int v = children[node][key];
        if (step[v] == step[node] + 1) {
            prev[u] = v;
        } else {
            int nv = ++ node_count;
            copy_data(nv, v);
            step[nv] = step[node] + 1;
            prev[u] = prev[v] = nv;
            for (; node && children[node][key] == v; node = prev[node]) {
                children[node][key] = nv;
            }
        }
    }
    return u;
}
Пример #6
0
int
archive_read_extract2(struct archive *_a, struct archive_entry *entry,
    struct archive *ad)
{
	struct archive_read *a = (struct archive_read *)_a;
	int r, r2;

	/* Set up for this particular entry. */
	if (a->skip_file_set)
		archive_write_disk_set_skip_file(ad,
		    a->skip_file_dev, a->skip_file_ino);
	r = archive_write_header(ad, entry);
	if (r < ARCHIVE_WARN)
		r = ARCHIVE_WARN;
	if (r != ARCHIVE_OK)
		/* If _write_header failed, copy the error. */
 		archive_copy_error(&a->archive, ad);
	else if (!archive_entry_size_is_set(entry) || archive_entry_size(entry) > 0)
		/* Otherwise, pour data into the entry. */
		r = copy_data(_a, ad);
	r2 = archive_write_finish_entry(ad);
	if (r2 < ARCHIVE_WARN)
		r2 = ARCHIVE_WARN;
	/* Use the first message. */
	if (r2 != ARCHIVE_OK && r == ARCHIVE_OK)
		archive_copy_error(&a->archive, ad);
	/* Use the worst error return. */
	if (r2 < r)
		r = r2;
	return (r);
}
Пример #7
0
int write_rbuf(char *ubuf, unsigned int ulen)
{
    char *rbuf = ringbuf;
    unsigned int r_nend;
    if (ulen > (MAX_RBUF_LEN - 1)) {
        ubuf = ubuf + (ulen  - (MAX_RBUF_LEN - 1));
        ulen = MAX_RBUF_LEN - 1;

    }

    /*
     *   ulen <= (MAX_RBUF_LEN - 1)
     */

    r_nend = (r_end + ulen) % MAX_RBUF_LEN;

    /* (r_st <= r_next_end < r_end)  || (r_next_end < r_end < r_st ) || (r_end < r_st <= r_next_end) */
    if ((r_st <= r_nend && r_end > r_nend) || ((r_st > r_end) && (r_nend >= r_st || r_nend < r_end)))
        r_st = (r_nend + 1)%MAX_RBUF_LEN;


    copy_data(rbuf, r_end, r_nend, ubuf, ulen);
    r_end = r_nend;
    return ulen;
}
Пример #8
0
	void TLSClient_Impl::handshake_finished_received(const void *data, int size)
	{
		if (conversation_state != cl_tls_state_receive_finished)
			throw Exception("TLS Expected server finished");

		const int verify_data_size = 12;
		Secret server_verify_data(verify_data_size);
		copy_data(server_verify_data.get_data(), verify_data_size, data, size);

		Secret client_verify_data(verify_data_size);

		Secret md5_handshake_messages(16);
		Secret sha1_handshake_messages(20);

		server_handshake_md5_hash.calculate();
		server_handshake_sha1_hash.calculate();

		server_handshake_md5_hash.get_hash(md5_handshake_messages.get_data());
		server_handshake_sha1_hash.get_hash(sha1_handshake_messages.get_data());

		PRF(client_verify_data.get_data(), verify_data_size, security_parameters.master_secret, "server finished", md5_handshake_messages, sha1_handshake_messages);

		if (memcmp(client_verify_data.get_data(), server_verify_data.get_data(), verify_data_size))
			throw Exception("TLS server finished verify data failed");

		conversation_state = cl_tls_state_connected;
	}
Пример #9
0
int main()
{   
	int sock,conn,i;
	struct sockaddr_in addr;
	socklen_t addr_len=sizeof(addr);
	if((sock=socket(AF_INET,SOCK_STREAM,0))<0){
		die("socket");
	}
	/*设置地址可重用*/
	i=1;
	setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&i,sizeof(i));
	/*绑定到任意地址*/
	memset(&addr,0,sizeof(addr));
	addr.sin_family=AF_INET;
	addr.sin_addr.s_addr=htonl(INADDR_ANY);
	addr.sin_port=htons(8888);

	if(bind(sock,(struct sockaddr*)&addr,sizeof(addr))){
		die("bind");
	}
	if(listen(sock,5)){
		die("listen");
	}
	while((conn=accept(sock,(struct sockaddr*)&addr,&addr_len))>0){
		printf("Accept %s:%d\n",inet_ntoa(addr.sin_addr),addr.sin_port);
		/*使用新接收的套机子通信*/
		copy_data(conn,STDOUT_FILENO);
		printf("Done!\n");
		close(conn);
	}
	if(conn<0)
		die("accept");
	close(sock);
	return 0;
}
Пример #10
0
static void
extract(const char *filename, int do_extract, int flags)
{
	struct archive *a;
	struct archive *ext;
	struct archive_entry *entry;
	int r;

	a = archive_read_new();
	ext = archive_write_disk_new();
	archive_write_disk_set_options(ext, flags);
	/*
	 * Note: archive_write_disk_set_standard_lookup() is useful
	 * here, but it requires library routines that can add 500k or
	 * more to a static executable.
	 */
	archive_read_support_format_tar(a);
	/*
	 * On my system, enabling other archive formats adds 20k-30k
	 * each.  Enabling gzip decompression adds about 20k.
	 * Enabling bzip2 is more expensive because the libbz2 library
	 * isn't very well factored.
	 */
	if (filename != NULL && strcmp(filename, "-") == 0)
		filename = NULL;
	if ((r = archive_read_open_filename(a, filename, 10240)))
		fail("archive_read_open_filename()",
		    archive_error_string(a), r);
	for (;;) {
		r = archive_read_next_header(a, &entry);
		if (r == ARCHIVE_EOF)
			break;
		if (r != ARCHIVE_OK)
			fail("archive_read_next_header()",
			    archive_error_string(a), 1);
		if (verbose && do_extract)
			msg("x ");
		if (verbose || !do_extract)
			msg(archive_entry_pathname(entry));
		if (do_extract) {
			r = archive_write_header(ext, entry);
			if (r != ARCHIVE_OK)
				warn("archive_write_header()",
				    archive_error_string(ext));
			else {
				copy_data(a, ext);
				r = archive_write_finish_entry(ext);
				if (r != ARCHIVE_OK)
					fail("archive_write_finish_entry()",
					    archive_error_string(ext), 1);
			}

		}
		if (verbose || !do_extract)
			msg("\n");
	}
	archive_read_close(a);
	archive_read_free(a);
	exit(0);
}
Пример #11
0
    ANDBenchmark(int argc, char *argv[]):name("AND"), num_test(100)
    {
        double t0=omp_get_wtime();
        if(argc !=2)
        {
            std::cerr<<"usage: "<<argv[0]<<" size_of_data_in_MiB"<<std::endl;
            exit(1);
        }
        num_data=std::atol(argv[1])*1024*1024/sizeof(T);

        random_data= new T [num_data];
        RandomNumber<REAL_TYPE> generator;
        generator(num_data, random_data);
        result = new T [num_data];
        data1  = new T [num_data];
        data2  = new T [num_data];
        copy_data(num_data, random_data, data1);
        zero_clear(num_data, data2);
        double t1=omp_get_wtime()-t0;
        std::cout << "Test data type = "<< typeid(T).name()<<std::endl;
        std::cout << "Test data size = "<< argv[1] <<" MiByte"<<std::endl;
        std::cout << "Elapsed time for initialize: "<<t1<<" sec"<<std::endl;
        std::cout << std::endl;
        std::cout << "====" << this->name << " Benchmark start ====" << std::endl;
    }
Пример #12
0
bool TGAImageDecoder::LoadRLE(DataStream* ds,ImageImpl* img) {
    Byte* data = img->GetRawData()->GetDataPtr();
    UInt32 pixels = img->GetWidth()*img->GetHeight();
    const UInt32 bpp = img->GetBpp();
    UInt32 c = 0;
    BufferedReader rdr(ds,2048);
    while (pixels && !rdr.Eof()) {
        /// @todo warning endianless
        rdr.Read(reinterpret_cast<Byte*> (&c),1);
        if (c < 128) {
            c++;
            if (c>pixels) c = pixels;
            data+=rdr.Read(data,c*bpp);
            pixels -= c;
        } else {
            c-=127;
            if (c>pixels) c = pixels;
            Byte* data_c = data;
            data+=rdr.Read(data,bpp);
            for(UInt32 counter = 1; counter < c; counter++)
            {
                data=copy_data(data_c,data,bpp);
            }
            pixels-= c;
        }
    }
    return pixels == 0;
}
Пример #13
0
int Tarball::install () {
  archive_entry *entry;
  int r;

  archive* a = archive_read_new();
  archive_read_support_format_all(a);
  archive_read_support_filter_all(a);

  archive* ext = archive_write_disk_new();
  const int flags = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM |
    ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS;
  archive_write_disk_set_options(ext, flags);
  archive_write_disk_set_standard_lookup(ext);

  const std::string subdir = "deps";
  const std::string filename = subdir + "/" + basename(this->location);
  printf("Unpacking archive %s\n", filename.c_str());
  if ((r = archive_read_open_filename(a,filename.c_str(), 10240))) {
    fprintf(stderr, "Error opening archive:\n%s\n", archive_error_string(a));
    return -1;
  }
  for (;;) {
    r = archive_read_next_header(a, &entry);
    if (r == ARCHIVE_EOF) {
      break;
    }
    if (r < ARCHIVE_OK) {
      fprintf(stderr, "%s\n", archive_error_string(a));
    }
    if (r < ARCHIVE_WARN) {
      return -1;
    }
    rewrite_subdir(entry, subdir);
    r = archive_write_header(ext, entry);
    if (r < ARCHIVE_OK) {
      fprintf(stderr, "%s\n", archive_error_string(ext));
    } else if (archive_entry_size(entry) > 0) {
      r = copy_data(a, ext);
      if (r < ARCHIVE_OK) {
        fprintf(stderr, "%s\n", archive_error_string(ext));
      }
      if (r < ARCHIVE_WARN) {
        return -1;
      }
    }
    r = archive_write_finish_entry(ext);
    if (r < ARCHIVE_OK) {
      fprintf(stderr, "%s\n", archive_error_string(ext));
    }
    if (r < ARCHIVE_WARN) {
      return -1;
    }
  }
  archive_read_close(a);
  archive_read_free(a);
  archive_write_close(ext);
  archive_write_free(ext);

  return 0;
};
Пример #14
0
void shell() {
	char ptr[64];
	
	copy_data();
	putstr("Welcome to the (unstable) C Kernel\n");
	
	while(1)
	{
		putstr("> ");
		getstr(ptr, 64);
		if (strcmp(ptr, "STOP"))
		{
			putstr("Exiting...\n");
			return;
		}
		else if (strcmp(ptr, "MEMTEST"))
		{
			putstr("Performing Memory Test\n");
			memtest();
		}
		else if (strcmp(ptr, "ERRTEST"))
		{
			asm ("trap #0\n");
		}
		else
		{
			putstr("Echo: ");
			putstr(ptr);
			putch('\n');
		}
	}
}
Пример #15
0
	/**
 	 * Set record argument
 	 * @param i index (position) of the argument (zero based)
 	 * @param a argument itself
 	 * @param tailroom number of bytes available at the tail of the record (used as generic buffer).
 	 * @param offset offset in the buffer (used for packing strings and complex args)
 	 */
	hogl_force_inline void set_arg(unsigned int i, const hogl::arg a, unsigned int tailroom, unsigned int &offset)
	{
		// In case of the fully inlined version (ie when an entire record posting stack
		// is inlined) a.type is known at compile time, which means all type checks 
		// are resolved at compile time.

		if (a.type == a.NONE)
			return;

		set_arg_type(i, a.type);

		if (a.type == a.HEXDUMP || a.type == a.RAW) {
			offset += copy_data(i, (const uint8_t *) a.val, a.len, tailroom, offset);
			return;
		}

		if (a.type == a.CSTR) {
			offset += copy_cstr(i, (const uint8_t *) a.val, a.len, tailroom, offset);
			return;
		}

		if (a.is_32bit())
			set_arg_val32(i, a.val);
		else
			set_arg_val64(i, a.val);
	}
Пример #16
0
int list__to_tuple(data_t **args, argc_t argc, data_t *ret, scope_t *scope)
{
    (void) argc;
    data_t ret1;
    checkf(list__length(args, 1, &ret1, scope) == 0, "Failed to find list length.");
    int len = ret1.value.integral;

    struct type **multiple = gc_add(scope->gc, malloc(sizeof(struct type *) * (len + 1)));
    multiple[len] = NULL;
    
    ret->value.tuple = gc_add(scope->gc, malloc(sizeof(data_t *) * (len + 1)));
    ret->value.tuple[len] = NULL;

    list_node_t *node;
    list_iterator_t *it = list_iterator_new(args[0]->value.list, LIST_HEAD);

    int i = 0;

    while ((node = list_iterator_next(it))) {
        ret->value.tuple[i] = copy_data((data_t *) node->val, scope);
        multiple[i] = ret->value.tuple[i]->type;
        check_mem(ret->value.tuple[i]);

        ++i;
    }

    ret->type = construct_type(tid_tuple, multiple, scope->gc);

    if (it) list_iterator_destroy(it);
    return 0;

error:
    if (it) list_iterator_destroy(it);
    return -1;
}
Пример #17
0
  main(void)
{

  set_eflags();

  /* Define the kernel segment registers */
  set_seg_regs(__KERNEL_DS, __KERNEL_DS, INITIAL_ESP);

  printk("Kernel Loaded!    ");

  /* Initialize hardware data */
  setGdt(); /* Definicio de la taula de segments de memoria */
  setIdt(); /* Definicio del vector de interrupcions */
  setTSS(); /* Definicio de la TSS */

  /* Initialize Memory */
  init_mm();

/* Initialize an address space to be used for the monoprocess version of ZeOS */

  /* monoprocess_init_addr_space(); TO BE DELETED WHEN ADDED THE PROCESS MANAGEMENT CODE TO BECOME MULTIPROCESS */

  /* Initialize Scheduling */
  init_sched();

  /* Initialize idle task data */
  init_idle();

  /* Initialize task 1 data */
  init_task1();

  /* Initialize keyboard buffer */
  init_keyboard_buffer();

  /* Move user code/data now (after the page table initialization) */
  copy_data((void *) KERNEL_START + *p_sys_size, usr_main, *p_usr_size);

  /* Adds this call in order to perform test suite provided by lab course */
  zeos_init_auxjp();

  printk("Entering user mode...");

  /*
   * zeos_ticks must be initialized after memory initialization and just before
   * enabling interrupts in order to measure the correct elapsed time
   */
  zeos_ticks = 0;

  enable_int();

  /*
   * We return from a 'theorical' call to a 'call gate' to reduce our privileges
   * and going to execute 'magically' at 'usr_main'...
   */
  return_gate(__USER_DS, __USER_DS, USER_ESP, __USER_CS, L_USER_START);

  /* The execution never arrives to this point */
  return 0;
}
Пример #18
0
address& address::operator=(address const& other)
{
	if (this == &other) return *this;
	clear();
	data_ = new sockaddr_in();
	copy_data(*other.data_, *this->data_);
	return *this;
}
Пример #19
0
int extract_archive(const char* filename, const char* to_path) {
  struct archive* a;
  struct archive* ext;
  struct archive_entry* entry;
  int r;
  int flags = ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS;

  a = archive_read_new();
  ext = archive_write_disk_new();
  archive_write_disk_set_options(ext, flags);
  archive_write_disk_set_standard_lookup(ext);

  archive_read_support_format_all(a);
  archive_read_support_compression_all(a);

  if(filename != NULL && strcmp(filename, "-") == 0) {
    filename = NULL;
  }
  if((r = archive_read_open_file(a, filename, 10240))) {
    printf("archive_read_open_file(): %s\n", archive_error_string(a));
    return r;
  }
  for(;;) {
    r = archive_read_next_header(a, &entry);
    if(r == ARCHIVE_EOF) {
      break;
    }
    if(r != ARCHIVE_OK) {
      printf("archive_read_next_header(): %s\n", archive_error_string(a));
      return 0;
    }

    // rewrite pathname
    const char* path = archive_entry_pathname(entry);
    char new_path[PATH_MAX + 1];
    sprintf(new_path, "%s/%s", to_path, path + (strncmp(path, "rootfs/", 7) == 0 ? 7 : 0));
    archive_entry_set_pathname(entry, new_path);

    r = archive_write_header(ext, entry);
    if(r != ARCHIVE_OK) {
      printf("archive_write_header(): %s\n", archive_error_string(ext));
    } else {
      copy_data(a, ext);
      if(r != ARCHIVE_OK) {
        printf("archive_write_finish_entry(): %s\n", archive_error_string(ext));
        return 0;
      }

    }
    r = archive_write_finish_entry(ext);

  }
  archive_read_close(a);
  archive_read_finish(a);
  archive_write_close(ext);
  archive_write_finish(ext);
  return 1;
}
Пример #20
0
int
main (int argc, char *argv[])
{   char 		*progname, *infilename, *outfilename ;
    SNDFILE	 	*infile, *outfile ;
    SF_INFO	 	sfinfo ;
    double		normfactor ;

    progname = strrchr (argv [0], '/') ;
    progname = progname ? progname + 1 : argv [0] ;

    if (argc != 3)
    {   print_usage (progname) ;
        return  1 ;
    } ;

    infilename = argv [1] ;
    outfilename = argv [2] ;

    if (! strcmp (infilename, outfilename))
    {   fprintf (stderr, "Error : Input and output filenames are the same.\n\n") ;
        print_usage (progname) ;
        return  1 ;
    } ;

    if (! (infile = sf_open (infilename, SFM_READ, &sfinfo)))
    {   fprintf (stderr, "Not able to open input file %s.\n", infilename) ;
        sf_perror (NULL) ;
        return  1 ;
    } ;

    if (sfinfo.format != (SF_FORMAT_WAV | SF_FORMAT_FLOAT))
    {   fprintf (stderr, "Error : Input file %s is not a 32 bit floating point WAV file.\n", infilename) ;
        return  1 ;
    } ;

    sfinfo.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_24) ;

    sf_command (infile, SFC_CALC_SIGNAL_MAX, &normfactor, sizeof (normfactor)) ;

    if (normfactor < 1.0 && normfactor > 0.0)
        normfactor = ((double) 0x400000) ;
    else
        normfactor = 1.0 ;

    fprintf (stderr, "normfactor : %g\n", normfactor) ;

    if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)))
    {   fprintf (stderr, "Not able to open output file %s.\n", outfilename) ;
        return  1 ;
    } ;

    copy_data (outfile, infile, BUFFER_LEN / sfinfo.channels, normfactor) ;

    sf_close (infile) ;
    sf_close (outfile) ;

    return 0 ;
} /* main */
Пример #21
0
static int do_copy(const char *source, const char *target)
{   
    struct stat info;
	int rv;
        int rv2;
	int fdtarget;
    int fdsource;
	FILE *fsource;
	FILE *ftarget;
	
	fdsource = open(source, O_RDONLY|O_BINARY, 0);

    if (fdsource == -1)
    {   
        error(CONSOLE_PREFIX "invalid input");
        return -1;
    }
    
    rv = fstat(fdsource, &info);
    
    if(rv == -1)
    {
        error(CONSOLE_PREFIX "stat failed\n");
        return -1;
    }
    
    fdtarget = open(target, O_WRONLY|O_BINARY|O_CREAT|O_TRUNC, info.st_mode);
    
	if (fdtarget == -1)
    {   
        error(CONSOLE_PREFIX "invalid output\n");
        close(fdsource);
        return -1;
    }

    fsource = fdopen(fdsource, "rb");
    ftarget = fdopen(fdtarget, "wb");
    
    rv = copy_data(fsource, ftarget);

    if (rv == -1)
    {
        error(CONSOLE_PREFIX "copy failed");
    }

    rv  = fclose(fsource);
    rv2 = fclose(ftarget);

    if (rv || rv2)
    {
        error(CONSOLE_PREFIX "file close failed");
        rv = -1;
    }

    return rv;
}
Пример #22
0
/**
 * Reads file into standard output.
 *
 * @param filename  the input file name.
 * @return   0 - success,
 *          -1 - error
 */
static int read_file(const char* filename)
{
	int fd = open(filename, O_RDONLY);
	if (fd == -1) {
		msg_error("failed to open input file %s (%s)\n", filename, strerror(errno));
		return -1;
	}
	int rc = copy_data(fd, STDOUT_FILENO);
	close(fd);
	return rc;
}
Пример #23
0
Deque& Deque::operator=(const Deque& d)
{
	if (this != &d)
	{
		itsCap = d.capacity();
		itsSize = d.size();
		delete [] itsData;
		copy_data(d.itsData);
	}
	return *this;
}
Пример #24
0
/**
 * Writes standard input into file.
 *
 * @param filename  the output file name.
 * @return   0 - success,
 *          -1 - error
 */
static int write_file(const char* filename)
{
	int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
	if (fd == -1) {
		msg_error("failed to create output file %s (%s)\n", filename, strerror(errno));
		return -1;
	}
	int rc = copy_data(STDIN_FILENO, fd);
	close(fd);
	return rc;
}
Пример #25
0
bool ffmpeg_decode_audio(struct ffmpeg_decode *decode,
		uint8_t *data, size_t size,
		struct obs_source_audio *audio,
		bool *got_output)
{
	AVPacket packet = {0};
	int got_frame = false;
	int ret = 0;

	*got_output = false;

	copy_data(decode, data, size);

	av_init_packet(&packet);
	packet.data = decode->packet_buffer;
	packet.size = (int)size;

	if (!decode->frame) {
		decode->frame = av_frame_alloc();
		if (!decode->frame)
			return false;
	}

	if (data && size)
		ret = avcodec_send_packet(decode->decoder, &packet);
	if (ret == 0)
		ret = avcodec_receive_frame(decode->decoder, decode->frame);

	got_frame = (ret == 0);

	if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
		ret = 0;

	if (ret < 0)
		return false;
	else if (!got_frame)
		return true;

	for (size_t i = 0; i < MAX_AV_PLANES; i++)
		audio->data[i] = decode->frame->data[i];

	audio->samples_per_sec = decode->frame->sample_rate;
	audio->format          = convert_sample_format(decode->frame->format);
	audio->speakers        =
		convert_speaker_layout((uint8_t)decode->decoder->channels);

	audio->frames = decode->frame->nb_samples;

	if (audio->format == AUDIO_FORMAT_UNKNOWN)
		return false;

	*got_output = true;
	return true;
}
Пример #26
0
SGVector<T>& SGVector<T>::operator=(const SGVector<T>& other)
{
	if(&other == this)
	return *this;

	unref();
	copy_data(other);
	copy_refcount(other);
	ref();
	return *this;
}
Пример #27
0
main(void)
{
    
    set_eflags();
    
    /* Define the kernel segment registers  and a stack to execute the 'main' code */
    // It is necessary to use a global static array for the stack, because the
    // compiler will know its final memory location. Otherwise it will try to use the
    // 'ds' register to access the address... but we are not ready for that yet
    // (we are still in real mode).
    set_seg_regs(__KERNEL_DS, __KERNEL_DS, (DWord) &protected_tasks[5]);
    
    printk("Kernel Loaded!    ");
    
    /* Initialize hardware data */
    setGdt(); /* Definicio de la taula de segments de memoria */
    setIdt(); /* Definicio del vector de interrupcions */
    setTSS(); /* Definicio de la TSS */
    
    /* Initialize Memory */
    init_mm();
    
    /* Initialize an address space to be used for the monoprocess version of ZeOS */
    
    monoprocess_init_addr_space(); /* TO BE DELETED WHEN ADDED THE PROCESS MANAGEMENT CODE TO BECOME MULTIPROCESS */
    
    /* Initialize Scheduling */
    init_sched();
    
    /* Initialize idle task  data */
    init_idle();
    /* Initialize task 1 data */
    init_task1();

    /* Initialize semaphores */
    init_semaphores();
    
    /* Move user code/data now (after the page table initialization) */
    copy_data((void *) KERNEL_START + *p_sys_size, usr_main, *p_usr_size);
    
    
    printk("Entering user mode...");
    
    enable_int();
    /*
     * We return from a 'theorical' call to a 'call gate' to reduce our privileges
     * and going to execute 'magically' at 'usr_main'...
     */
    return_gate(__USER_DS, __USER_DS, USER_ESP, __USER_CS, L_USER_START);
    
    /* The execution never arrives to this point */
    return 0;
}
Пример #28
0
static enum resp_states send_data_in(struct rxe_qp *qp, void *data_addr,
				     int data_len)
{
	int err;

	err = copy_data(qp->pd, IB_ACCESS_LOCAL_WRITE, &qp->resp.wqe->dma,
			data_addr, data_len, to_mem_obj, NULL);
	if (unlikely(err))
		return (err == -ENOSPC) ? RESPST_ERR_LENGTH
					: RESPST_ERR_MALFORMED_WQE;

	return RESPST_NONE;
}
Пример #29
0
void copy_data (void *dst, void *src,
        int idim,
        int ndim,
        uint64_t* size_in_dset,
        uint64_t* ldims,
        const uint64_t * readsize,
        uint64_t dst_stride,
        uint64_t src_stride,
        uint64_t dst_offset,
        uint64_t src_offset,
        uint64_t ele_num,
        int      size_of_type,
        enum ADIOS_FLAG change_endiness,
        enum ADIOS_DATATYPES type
        )
{
    unsigned int i, j;
    uint64_t dst_offset_new=0;
    uint64_t src_offset_new=0;
    uint64_t src_step, dst_step;
    if (ndim-1==idim) {
        for (i=0;i<size_in_dset[idim];i++) {
            memcpy ((char *)dst + (i*dst_stride+dst_offset)*size_of_type,
                    (char *)src + (i*src_stride+src_offset)*size_of_type,
                    ele_num*size_of_type);
            if (change_endiness == adios_flag_yes) {
                change_endianness ((char *)dst + (i*dst_stride+dst_offset)*size_of_type, 
                                   ele_num*size_of_type, type);
            }
        }
        return;
    }

    for (i = 0; i<size_in_dset[idim];i++) {
        // get the different step granularity 
        // for each different reading pattern broke
        src_step = 1;
        dst_step = 1;
        for (j = idim+1; j <= ndim-1;j++) {
            src_step *= ldims[j];
            dst_step *= readsize[j];
        }
        src_offset_new =src_offset + i * src_stride * src_step;
        dst_offset_new = dst_offset + i * dst_stride * dst_step;
        copy_data ( dst, src, idim+1, ndim, size_in_dset,
                ldims,readsize,
                dst_stride, src_stride,
                dst_offset_new, src_offset_new,
                ele_num, size_of_type, change_endiness, type);
    }
}
Пример #30
0
void single_test(const int n, const double alpha, reconstruct r, complex_mesh_func cmf, err_t *err)
{
	data_t d, nd;
	integrate(n, alpha, r, cmf, &d);
	save_data("bis2.txt", &d);
	copy_data(&d, &nd);
	initial_sin4(T, &nd);
	save_data("none.txt", &d);
	err->l1 = L1(&d, &nd);
	err->l2 = L2(&d, &nd);
	err->linf = Linf(&d, &nd);
	free_data(&d, 1);
	free_data(&nd, 1);
}