Example #1
0
LoopInvariantCodeMotion::LoopInvariantCodeMotion(ShortLoopOptimizer *slo, GlobalValueNumbering* gvn, BlockBegin* loop_header, BlockList* loop_blocks)
  : _gvn(gvn), _short_loop_optimizer(slo) {

  TRACE_VALUE_NUMBERING(tty->print_cr("using loop invariant code motion loop_header = %d", loop_header->block_id()));
  TRACE_VALUE_NUMBERING(tty->print_cr("** loop invariant code motion for short loop B%d", loop_header->block_id()));

  BlockBegin* insertion_block = loop_header->dominator();
  if (insertion_block->number_of_preds() == 0) {
    return;  // only the entry block does not have a predecessor
  }

  assert(insertion_block->end()->as_Base() == NULL, "cannot insert into entry block");
  _insertion_point = insertion_block->end()->prev();
  _insert_is_pred = loop_header->is_predecessor(insertion_block);

  BlockEnd *block_end = insertion_block->end();
  _state = block_end->state_before();

  if (!_state) {
    // If, TableSwitch and LookupSwitch always have state_before when
    // loop invariant code motion happens..
    assert(block_end->as_Goto(), "Block has to be goto");
    _state = block_end->state();
  }

  // the loop_blocks are filled by going backward from the loop header, so this processing order is best
  assert(loop_blocks->at(0) == loop_header, "loop header must be first loop block");
  process_block(loop_header);
  for (int i = loop_blocks->length() - 1; i >= 1; i--) {
    process_block(loop_blocks->at(i));
  }
}
Example #2
0
void accept_client(void) {
	char buffer[1024];
	struct sockaddr_in cli_addr;
	int n;
	int client;
	socklen_t clilen = sizeof(struct sockaddr_in);

	/* Accept a client: */
	client = accept(s, (struct sockaddr *)&cli_addr, &clilen);

	if(client < 0) {
		warn("Error on accept.");
		return;
	}

	ip4_t r_addr = {cli_addr.sin_addr.s_addr};
	printf("Got client from %d.%d.%d.%d.\n", r_addr.components.p1, r_addr.components.p2, r_addr.components.p3, r_addr.components.p4);

	/* Read data from the client: */
	do {
		bzero(buffer, 1024);
		n = read(client, buffer, 1023);

		if(n < 0) {
			warn("Error reading from socket; breaking connection.");
			close(client);
			return;
		}

		process_block(buffer, n);
	} while(n == 1023);

	process_block(NULL, 0);

	printf("\n");

	/* Write data to the client: */
	const char * output = "HTTP/1.1 200 OK\nContent-Type: text/html\n\n";
	n = write(client, output, strlen(output));

	if(n < 0) {
		warn("Error writing to socket; breaking connection.");
		close(client);
		return;
	}

	if(output_file(client, "public/index.html")) {
		close(client);
		return;
	}

	/* Close the connection: */
	close(client);
}
Example #3
0
void
pdfout_text_get_page (FILE *stream, fz_context *ctx,
		      pdf_document *doc, int page_number)
{
  fz_stext_sheet *sheet;
  fz_stext_page *text;

  sheet = fz_new_stext_sheet (ctx);

  text = fz_new_stext_page_from_page_number (ctx, &doc->super, page_number,
					     sheet, 0);
  
  /* printf ("in pdfout_text_get_page, page_number: %d, page->len: %d\n", */
  /* 	  page_number, text->len); */

  for (int i = 0; i < text->len; ++i)
    {
      fz_page_block *block = &text->blocks[i];
      if (block->type == FZ_PAGE_BLOCK_TEXT)
	process_block (ctx, stream, block->u.text);
    }
  
  fprintf (stream, "\f\n");

  /* cleanup */
  fz_drop_stext_page (ctx, text);
  fz_drop_stext_sheet (ctx, sheet);
}
Example #4
0
File: sha1.c Project: 0xe/win-sshd
unsigned char *sha1(const unsigned char *data, unsigned int len) {
	sha1_ctx *ctx = CRYPTO_MALLOC(sizeof(*ctx));
	char *hash = CRYPTO_MALLOC(20);
	int i;

	ctx->overflow = 0;
	ctx->data = data;
	ctx->len = len;
	ctx->datalen = len * 8;
	ctx->next = data;
	ctx->H[0] = 0x67452301;
	ctx->H[1] = 0xEFCDAB89; 
	ctx->H[2] = 0x98BADCFE;
	ctx->H[3] = 0x10325476;
	ctx->H[4] = 0xC3D2E1F0;
	do {
          process_block(ctx);
	} while (ctx->len > 0);
	for (i = 0; i < 5; i++) {
          unsigned int l = long_swap(ctx->H[i]);
          memcpy(hash + i*sizeof(unsigned int), (void *)&l, sizeof(unsigned int));
	}
	CRYPTO_FREE(ctx);
	return hash;
}
Example #5
0
static bool read_block_msg(struct p2p_message *msg, int64_t fpos)
{
	/* unknown records are invalid */
	if (strncmp(msg->hdr.command, "block",
		    sizeof(msg->hdr.command)))
		return false;

	bool rc = false;

	struct bp_block block;
	bp_block_init(&block);

	struct const_buffer buf = { msg->data, msg->hdr.data_len };
	if (!deser_bp_block(&block, &buf)) {
		fprintf(plog, "brd: block deser fail\n");
		goto out;
	}
	bp_block_calc_sha256(&block);

	if (!bp_block_valid(&block)) {
		fprintf(plog, "brd: block not valid\n");
		goto out;
	}

	rc = process_block(&block, fpos);

out:
	bp_block_free(&block);
	return rc;
}
Example #6
0
void cpp_from_isl::process_node(isl_ast_node *node)
{
    auto type = isl_ast_node_get_type(node);
    switch(type)
    {
    case isl_ast_node_for:
        process_for(node); break;
    case isl_ast_node_if:
        process_if(node); break;
    case isl_ast_node_block:
        process_block(node); break;
    case isl_ast_node_user:
        process_user(node); break;
    case isl_ast_node_mark:
    {
        // TODO: label the stmt?
        auto marked_node = isl_ast_node_mark_get_node(node);
        process_node(marked_node);
        isl_ast_node_free(marked_node);
        break;
    }
    default:
        throw error("Unexpected AST node type.");
    }
}
Example #7
0
/* ============================== Process Associated Data =================================*/
static void process_AD(
	block W, block Delta_1, const block npub, block param, 
	const u8 *ad, u64 adlen) {	

	block Delta_2, blk, result;
	u8 Is_complete = 1, ozs[16];
	int i; for(i=1; i<16; i++){ozs[i]=0x00;} ozs[0] = 0x80; 

	

	/* ===== make the first block blk based on npub and param ===== */
	load_block(blk, npub, param, 8, 8);
	
	while(1){ 
		
		/* ============= Process the current Block ==================== */
		process_block(Delta_1, Delta_2, result, blk, W, Is_complete, ENCRYPT, 0, AD);
				
		/* === Compute the next Block and updating the pointers and counters ===*/
		if(adlen==0) break; 
		
		else if(adlen <= 16) {
			load_block(blk, ad, ozs, adlen, 16-adlen); 
			if(adlen != 16) Is_complete = 0;
			adlen = 0; 
		}

		else {load_block(blk, ad, ozs, 16, 0); ad +=16; adlen -=16;}
	}

}
Example #8
0
//----------------------------------------------------------------------------------------------------//
//  @func - sys_sem_wait_x
//! @desc
//!   Semaphore wait operation
//!   - Decrement semaphore value
//!   - If value < 0, block
//! @param
//!   - sem is the semaphore reference
//! @return
//!   - 0 on success, -1 on failure
//!     errno set to,
//!     EINVAL - If the semaphore identifier does not refer to a valid semaphore
//!     EIDRM  - If the semaphore was removed forcibly
//! @note
//!   - Renamed away from sys_sem_wait because it conflicts with functions in LWIP.
//----------------------------------------------------------------------------------------------------//
int sys_sem_wait_x (sem_t* sem)
{
    sem_info_t* seminfo = get_sem_by_semt (sem);
    if (seminfo == NULL) {
        kerrno = EINVAL;
	return -1;
    }

    seminfo->sem_value-- ;                                              // Decrement the resource count
    if (seminfo->sem_value < 0)                                         // If resource unavailable
	process_block (&(seminfo->sem_wait_q), PROC_WAIT);

    // Return here on unblock

    // Special. Not part of posix specification. If the semaphore was force_destroy'ed
    // then the process has not really acquired the semaphore when it was unblocked,
    // but rather it is in an interrupted situation. Signal error in this case

    if (seminfo->sem_id == -1) {                                         // If sem invalidated by now
        kerrno = EIDRM;
	return -1;
    }

    return 0 ;
}
Example #9
0
//----------------------------------------------------------------------------------------------------//
//  @func - sys_pthread_join
//! @desc
//!   Suspend current thread till target thread terminates. Then completely detach target thread.
//!   - Verify target is present and is joinable
//!   - Block onto target's join queue
//!   - When unblocked, if thread not already detached, detach it
//!   - if retval is not NULL, then store target's return value in *retval.
//! @param
//!   - target is the thread to join with
//!   - retval is the location to store return value of target thread.
//! @return
//!   - Return 0 on success and return value of target thread in location referenced by retval.
//!   - Return ESRCH, EINVAL as appropriate
//! @note
//!   - none
//----------------------------------------------------------------------------------------------------//
int sys_pthread_join (pthread_t target, void **retval)
{
    pthread_info_t *target_info = pthread_get_info (target);
    pthread_t cur  = sys_pthread_self ();
    pthread_info_t *self = pthread_get_info (cur);

    if (target_info == NULL)
        return ESRCH;

    // @note - Can possibly detect deadlocks here
    if (target_info->state == PTHREAD_STATE_ALIVE) {
        if (target_info->join_thread != NULL)                   // Some other thread already waiting to join
            return EINVAL;                                      // Therefore invalid to join with this target

        target_info->join_thread = self;                        // Block and yield execution to some other context
        process_block (&(target_info->joinq), PROC_WAIT);       // Indicate that self wants to join with target.

        if (retval != NULL)
            *retval = target_info->retval;
    } else if (target_info->state == PTHREAD_STATE_DETACHED)    // Can potentially return success here.
        return ESRCH;                                           // POSIX is not specific about behavior on multiple joins to an already terminated thread.

    if (target_info->state != PTHREAD_STATE_DETACHED)  {        // Target thread already in state PTHREAD_STATE_EXIT. Detach target thread.
        if (retval != NULL)                                     // Thread already detached if detachstate was PTHREAD_STATE_DETACHED,
            *retval = target_info->retval;
        process_invalidate (target_info->parent);               // Clear up corresponding parent structure
        invalidate_thread_info (target_info);
    }

    return 0; // Success
}
Example #10
0
inline void sha1::process_byte(cvc4_uchar8 byte)
{
    block_[block_byte_index_++] = byte;
    ++byte_count_;
    if (block_byte_index_ == 64) {
        block_byte_index_ = 0;
        process_block();
    }
}
Example #11
0
File: a32.c Project: jjdmol/LOFAR
int parse_stream (FILE *stream, void *resblock)
{
  char buffer[BLOCKSIZE + 72];
  size_t sum;


  /* Iterate over full file contents.  */
  while (1)
    {
      /* We read the file in blocks of BLOCKSIZE bytes.  One call of the
         computation function processes the whole buffer so that with the
         next round of the loop another block can be read.  */
      size_t n;
      sum = 0;

      /* Read block.  Take care for partial reads.  */
      while (1)
	{
	  n = fread (buffer + sum, 1, BLOCKSIZE - sum, stream);

	  sum += n;

	  if (sum == BLOCKSIZE)
	    break;

	  if (n == 0)
	    {
	      /* Check for the error flag IFF N == 0, so that we don't
	         exit the loop after a partial read due to e.g., EAGAIN
	         or EWOULDBLOCK.  */
	      if (ferror (stream))
		return 1;
	      goto process_partial_block;
	    }

	  /* We've read at least one byte, so ignore errors.  But always
	     check for EOF, since feof may be true even though N > 0.
	     Otherwise, we could end up calling fread after EOF.  */
	  if (feof (stream))
	    goto process_partial_block;
	}

      /* Process buffer with BLOCKSIZE bytes.  Note that
         BLOCKSIZE % 64 == 0
       */
      process_block (buffer, BLOCKSIZE);
    }

process_partial_block:

  /* Process any remaining bytes.  */
  if (sum > 0)
    process_bytes (buffer, sum);

  return 0;
}
static int
process_conf(struct sc_profile *profile, scconf_context *conf)
{
	struct state	state;

	memset(&state, 0, sizeof(state));
	state.filename = conf->filename;
	state.profile = profile;
	return process_block(&state, &root_ops, "root", conf->root);
}
Example #13
0
         file_encoder(const encoder_type& encoder,
                      const std::string& input_file_name,
                      const std::string& output_file_name)
         {
            std::size_t remaining_bytes = schifra::fileio::file_size(input_file_name);
            if (remaining_bytes == 0)
            {
               std::cout << "reed_solomon::file_encoder() - Error: input file has ZERO size." << std::endl;
               return;
            }

            std::ifstream in_stream(input_file_name.c_str(),std::ios::binary);
            if (!in_stream)
            {
               std::cout << "reed_solomon::file_encoder() - Error: input file could not be opened." << std::endl;
               return;
            }

            std::ofstream out_stream(output_file_name.c_str(),std::ios::binary);
            if (!out_stream)
            {
               std::cout << "reed_solomon::file_encoder() - Error: output file could not be created." << std::endl;
               return;
            }

            std::memset(data_buffer_,0,sizeof(data_buffer_));
            std::memset(fec_buffer_ ,0,sizeof(fec_buffer_ ));

            while (remaining_bytes >= data_length)
            {
               process_block(encoder,in_stream,out_stream,data_length);
               remaining_bytes -= data_length;
            }

            if (remaining_bytes > 0)
            {
               process_block(encoder,in_stream,out_stream,remaining_bytes);
            }

            in_stream.close();
            out_stream.close();
         }
Example #14
0
File: cmac.c Project: bk2204/drew
static int cmac_update(drew_mac_t *ctx, const uint8_t *data, size_t len)
{
	struct cmac *c = ctx->ctx;
	const uint8_t *in = data;

	if (len == 0)
		return 0;

	c->nonzero_len = true;

	if (c->boff) {
		const size_t b = MIN(c->blksize - c->boff, len);
		memcpy(c->buf+c->boff, in, b);
		if ((c->boff += b) == c->blksize) {
			if (len != b) {
				process_block(c, c->buf);
				c->boff = 0;
			}
			else
				c->boff = 16;
		}
		len -= b;
		in += b;
	}

	/* The last block must be treated specially, so make sure that this isn't it
	 * by ensuring that there's at least one more byte than the block size.
	 */
	while (len >= c->blksize+1) {
		process_block(c, in);
		len -= c->blksize;
		in += c->blksize;
	}

	if (len) {
		memcpy(c->buf, in, len);
		c->boff = len;
	}

	return 0;
}
Example #15
0
bool OOBase::Environment::get_current(env_table_t& tabEnv)
{
	wchar_t* env = GetEnvironmentStringsW();
	if (!env)
		return GetLastError() == ERROR_SUCCESS;

	int err = process_block(env,tabEnv);

	FreeEnvironmentStringsW(env);

	return (err == ERROR_SUCCESS);
}
Example #16
0
int OOBase::Environment::get_user(HANDLE hToken, env_table_t& tabEnv)
{
	LPVOID lpEnv = NULL;
	if (!CreateEnvironmentBlock(&lpEnv,hToken,FALSE))
		return GetLastError();

	int err = process_block(static_cast<wchar_t*>(lpEnv),tabEnv);
		
	if (lpEnv)
		DestroyEnvironmentBlock(lpEnv);

	return err;
}
/*
 * Process an option block
 */
static int
process_option(struct state *cur, struct block *info,
		const char *name, scconf_block *blk)
{
	sc_profile_t	*profile = cur->profile;
	int		match = 0, i;

	for (i = 0; profile->options[i]; i++)
		match |= !strcmp(profile->options[i], name);
	if (!match && strcmp("default", name))
		return 0;
	return process_block(cur, info, name, blk);
}
/*
 * Process a key block
 */
static int
process_key(struct state *cur, struct block *info,
		const char *name, scconf_block *blk)
{
	unsigned int	type, id;
	struct state	state;

	if (get_authid(cur, name, &type, &id))
		return 1;

	init_state(cur, &state);
	state.key = new_key(cur->profile, type, id);
	return process_block(&state, info, name, blk);
}
static int
process_pin(struct state *cur, struct block *info,
		const char *name, scconf_block *blk)
{
	struct state	state;
	unsigned int	id;

	if (map_str2int(cur, name, &id, pinIdNames))
		return 1;

	init_state(cur, &state);
	state.pin = new_pin(cur->profile, id);

	return process_block(&state, info, name, blk);
}
static int
process_ef(struct state *cur, struct block *info,
		const char *name, scconf_block *blk)
{
	struct state	state;

	init_state(cur, &state);
	if (name == NULL) {
		parse_error(cur, "No name given for EF object.");
		return 1;
	}
	if (!(state.file = new_file(cur, name, SC_FILE_TYPE_WORKING_EF)))
		return 1;
	return process_block(&state, info, name, blk);
}
Example #21
0
string RVRecursiveFunctionLocator::nextRecursiveFunction()
{
	for(; currStmnt; currStmnt = currStmnt->next) {
		if (currStmnt->isFuncDef()){
			currName = ((FunctionDef*) currStmnt)->FunctionName()->name;
			wasFound = false;
			process_block((FunctionDef*) currStmnt);
			//if (wasFound){
			if (true){
				currStmnt = currStmnt->next;
				return currName;
			}
		}
	}
	return "";
}
Example #22
0
void Encode::run()
{
    Stopwatch stopwatch;

    while (next_block())
        process_block();

    stopwatch.stop("[runtime]");

    printf("\n");
    vmpeak(stdout);

    printf("\n");
    printf("output.nomatch      : %zu (%.2f%%)\n", output.nomatch, (output.nomatch/(double)input.nreads)*100.0);
    printf("output.fullmatch    : %zu (%.2f%%)\n", output.nfullmatch, (output.nfullmatch/(double)input.nreads)*100.0);
    printf("output.nrcomplement : %zu (%.2f%%)\n", output.nrcomplement, (output.nrcomplement/(double)input.nreads)*100.0);
    printf("output.nbits        : %zu\n", output.nbits);
    printf("output.nbytes       : %zu (%.2f MB)\n", output.nbits / 8, output.nbits / 8.0 / 1e6);
    printf("output.compression  : %.2f%%\n", ((output.nbits/8.0)/input.nbytes)*100.0);
    printf("\n");
}
Example #23
0
File: cmac.c Project: bk2204/drew
static int cmac_final(drew_mac_t *ctx, uint8_t *digest, int flags)
{
	struct cmac *c = ctx->ctx;

	if (!c->nonzero_len) {
		memset(c->buf+1, 0, c->blksize-1);
		c->buf[c->boff] = 0x80;
		xor_aligned2(c->buf, c->k2, BUFFER_SIZE);
	}
	else if (c->boff == c->blksize) {
		xor_aligned2(c->buf, c->k1, BUFFER_SIZE);
	}
	else {
		memset(c->buf+c->boff, 0, c->blksize-c->boff);
		c->buf[c->boff] = 0x80;
		xor_aligned2(c->buf, c->k2, BUFFER_SIZE);
	}
	process_block(c, c->buf);
	memcpy(digest, c->hash, c->taglen);

	return 0;
}
static int
process_tmpl(struct state *cur, struct block *info,
		const char *name, scconf_block *blk)
{
	struct state	state;
	sc_template_t	*tinfo;
	sc_profile_t	*templ;

	if (name == NULL) {
		parse_error(cur, "No name given for template.");
		return 1;
	}

	templ = (sc_profile_t *) calloc(1, sizeof(*templ));
	if (templ == NULL) {
		parse_error(cur, "memory allocation failed");
		return 1;
	}
		
	templ->cbs = cur->profile->cbs;

	tinfo = (sc_template_t *) calloc(1, sizeof(*tinfo));
	if (tinfo == NULL) {
		parse_error(cur, "memory allocation failed");
		free(templ);
		return 1;
	}
	tinfo->name = strdup(name);
	tinfo->data = templ;

	tinfo->next = cur->profile->template_list;
	cur->profile->template_list = tinfo;

	init_state(cur, &state);
	state.profile = tinfo->data;
	state.file = NULL;

	return process_block(&state, info, name, blk);
}
Example #25
0
//----------------------------------------------------------------------------------------------------//
//  @func - sys_sem_timedwait
//! @desc
//!   Semaphore timedwait operation
//!   - Decrement semaphore value
//!   - If value < 0, block with a timeout, as specified by the second parameters 'ms'
//! @param
//!   - sem is the semaphore reference
//!   - ms is the amount of time to be blocked on the semaphore in milliseconds
//! @return
//!   - 0 on success, -1 on failure
//!     errno set to,
//!     EINVAL - If the semaphore identifier does not refer to a valid semaphore
//!     ETIMEDOUT - The semaphore could not be locked before the specified timeout expired.
//!     EIDRM - If the semaphore was forcibly removed from the system
//! @note
//!   - Depends on CONFIG_TIME being true
//----------------------------------------------------------------------------------------------------//
int sys_sem_timedwait (sem_t* sem, unsigned int ms)
{
    sem_info_t* seminfo = get_sem_by_semt (sem);
    process_struct *self;

    if (seminfo == NULL) {
        kerrno = EINVAL;
	return -1;
    }

    seminfo->sem_value-- ;                                              // Decrement the resource count
    if (seminfo->sem_value < 0)  {                                      // If resource unavailable
        self = current_process;
        add_tmr (self->pid, ms);                                        // Add a timer for self
        process_block (&(seminfo->sem_wait_q), PROC_TIMED_WAIT);

                                                                        // Return here on unblock
        if (self->timeout) {                                            // Timeout during semaphore wait. Return with error
            seminfo->sem_value++;                                       // Restore sem value
            self->timeout = 0;
            kerrno = ETIMEDOUT;
            return -1;
        } else {
            remove_tmr (self->pid);                                     // We managed to acquire the semaphore. Remove associated timer
        }
    }

    // Special. Not part of posix specification. If the semaphore was force_destroy'ed
    // then the process has not really acquired the semaphore when it was unblocked,
    // but rather it is in an interrupted situation. Signal error in this case

    if (seminfo->sem_id == -1) {                                        // If sem invalidated by now
        kerrno = EIDRM;
	return -1;
    }

    return 0 ;
}
Example #26
0
//----------------------------------------------------------------------------------------------------//
//  @func - pthread_mutex_lock_basic
//! @desc
//!   Lock a mutex
//!   - If mutex has only been statically initialized, initialize with a call to pthread_mutex_init
//!   - If mutex is not already locked, lock it.
//!   - If mutex is locked, then if trylock is true, then return immediately with EBUSY. Block onto
//!     mutex wait queue if trylock is not true.
//!   - When the call returns the mutex is locked by the process that made the call
//!   - Ownership checks are performed if mutex type is PTHREAD_MUTEX_RECURSIVE
//!   - Recursive locks, cause the mutex lock count to be incremented.
//! @param
//!   - mutex is the pointer to mutex identifier
//!   - trylock indicates if lock should just be tried for instead of committing to acquire the lock
//! @return
//!   - Returns 0 on success and the mutex in a locked state.
//!   - Returns EBUSY if mutex locked and trylock requested. -1 on unhandled errors.
//! @note
//!   - None
//----------------------------------------------------------------------------------------------------//
int pthread_mutex_lock_basic (pthread_mutex_t *mutex, int trylock)
{
    unsigned int i;

    if ((mutex == NULL) ||                                                                      // Verify parameters
        ((*mutex != PTHREAD_MUTEX_INITIALIZER) &&
         ((*mutex < 0) || (*mutex >= MAX_PTHREAD_MUTEX))))
        return EINVAL;
    
    if (*mutex == PTHREAD_MUTEX_INITIALIZER)  {                                                 // Initialize statically allocated mutex lock
	if (sys_pthread_mutex_init(mutex, &default_mutex_attr) != 0)
	    return -1;                                                                          // Undefined error code
    }
    
    i = (unsigned int)*mutex;
    if (pthread_mutex_heap[i].is_allocated != 1)
        return EINVAL;

    while (pthread_mutex_heap[i].locked) {
        if ((pthread_mutex_heap[i].attr.type != PTHREAD_MUTEX_RECURSIVE ||                      // Suspend this request only if either of 
             pthread_mutex_heap[i].owner != current_pid)) {                                     //    a. MUTEX type is not recursive 
            if (trylock)                                                                        //    b. Requestor is not owner
                return EBUSY;                                                                   // or both are true.
            else
                process_block (&(pthread_mutex_heap[i].mutex_wait_q), PROC_WAIT);                            
        } else
            break;
    }

    
    if (pthread_mutex_heap[i].attr.type == PTHREAD_MUTEX_RECURSIVE)     
        pthread_mutex_heap[i].locked++;                                                         // Lock with lock count incremented
    else
        pthread_mutex_heap[i].locked = 1;                                                       // Simple lock            
    
    pthread_mutex_heap[i].owner = current_pid;
    return 0;
}
Example #27
0
static int comment_43_uncompress(FILE *infp, FILE *outfp, int skip_magic)
{
  block_data_t *block_data = malloc(sizeof(block_data_t));
  size_t work_len = snappy_max_compressed_length(UINT16_MAX); /* length of worst case */
  char *work = malloc(work_len);
  int err = 1;
  stream_state_t state = skip_magic ? PROCESSING_STATE : INITIAL_STATE;

  if (block_data == NULL || work == NULL) {
    print_error("out of memory\n");
    goto cleanup;
  }

  while (state != ERROR_STATE) {
    switch (read_block(infp, block_data)) {
    case EOF:
      if (state == END_OF_STREAM_STATE) {
        err = 0; /* success */
        goto cleanup;
      }
      /* FALLTHROUGH */
    case TOO_SHORT_DATA_BLOCK:
      if (feof_unlocked(infp)) {
        print_error("Unexpected end of file\n");
      } else {
        print_error("Failed to read a file: %s\n", strerror(errno));
      }
      goto cleanup;
    }
    state = process_block(outfp, state, block_data, work, work_len);
  }
 cleanup:
  free(block_data);
  free(work);
  return err;
}
Example #28
0
inline void sha1::process_bytes(void const* buffer, std::size_t byte_count)
{
    unsigned char const* b = static_cast<unsigned char const*>(buffer);
    process_block(b, b+byte_count);
}
Example #29
0
static int process_data(server *srv, connection *con, plugin_data *p,
			buffer *filename, chunkqueue *cq, off_t range_start)
{
	int err;
	size_t len;
	//off_t *abs_off;
	vhd_state_t *state;
	vhd_context_t *vhd;

	err = 0;
	state = &p->state;
	vhd = &state->vhd;
	//abs_off = range_start + con->range_offset;
	//abs_off = state->abs_off;
	DEBUGLOG("so", "Absolute Offset", state->abs_off);
	DEBUGLOG("sd", "Current Virtual Block = ", state->curr_virt_blk);
	if (state->curr_virt_blk != -1) {
		DEBUGLOG("s", "Process Block");
		err = process_block(srv, cq, state, &(state->abs_off));
		goto done;
	}

	if (state->abs_off < 0 + sizeof(vhd_footer_t)) {
		err = get_footer(srv, cq, state, &(state->abs_off));
		goto done;
	}

	if (((off_t)state->abs_off) < vhd->footer.data_offset + sizeof(vhd_header_t)) {
		err = get_header(srv, cq, state, &(state->abs_off));
		goto done;
	}

	if (((off_t)state->abs_off) < vhd->header.table_offset + state->bat_buf_size) {
		err = get_bat(srv, cq, state, &(state->abs_off));
		if (err)
			goto done;
		if (state->vhd_ready)
			err = prepare_for_write(srv, state, filename, state->abs_off);
		goto done;
	}

	if (state->blocks_written < state->blocks_allocated) {
		LOG("sdd", "BUG!", state->blocks_written,
				state->blocks_allocated);
		err = -EINVAL;
		goto done;
	}

	// TODO: we could actually validate the primary footer at the end
	len = chunkqueue_avail(cq);
	DEBUGLOG("sd", "Discarding the remainder", len);
	discard_bytes(srv, cq, len);
	state->abs_off += len;

	if (state->zero_unalloc) {
		err = zero_unallocated(srv, state);
		state->zero_unalloc = 0;
	}

done:
	con->range_offset = state->abs_off - range_start;
	return err;
}
Example #30
0
int crypto_aead_encrypt(
unsigned char *c,unsigned long long *clen,
const unsigned char *m,unsigned long long mlen,
const unsigned char *ad,unsigned long long adlen,
const unsigned char *nsec,
const unsigned char *npub,
const unsigned char *k
)
{
	u8 param[]={0x06,0,0,0,0x80,0,0,0}; 
	
	block L, W, Delta_0, Delta_1, Delta_2, blk, result, CS;
	int i; u8 zeroes[16], ozs[16], blen = 16, Is_final = 0, Is_complete =1;
	unsigned long long cnt;
	for(i=0; i<16; i++)	{zeroes[i]=0x00;}   	
	for(i=1; i<16; i++)	{ozs[i]=0x00;} ozs[0] = 0x80; 	


	cnt = (8+mlen-1)/16 + 1;
	*clen = (cnt +1)* 16 + 1;

	if((mlen+8)%16 == 0) 
		c[*clen-1] = 0x00; 
	else 
		c[*clen-1] = 0x01; 

	key_schedule(k);

	/* ==========  Generate the Masks =========== */
	AES(6, ENCRYPT, blk, zeroes, &aes_key1);
	AES(6, ENCRYPT, L, blk, &aes_key1);

	mult_3(Delta_0, L); 
	mult_inv2(Delta_0, Delta_0); 

	mult_inv2(Delta_1, L); 	

	mult_3(Delta_2, L); 
	mult_3(Delta_2, Delta_2); 
	mult_inv2(Delta_2, Delta_2);

	/* ======  Process Associated Data ======== */
	for(i=0; i<16; i++)
		W[i]=0x00;
	process_AD(W, Delta_0, npub, param, ad, adlen);


	/* ================  Process Successive Message Blocks ==================== */

	
	/* ====== Process the first Message block, whose first 8 byte is the secret message number ===== */
	
	if(mlen < 8){ Is_complete = 0; }
	if(mlen <= 8) { blen = 8 + mlen; }
	load_block(blk, nsec, m, 8, blen-8); copy_block(CS, blk); 
	process_block(Delta_1, Delta_2, result, blk, W, Is_complete, ENCRYPT, Is_final, MESSAGE);
	
	store_bytes(c, result, 0, 15); c +=16;
	if(mlen >= 8)  {mlen -= 8; m +=8;}
	else mlen = 0;

	/* ============= Process Message blocks ================== */
	while(mlen > 0){
		if(mlen >= 16){
			load_block(blk, m, ozs, 16, 0);
			if(mlen == 16) {xor_block(blk, blk, CS); }
			else xor_block(CS, CS, blk);
			blen = 16; mlen -= 16; m+=16; 
		}
		else 	{Is_complete = 0; blen = mlen; mlen = 0; 
			load_block(blk, m, ozs, blen, 0); xor_block(blk, CS, blk);
			
		}	
		process_block(Delta_1, Delta_2, result, blk, W, Is_complete, ENCRYPT, Is_final, MESSAGE); 
		store_bytes(c, result, 0, 15); c +=16;
		
	}

	/* ================ Process checksum block ====================== */
	process_block(Delta_1, Delta_2, result, blk, W, 1, ENCRYPT, 1, MESSAGE); 
	store_bytes(c, result, 0, 15);
	return 0;
}