示例#1
1
static ssh_session create_ssh_connection(const char* hostname, const unsigned int port, const char* username,
	const char* password, const char* sshkey_path, const char* sshkey_passphrase)
{
	ssh_session sshs;

	/* Open session and set options */
	sshs = ssh_new();
	if (sshs == NULL) {
		errmsg_print("Can't create ssh session");
		return NULL;
	}

	if (!hostname)
		return NULL;

	if (ssh_options_set(sshs, SSH_OPTIONS_HOST, hostname)) {
		errmsg_print("Can't set the hostname: %s\n", hostname);
		goto failure;
	}

	if (port != 0) {
		if (ssh_options_set(sshs, SSH_OPTIONS_PORT, &port)) {
			errmsg_print("Can't set the port: %d\n", port);
			goto failure;
		}
	}

	if (!username)
		username = g_get_user_name();

	if (ssh_options_set(sshs, SSH_OPTIONS_USER, username)) {
		errmsg_print("Can't set the username: %s\n", username);
		goto failure;
	}

	verbose_print("Opening ssh connection to %s@%s:%u\n", username, hostname, port);

	/* Connect to server */
	if (ssh_connect(sshs) != SSH_OK) {
		errmsg_print("Error connecting to %s@%s:%u (%s)\n", username, hostname, port,
			ssh_get_error(sshs));
		goto failure;
	}

#ifdef HAVE_LIBSSH_USERAUTH_AGENT
	verbose_print("Connecting using ssh-agent...");
	/* Try to authenticate using ssh agent */
	if (ssh_userauth_agent(sshs, NULL) == SSH_AUTH_SUCCESS) {
		verbose_print("done\n");
		return sshs;
	}
	verbose_print("failed\n");
#endif

	/* If a public key path has been provided, try to authenticate using it */
	if (sshkey_path) {
		ssh_key pkey = ssh_key_new();
		int ret;

		verbose_print("Connecting using public key in %s...", sshkey_path);
		ret = ssh_pki_import_privkey_file(sshkey_path, sshkey_passphrase, NULL, NULL, &pkey);

		if (ret == SSH_OK) {
			if (ssh_userauth_publickey(sshs, NULL, pkey) == SSH_AUTH_SUCCESS) {
				verbose_print("done\n");
				ssh_key_free(pkey);
				return sshs;
			}
		}
		ssh_key_free(pkey);
		verbose_print("failed (%s)\n", ssh_get_error(sshs));
	}

	/* Try to authenticate using standard public key */
	verbose_print("Connecting using standard public key...");
	if (ssh_userauth_publickey_auto(sshs, NULL, NULL) == SSH_AUTH_SUCCESS) {
		verbose_print("done\n");
		return sshs;
	}
	verbose_print("failed\n");

	/* If a password has been provided and all previous attempts failed, try to use it */
	if (password) {
		verbose_print("Connecting using password...");
		if (ssh_userauth_password(sshs, username, password) == SSH_AUTH_SUCCESS) {
			verbose_print("done\n");
			return sshs;
		}
		verbose_print("failed\n");
	}

	errmsg_print("Can't find a valid authentication. Disconnecting.\n");

	/* All authentication failed. Disconnect and return */
	ssh_disconnect(sshs);

failure:
	ssh_free(sshs);
	return NULL;
}
示例#2
0
文件: record.c 项目: npnth/bysans
static void
session_notify_cb (ByzanzSession *session, GParamSpec *pspec, gpointer unused)
{
  const GError *error = byzanz_session_get_error (session);
  
  if (g_str_equal (pspec->name, "error")) {
    g_print (_("Error during recording: %s\n"), error->message);
    gtk_main_quit ();
    return;
  }

  if (!byzanz_session_is_encoding (session)) {
    verbose_print (_("Recording done.\n"));
    gtk_main_quit ();
  }
}
示例#3
0
static void
process_symbols(void *dcontext, char *dllname, LOADED_IMAGE *img)
{
    /* We have to specify the module via "modname!symname".
     * We must use the same modname as in full_path.
     */
# define MAX_SYM_WITH_MOD_LEN 256
    char sym_with_mod[MAX_SYM_WITH_MOD_LEN];
    size_t modoffs;
    drsym_error_t symres;
    char *fname = NULL, *c;
    search_data_t sd;

    if (drsym_init(NULL) != DRSYM_SUCCESS) {
        print("WARNING: unable to initialize symbol engine\n");
        return;
    }

    if (dllname == NULL)
        return;
    for (c = dllname; *c != '\0'; c++) {
        if (*c == '/' || *c == '\\')
            fname = c + 1;
    }
    assert(fname != NULL && "unable to get fname for module");
    if (fname == NULL)
        return;
    /* now get rid of extension */
    for (; c > fname && *c != '.'; c--)
        ; /* nothing */

    assert(c - fname < BUFFER_SIZE_ELEMENTS(sym_with_mod) && "sizes way off");
    modoffs = dr_snprintf(sym_with_mod, c - fname, "%s", fname);
    assert(modoffs > 0 && "error printing modname!symname");
    modoffs = dr_snprintf(sym_with_mod + modoffs,
                          BUFFER_SIZE_ELEMENTS(sym_with_mod) - modoffs,
                          "!%s", SYM_PATTERN);
    assert(modoffs > 0 && "error printing modname!symname");

    sd.dcontext = dcontext;
    sd.img = img;
    verbose_print("Searching \"%s\" for \"%s\"\n", dllname, sym_with_mod);
    symres = drsym_search_symbols(dllname, sym_with_mod, true, search_syms_cb, &sd);
    if (symres != DRSYM_SUCCESS)
        print("Error %d searching \"%s\" for \"%s\"\n", dllname, sym_with_mod);
    drsym_exit();
}
示例#4
0
void s_rename_all(TOPLEVEL * pr_current, NETLIST * netlist_head)
{
    RENAME * temp;
    
#if DEBUG
    s_rename_print();
#endif

    if (last_set)
    {
        for (temp = last_set->first_rename; temp; temp = temp->next)
        {
            verbose_print("R");
            s_rename_all_lowlevel(netlist_head, temp->src, temp->dest);
	}
    }
}
示例#5
0
/* Read bytes from the channel. If bytes == -1, read all data (until timeout). If outbuf != NULL, data are stored there */
static int read_output_bytes(ssh_channel channel, int bytes, char* outbuf)
{
	char chr;
	int total;
	int bytes_read;

	total = (bytes > 0 ? bytes : G_MAXINT);
	bytes_read = 0;

	while(ssh_channel_read_timeout(channel, &chr, 1, 0, 2000) > 0 && bytes_read < total) {
		verbose_print("%c", chr);
		if (chr == '^')
			return EXIT_FAILURE;
		if (outbuf)
			outbuf[bytes_read] = chr;
		bytes_read++;
	}
	return EXIT_SUCCESS;
}
示例#6
0
static void
load_and_analyze(void *dcontext, char *dllname)
{
    LOADED_IMAGE img;
    BOOL res;

    res = MapAndLoad(dllname, NULL, &img, FALSE, TRUE);
    if (!res) {
        print("Error loading %s\n", dllname);
        return;
    }
    verbose_print("mapped at "PFX" (preferred "PFX")\n",
                  img.MappedAddress, get_preferred_base(&img));
    if (!list_usercalls)
        process_exports(dcontext, dllname, &img);
    if (list_syscalls || list_usercalls)
        process_symbols(dcontext, dllname, &img);
    UnMapAndLoad(&img);
}
示例#7
0
文件: eval.c 项目: cwbowron/BCE
int score_rook(int f, int r, int c)
{
    int o = opp(c);
    int df = abs(F(board->kings[o])-f);
    int dr = abs(R(board->kings[o])-r);
    int bonus=(7-min(df,dr))*weights[ROOK_TROPISM];
    
    verbose_print(f,r,bonus,"rook/king tropism");

    if (c == WHITE)
    {
	if (r == 6)
	{
	    bonus += weights[SEVENTH_RANK_ROOK];
	    verbose_print(f,r,weights[SEVENTH_RANK_ROOK],"seventh rank rook");
	}
    }
    else if (r == 1)
    {
	bonus += weights[SEVENTH_RANK_ROOK];
	verbose_print(f,r,weights[SEVENTH_RANK_ROOK],"seventh rank rook");
    }
    
    if (rooks[c] == -1)
    {
	rooks[c] = SQ(f,r);
    }
    else
    {
	if ((f==F(rooks[c]))||(r==R(rooks[c])))
	{
	    bonus += weights[DOUBLEDROOKS];
	    verbose_print(f,r,weights[DOUBLEDROOKS], "doubled rooks");
	}
    }
    
    if (!board->pawns[c][f+1])
    {
	bonus += weights[SEMIOPEN];
	if (!board->pawns[o][f+1])
	{
	    bonus += weights[OPENFILE];
	    verbose_print(f,r,weights[OPENFILE]+weights[SEMIOPEN],
			  "rook on open file");
	}
	else verbose_print(f,r,weights[SEMIOPEN], "rook on semi-open file");
    }
    
    return bonus;
}
示例#8
0
int Resource::seize(Arrival* arrival, int amount) {
  int status;
  // serve now
  if (room_in_server(amount, arrival->order.get_priority())) {
    insert_in_server(sim->verbose, sim->now(), arrival, amount);
    status = SUCCESS;
  }
  // enqueue
  else if (room_in_queue(amount, arrival->order.get_priority())) {
    insert_in_queue(sim->verbose, sim->now(), arrival, amount);
    status = ENQUEUE;
  }
  // reject
  else {
    if (sim->verbose) verbose_print(sim->now(), arrival->name, "REJECT");
    return REJECT;
  }

  arrival->register_entity(this);
  if (is_monitored())
    sim->record_resource(name, server_count, queue_count, capacity, queue_size);
  return status;
}
示例#9
0
void dump_crb( cop_session_t *s ){
	struct cop_crb *crb = (struct cop_crb *) s->ptrPVT;   
	int i;

	verbose_print("Dumping crb\n");
	verbose_print("crb->command_word: %02X\n", crb->ccw.value );
	verbose_print("crb->qos: %02X\n", crb->qos );
	verbose_print("crb->mt_tag: %02X\n", crb->mt_tag);
	verbose_print("crb->flags: %02X\n", crb->flags);
	verbose_print("crb->ch: %02X\n", crb->ch);
	verbose_print("crb->seq_num: %02X\n", crb->seq_num);
	verbose_print("crb->ptrCSBValue: %02X\n", crb->cop_addr_value);
	verbose_print("crb->source_DDE\n");
	verbose_print("crb->source_progress: %02X\n", crb->src_dde.pr );
	verbose_print("crb->source_countt: %02X\n", crb->src_dde.countt);
	verbose_print("crb->source_pi: %02X\n", crb->src_dde.pi );
	verbose_print("crb->source_byte_count: %02X\n", crb->src_dde.bytes );
	verbose_print("crb->ptrSD: %02X\n", crb->src_dde.data);
	verbose_print("crb->target_DDE\n");
	verbose_print("crb->target_progress: %02X\n", crb->tgt_dde.pr);
	verbose_print("crb->target_countt: %02X\n", crb->tgt_dde.countt);
	verbose_print("crb->target_pi: %02X\n", crb->tgt_dde.pi);
	verbose_print("crb->target_byte_count: %02X\n", crb->tgt_dde.bytes);
	verbose_print("crb->ptrTD: %02X\n", crb->tgt_dde.data);
	verbose_print("\n");
}
示例#10
0
int main(int argc, char *argv[])
{
	int i;
	mapped_memory_pool_t cc_pool = cop_cc_pool();
	
	FILE *test_file = fopen( "/bin/busybox", "r" );
	fseek( test_file, 0L, SEEK_END );

	size_t size = ftell(test_file), size_uncomp = 64;
	char *src = (char *)cop_malloc(cc_pool, size, 1);
	char *tgt = (char *)cop_malloc(cc_pool, size, 1);
	char *tgt_uncompressed = NULL;
	cop_session_t *session,*session_uncomp;
	size_t compressed_size, uncompressed_size;
	size_t decomp_size = 0;
	int fail = 0;

	fseek( test_file, 0L, SEEK_SET );
	fread( src, 1, size, test_file );
	fclose( test_file );

	memcpy(tgt, src, size);

	errno=0;

	session=cop_create_gzip_session(COMPLETION_STORE, size, src, size, tgt);

/* DD1 workaround */
if (gDD_version == 1) {
        session=cop_psr2_gzip_compression(session,tgt, &compressed_size);
} else {
        session=cop_commit_session(session);
}  
	CHECK_ERROR();

	if (cop_session_iscomplete(session)) {
		compressed_size=cop_get_target_output_size(session);
	}

    // now decompress and see if we get the same thing

	int max_num_chunks = 12;
	int num_chunks = max_num_chunks > compressed_size ? compressed_size : max_num_chunks;
	size_t chunk_size = (size_t)floor(compressed_size/num_chunks);
	
	session_uncomp = cop_create_gunzip_session_with_dde_list(COMPLETION_STORE,1, chunk_size, tgt, size_uncomp );
SEND_ME_FIRST:
	dump_crb(session_uncomp);
    session_uncomp = cop_commit_session(session_uncomp);
	CHECK_ERROR();
	dump_csb(session_uncomp);
    
    if( errno == 13 ){
        printf("Updating target buffer (%d)\n", size_uncomp);
		cop_comp_session_t *cdc_session = (cop_comp_session_t *) session_uncomp->data;

        cop_free(cc_pool, cdc_session->last->target_buffer);

        size_uncomp *= 2;

        cdc_session->last->target_buffer = (char *) cop_malloc( cc_pool, size_uncomp, 64 );
		cdc_session->last->size = size_uncomp;

        memset( cdc_session->last->target_buffer, 0x0, size_uncomp );

        session_uncomp = cop_gunzip_add_tgt_buffer(session_uncomp, cdc_session->last->size, cdc_session->last->target_buffer );
		
        goto SEND_ME_FIRST;	
	}
    
    if (cop_session_iscomplete(session_uncomp)) {
		uncompressed_size = cop_get_target_output_size(session_uncomp);
	}

    printf("Decompression step-1 completed %u bytes sent - uncompressed size up till now %u bytes\n",  chunk_size, uncompressed_size);
    
    for( i = 1; i  < num_chunks; i++ ){
		int first_try = 1;
        int isLast = (i + 1) == num_chunks;
       	int bsize = isLast ? compressed_size - i*chunk_size : chunk_size;      	

        session_uncomp = cop_prep_next_decompression(session_uncomp, isLast, bsize, tgt + i*chunk_size, 0, NULL );

SEND_ME:
		dump_crb(session_uncomp);
		session_uncomp = cop_commit_session(session_uncomp);
		CHECK_ERROR();
		dump_csb(session_uncomp);
        
		if( errno == 13 ){
			size_uncomp = size_uncomp < 2048 ? 2048 : size_uncomp;

			if( first_try ){ //We're just adding a new target buffer
				session_uncomp = cop_gunzip_add_dde( session_uncomp, size_uncomp );
			} else { //We haven't made any progress because our buffer is still not big enough
				cop_comp_session_t *cdc_session = (cop_comp_session_t *) session_uncomp->data;

				cop_free(cc_pool, cdc_session->last->target_buffer);

				size_uncomp = size_uncomp + 2048;

				cdc_session->last->target_buffer = (char *) cop_malloc( cc_pool, size_uncomp, 64 );
				cdc_session->last->size = size_uncomp;

				memset( cdc_session->last->target_buffer, 0x0, size_uncomp );

				session_uncomp = cop_gunzip_add_tgt_buffer(session_uncomp, cdc_session->last->size, cdc_session->last->target_buffer );		
			}

			first_try = 0;
            
			printf("[%d] Adding a new target buffer of size %u\n", i, size_uncomp);

            uncompressed_size = 0;
			goto SEND_ME;	
		} else if( errno ) {
			fail++;

			goto CLEAN;
		}
		
		if(cop_session_iscomplete(session_uncomp)) {
			uncompressed_size = cop_get_target_output_size( session_uncomp );
		}
		    
		printf("Decompression step-%d completed %d bytes sent - uncompressed size up till now %d bytes\n", (i+1), bsize, uncompressed_size);
    }

	tgt_uncompressed = (char *) malloc( uncompressed_size );
	memset( tgt_uncompressed, 0x0, uncompressed_size );

	cop_comp_copy_dde_list( session_uncomp, tgt_uncompressed, uncompressed_size );

    printf("Decompression completed. Output size is %d src data size was %d\n", uncompressed_size, size);

	if ( memcmp(src, tgt_uncompressed, uncompressed_size) != 0 ) {
		fail++;
		printf("input -> compressed -> uncompressd output are not equal\n");
        print_text( src, uncompressed_size );

        print_text( tgt_uncompressed, uncompressed_size );
	} else {
		verbose_print("Output data: \n");
		print_text( tgt_uncompressed, uncompressed_size );
	}

CLEAN:
	cop_free_comp_session(session);
	cop_free_comp_session(session_uncomp);

	cop_free(cc_pool, src);
	cop_free(cc_pool, tgt);
	
	if( tgt_uncompressed ) free(tgt_uncompressed);

	printf("=== %s: %d/%d failures ===\n", argv[0], fail, 3);
	return 0;
}
示例#11
0
/*! \brief Add nets to net table
 *
 * This function iterates over adds all
 * items found on this page looking
 * for nets and adds them individually to the net table.  Looping over
 * objects occurs here.
 *
 * \param start_obj Pointer to first object
 *
 * \todo Why do the calling semantics of this function disagree with
 *       s_table_add_toplevel_pin_items_to_pin_table()?  That function
 *       takes a GList, this one takes a pointer to OBJECT.
 */
void s_table_add_toplevel_net_items_to_net_table(OBJECT *start_obj) {
  OBJECT *o_current;
  char *temp_netname;
  int row, col;
  char *attrib_text;
  char *attrib_name;
  char *attrib_value;
  ATTRIB *a_current;
 
  /* -----  Iterate through all objects found on page  ----- */
  o_current = start_obj;
  while (o_current != NULL) {
 
    /* -----  Now process objects found on page  ----- */
    if (o_current->type == OBJ_NET) {
#if DEBUG
      fflush(stderr);
      fflush(stdout);
      printf("In s_table_add_toplevel_net_items_to_net_table, Found net on page\n");
#endif
      verbose_print(" N");
 
      /* Having found a net, we stick it into the table. */
      a_current = o_current->attribs;
      while (a_current != NULL) {
        if (a_current->object->type == OBJ_TEXT
            && a_current->object->text != NULL) {  /* found an attribute */
          /* may need to check more thoroughly here. . . . */
          attrib_text = g_strdup(a_current->object->text->string);
          attrib_name = u_basic_breakup_string(attrib_text, '=', 0);
          attrib_value = s_misc_remaining_string(attrib_text, '=', 1);
          if (strcmp(attrib_name, "netname") != 0) {
            /* Don't include "netname" */
             
            /* Get row and col where to put this attrib */
            row = s_table_get_index(sheet_head->master_net_list_head, temp_netname);
            col = s_table_get_index(sheet_head->master_net_attrib_list_head, attrib_name);
#if DEBUG
            fflush(stderr);
            fflush(stdout);
            printf("In s_table_add_toplevel_net_items_to_net_table, about to add row %d, col %d, attrib_value = %s\n",
                   row, col, attrib_value);
            printf(" . . . current address of attrib_value cell is [%p]\n", &((sheet_head->net_table)[row][col]).attrib_value);
#endif
            /* Is there a compelling reason for me to put this into a separate fcn? */
            ((sheet_head->net_table)[row][col]).row = row;
            ((sheet_head->net_table)[row][col]).col = col;
            ((sheet_head->net_table)[row][col]).row_name = g_strdup(temp_netname);
            ((sheet_head->net_table)[row][col]).col_name = g_strdup(attrib_name);
            ((sheet_head->net_table)[row][col]).attrib_value = g_strdup(attrib_value);
          }
          g_free(attrib_name);
          g_free(attrib_text);
          g_free(attrib_value);
        }
        a_current = a_current->next;
 
      }  /* while (a_current != NULL) */
      g_free(temp_netname);
 
    }    /*--- if (o_current->type == OBJ_NET)   ---*/
       
 
    o_current = o_current->next;  /* iterate to next object on page */
  }  /* while o_current != NULL */
 
  verbose_done();
 
#if DEBUG
  fflush(stderr);
  fflush(stdout);
  printf("In s_table_add_toplevel_net_items_to_net_table -- we are about to return\n");
#endif
 
}
示例#12
0
/*! \brief Add components to the component table
 *
 * This fcn iterates over adds all
 * objects found on this page looking
 * for components.  When it finds a component, it finds all component
 * attribs and sticks them in the TABLE.
 * \param obj_list pointer to GList containing objects on this page
 */
void s_table_add_toplevel_comp_items_to_comp_table (const GList *obj_list) {
  gchar *temp_uref;
  int row, col;
  gchar *attrib_text;
  gchar *attrib_name;
  gchar *attrib_value;
  const GList *o_iter;
  GList *a_iter;
  OBJECT *a_current;
  gint old_visibility, old_show_name_value;


  if (verbose_mode) {
    printf("- Starting internal component TABLE creation\n");
  }

#ifdef DEBUG
  fflush(stderr);
  fflush(stdout);
  printf("=========== Just entered  s_table_add_toplevel_comp_items_to_comp_table!  ==============\n");
#endif

  /* -----  Iterate through all objects found on page  ----- */
  for (o_iter = obj_list; o_iter != NULL; o_iter = g_list_next (o_iter)) {
    OBJECT *o_current = o_iter->data;

#ifdef DEBUG
      printf("   ---> In s_table_add_toplevel_comp_items_to_comp_table, examining o_current->name = %s\n", o_current->name);
#endif

    /* -----  Now process objects found on page  ----- */
    if (o_current->type == OBJ_COMPLEX &&
        o_current->attribs != NULL) {

      /* ---- Don't process part if it lacks a refdes ----- */
      temp_uref = g_strdup(s_attrib_get_refdes(o_current));
      if (temp_uref) {

#if DEBUG
        printf("      In s_table_add_toplevel_comp_items_to_comp_table, found component on page. Refdes = %s\n", temp_uref);
#endif
        verbose_print(" C");

        /* Having found a component, we loop over all attribs in this
         * component, and stick them
         * into cells in the table. */
        a_iter = o_current->attribs;
        while (a_iter != NULL) {
          a_current = a_iter->data;
          if (a_current->type == OBJ_TEXT
              && a_current->text != NULL) {  /* found an attribute */
            /* may need to check more thoroughly here. . . . */
            attrib_text = g_strdup(a_current->text->string);
            attrib_name = u_basic_breakup_string(attrib_text, '=', 0);
            attrib_value = s_misc_remaining_string(attrib_text, '=', 1);
            old_visibility = o_is_visible (pr_current, a_current)
              ? VISIBLE : INVISIBLE;
	    old_show_name_value = a_current->show_name_value;

	    /* Don't include "refdes" or "slot" because they form the row name. */
	    /* Also don't include "net" per bug found by Steve W.  4.3.2007 -- SDB */
            if ( (strcmp(attrib_name, "refdes") != 0) &&
		 (strcmp(attrib_name, "net") != 0) &&
		 (strcmp(attrib_name, "slot") != 0) ) {
               
              /* Get row and col where to put this attrib */
              row = s_table_get_index(sheet_head->master_comp_list_head, temp_uref);
              col = s_table_get_index(sheet_head->master_comp_attrib_list_head, attrib_name);
              /* Sanity check */
              if (row == -1 || col == -1) {
                /* we didn't find the item in the table */
                fprintf (stderr,
                         "In s_table_add_toplevel_comp_items_to_comp_table, we didn't find either row or col in the lists!\n");
              } else {

#if DEBUG
                printf("       In s_table_add_toplevel_comp_items_to_comp_table, about to add row %d, col %d, attrib_value = %s\n",
                       row, col, attrib_value);
                printf(" . . . current address of attrib_value cell is [%p]\n", &((sheet_head->component_table)[row][col]).attrib_value);
#endif
                /* Is there a compelling reason for me to put this into a separate fcn? */
                ((sheet_head->component_table)[row][col]).row = row;
                ((sheet_head->component_table)[row][col]).col = col;
                ((sheet_head->component_table)[row][col]).row_name = g_strdup(temp_uref);
                ((sheet_head->component_table)[row][col]).col_name = g_strdup(attrib_name);
                ((sheet_head->component_table)[row][col]).attrib_value = g_strdup(attrib_value);
                ((sheet_head->component_table)[row][col]).visibility = old_visibility;
                ((sheet_head->component_table)[row][col]).show_name_value = old_show_name_value;
              }
            }
            g_free(attrib_name);
            g_free(attrib_text);
            g_free(attrib_value);
          }
          a_iter = g_list_next (a_iter);
           
        }  /* while (a_current != NULL) */
        g_free(temp_uref);
      }  /* if (temp_uref) */
    }    /* if (o_current->type == OBJ_COMPLEX)  */
  }
 
  verbose_done();
 
}
示例#13
0
/**
 *  Expand matmul at the given pc in the bhir instruction list.
 *
 *  Returns the number of additional instructions used.
 */
int Expander::expand_matmul(bh_ir& bhir, int pc)
{
    int start_pc = pc;
    bh_instruction& composite = bhir.instr_list[pc];

    // Lazy choice... no re-use just NOP it.
    composite.opcode = BH_NONE;

    // Grab operands
    bh_view out = composite.operand[0];
    bh_view a   = composite.operand[1];
    bh_view b   = composite.operand[2];

    // Grab the shape
    int n = a.shape[0];
    int m = a.shape[1];
    int k = b.shape[1];

    // Construct intermediary operands
    // Needs broadcast
    bh_view a_3d = a;

    // Needs transposition + broadcast
    bh_view b_3d = b;

    a_3d.ndim = 3;
    b_3d.ndim = 3;

    // Set the shape
    a_3d.shape[0] = b_3d.shape[0] = n;
    a_3d.shape[1] = b_3d.shape[1] = k;
    a_3d.shape[2] = b_3d.shape[2] = m;

    // Construct broadcast
    a_3d.stride[0] = a.stride[0];
    a_3d.stride[1] = 0;
    a_3d.stride[2] = a.stride[1];

    // Construct transpose + broadcast
    b_3d.stride[0] = 0;
    b_3d.stride[1] = b.stride[1];
    b_3d.stride[2] = b.stride[0];

    // Construct temp for mul-result
    bh_view c_3d = b_3d;

    // Count number of elements
    bh_intp nelements = 1;

    // Set contiguous stride
    for(bh_intp dim=c_3d.ndim-1; dim >= 0; --dim) {
        c_3d.stride[dim] = nelements;
        nelements *= c_3d.shape[dim];
    }
    c_3d.start = 0;
    c_3d.base = make_base(b_3d.base->type, nelements);

    // Expand sequence
    inject(bhir, ++pc, BH_MULTIPLY,   c_3d, a_3d, b_3d);
    inject(bhir, ++pc, BH_ADD_REDUCE, out,  c_3d, (int64_t)2, BH_INT64);
    inject(bhir, ++pc, BH_FREE,       c_3d);

    verbose_print("[Matmul] Expanding BH_MATMUL");
    return pc - start_pc;
}
示例#14
0
static void
process_symbols(void *dcontext, char *dllname, LOADED_IMAGE *img)
{
    /* We have to specify the module via "modname!symname".
     * We must use the same modname as in full_path.
     */
    char fullpath[MAX_PATH];
# define MAX_SYM_WITH_MOD_LEN 256
    char sym_with_mod[MAX_SYM_WITH_MOD_LEN];
    int len;
    drsym_error_t symres;
    char *fname = NULL, *c;
    search_data_t sd;

    if (drsym_init(NULL) != DRSYM_SUCCESS) {
        print("WARNING: unable to initialize symbol engine\n");
        return;
    }

    if (dllname == NULL)
        return;
    fname = dllname;
    for (c = dllname; *c != '\0'; c++) {
        if (*c == '/' || *c == '\\')
            fname = c + 1;
    }
    assert(fname != NULL && "unable to get fname for module");
    if (fname == NULL)
        return;
    /* now get rid of extension */
    for (; c > fname && *c != '.'; c--)
        ; /* nothing */

    assert(c > fname && "file has no extension");
    assert(c - fname < BUFFER_SIZE_ELEMENTS(sym_with_mod) && "sizes way off");
    len = dr_snprintf(sym_with_mod, BUFFER_SIZE_ELEMENTS(sym_with_mod), "%.*s!%s",
                      c - fname, fname, SYM_PATTERN);
    assert(len > 0 && "error printing modname!symname");
    NULL_TERMINATE_BUFFER(sym_with_mod);

    len = GetFullPathName(dllname, BUFFER_SIZE_ELEMENTS(fullpath), fullpath, NULL);
    assert(len > 0);
    NULL_TERMINATE_BUFFER(dllname);

    if (list_usercalls) {
        int i;
        for (i = 0; i < NUM_USERCALL; i++) {
            size_t offs;
            symres = drsym_lookup_symbol(fullpath, usercall_names[i], &offs, 0);
            if (symres == DRSYM_SUCCESS) {
                usercall_addr[i] = ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                                (ULONG)offs, NULL);
                verbose_print("%s = %d +0x%x == "PFX"\n", usercall_names[i], symres,
                              offs, usercall_addr[i]);
            } else {
                dr_printf("Error locating usercall %s: aborting\n", usercall_names[i]);
                return;
            }
        }
    }

    sd.dcontext = dcontext;
    sd.img = img;
    sd.modpath = fullpath;
    verbose_print("Searching \"%s\" for \"%s\"\n", fullpath, sym_with_mod);
    symres = drsym_search_symbols(fullpath, sym_with_mod, true, search_syms_cb, &sd);
    if (symres != DRSYM_SUCCESS)
        print("Error %d searching \"%s\" for \"%s\"\n", symres, fullpath, sym_with_mod);
    drsym_exit();
}
示例#15
0
int main(int argc, char **argv)
{
	int result;
	int option_idx = 0;
	int i;
	char* remote_host = NULL;
	unsigned int remote_port = 22;
	char* remote_username = NULL;
	char* remote_password = NULL;
	char* remote_interface = NULL;
	char* remote_capture_bin = NULL;
	char* sshkey = NULL;
	char* sshkey_passphrase = NULL;
	char* remote_filter = NULL;
	unsigned long int count = 0;
	int ret = EXIT_FAILURE;
	extcap_parameters * extcap_conf = g_new0(extcap_parameters, 1);

#ifdef _WIN32
	WSADATA wsaData;

	attach_parent_console();
#endif  /* _WIN32 */

	extcap_base_set_util_info(extcap_conf, SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE, NULL);
	extcap_base_register_interface(extcap_conf, SSH_EXTCAP_INTERFACE, "SSH remote capture", 147, "Remote capture dependent DLT");

	opterr = 0;
	optind = 0;

	if (argc == 1) {
		help(argv[0]);
		goto end;
	}

	for (i = 0; i < argc; i++) {
		verbose_print("%s ", argv[i]);
	}
	verbose_print("\n");

	while ((result = getopt_long(argc, argv, ":", longopts, &option_idx)) != -1) {

		switch (result) {

		case OPT_HELP:
			help(argv[0]);
			ret = EXIT_SUCCESS;
			goto end;

		case OPT_VERBOSE:
			verbose = TRUE;
			break;

		case OPT_VERSION:
			printf("%s.%s.%s\n", SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE);
			ret = EXIT_SUCCESS;
			goto end;

		case OPT_REMOTE_HOST:
			g_free(remote_host);
			remote_host = g_strdup(optarg);
			break;

		case OPT_REMOTE_PORT:
			remote_port = (unsigned int)strtoul(optarg, NULL, 10);
			if (remote_port > 65535 || remote_port == 0) {
				errmsg_print("Invalid port: %s", optarg);
				goto end;
			}
			break;

		case OPT_REMOTE_USERNAME:
			g_free(remote_username);
			remote_username = g_strdup(optarg);
			break;

		case OPT_REMOTE_PASSWORD:
			g_free(remote_password);
			remote_password = g_strdup(optarg);
			memset(optarg, 'X', strlen(optarg));
			break;

		case OPT_SSHKEY:
			g_free(sshkey);
			sshkey = g_strdup(optarg);
			break;

		case OPT_SSHKEY_PASSPHRASE:
			g_free(sshkey_passphrase);
			sshkey_passphrase = g_strdup(optarg);
			memset(optarg, 'X', strlen(optarg));
			break;

		case OPT_REMOTE_INTERFACE:
			g_free(remote_interface);
			remote_interface = g_strdup(optarg);
			break;

		case OPT_REMOTE_CAPTURE_BIN:
			g_free(remote_capture_bin);
			remote_capture_bin = g_strdup(optarg);
			break;

		case OPT_REMOTE_FILTER:
			g_free(remote_filter);
			remote_filter = g_strdup(optarg);
			break;

		case OPT_REMOTE_COUNT:
			count = strtoul(optarg, NULL, 10);
			break;

		case ':':
			/* missing option argument */
			errmsg_print("Option '%s' requires an argument", argv[optind - 1]);
			break;

		default:
			if (!extcap_base_parse_options(extcap_conf, result - EXTCAP_OPT_LIST_INTERFACES, optarg)) {
				errmsg_print("Invalid option: %s", argv[optind - 1]);
				goto end;
			}
		}
	}

	if (optind != argc) {
		errmsg_print("Unexpected extra option: %s", argv[optind]);
		goto end;
	}

	if (extcap_base_handle_interface(extcap_conf)) {
		ret = EXIT_SUCCESS;
		goto end;
	}

	if (extcap_conf->show_config) {
		ret = list_config(extcap_conf->interface, remote_port);
		goto end;
	}

#ifdef _WIN32
	result = WSAStartup(MAKEWORD(1,1), &wsaData);
	if (result != 0) {
		if (verbose)
			errmsg_print("ERROR: WSAStartup failed with error: %d", result);
		goto end;
	}
#endif  /* _WIN32 */

	if (extcap_conf->capture) {
		char* filter;

		if (!remote_host) {
			errmsg_print("Missing parameter: --remote-host");
			goto end;
		}
		filter = concat_filters(extcap_conf->capture_filter, remote_filter);
		ret = ssh_open_remote_connection(remote_host, remote_port, remote_username,
			remote_password, sshkey, sshkey_passphrase, remote_interface,
			filter, remote_capture_bin, count, extcap_conf->fifo);
		g_free(filter);
	} else {
		verbose_print("You should not come here... maybe some parameter missing?\n");
		ret = EXIT_FAILURE;
	}

end:
	/* clean up stuff */
	g_free(remote_host);
	g_free(remote_username);
	g_free(remote_password);
	g_free(remote_interface);
	g_free(remote_capture_bin);
	g_free(sshkey);
	g_free(sshkey_passphrase);
	g_free(remote_filter);
	extcap_base_cleanup(&extcap_conf);
	return ret;
}
示例#16
0
文件: s_traverse.c 项目: vzh/geda-gaf
NET *s_traverse_net (TOPLEVEL *pr_current, NET *nets, int starting,
                     OBJECT *object, char *hierarchy_tag, int type)
{
  NET *new_net;
  CONN *c_current;
  GList *cl_current;
  char *temp = NULL;
  const gchar *netattrib_pinnum = NULL;

  visit (object);

  if (connection_type (object) != type)
    return nets;

  new_net = nets = s_net_add(nets);
  new_net->nid = object->sid;

  /* pins are not allowed to have the netname attribute attached to them */
  if (object->type != OBJ_PIN) {
    /* Ignore netname attributes on buses */
    if (object->type == OBJ_NET)
      temp = o_attrib_search_object_attribs_by_name (object, "netname", 0);

    if (temp) {
      new_net->net_name =
        s_hierarchy_create_netname(pr_current, temp,
                                   hierarchy_tag);
      g_free(temp);
    } else if (object->type == OBJ_NET) {
      /* search for the old label= attribute on nets */
      temp = o_attrib_search_object_attribs_by_name (object, "label", 0);
      if (temp) {
        printf(_("WARNING: Found label=%s. label= is deprecated, please use netname=\n"), temp);
        new_net->net_name =
          s_hierarchy_create_netname(pr_current, temp,
                                     hierarchy_tag);
        g_free(temp);
      }
    }
  }
#if DEBUG
  printf("inside traverse: %s\n", object->name);
#endif

  if (object->type == OBJ_PIN) {

    verbose_print (starting ? "p" : "P");

    new_net->connected_to =
      s_net_return_connected_string (pr_current, object, hierarchy_tag);

    temp = o_attrib_search_object_attribs_by_name (object, "pinlabel", 0);

    if (temp) {
      new_net->pin_label = temp;
    }

    /* net= new */
    netattrib_pinnum = s_netattrib_connected_string_get_pinnum (nets->connected_to);
    if (netattrib_pinnum != NULL && type == PIN_TYPE_NET) {

#if DEBUG
      printf("going to find netname %s \n", nets->connected_to);
#endif
      nets->net_name =
        s_netattrib_return_netname (pr_current, object,
                                    nets->connected_to,
                                    hierarchy_tag);
      nets->net_name_has_priority = TRUE;
      g_free(nets->connected_to);
      nets->connected_to = NULL;
    }
#if DEBUG
    printf("traverse connected_to: %s\n", new_net->connected_to);
#endif

    /* Terminate if we hit a pin which isn't the one we started with */
    if (!starting)
      return nets;
  }

  /*printf("Found net %s\n", object->name); */
  verbose_print("n");

  /* this is not perfect yet and won't detect a loop... */
  if (is_visited(object) > 100) {
    fprintf(stderr, _("Found a possible net/pin infinite connection\n"));
    exit(-1);
  }

  cl_current = object->conn_list;
  while (cl_current != NULL) {

    c_current = (CONN *) cl_current->data;

    if (c_current->other_object != NULL) {

      if (!is_visited(c_current->other_object) &&
          c_current->other_object != object) {
        nets = s_traverse_net (pr_current, nets, FALSE,
                               c_current->other_object, hierarchy_tag, type);
      }

    }
    cl_current = g_list_next(cl_current);
  }

  return (nets);
}
示例#17
0
文件: eval.c 项目: cwbowron/BCE
int score_pawn(int f, int r, int c)
{
    int bonus = 0;

#define PASSED_PAWN_BONUS
#ifdef PASSED_PAWN_BONUS
    if (c==WHITE)
    {
	int x;
	
	for(x=r+1;x<8;x++)
	{
	    if (getpiece(f,x)==BPAWN)
		goto ppdone;
	    if (getpiece(f-1,x)==BPAWN)
		goto ppdone;
	    if (getpiece(f+1,x)==BPAWN)
		goto ppdone;
	}
	bonus += weights[PASSED_PAWN+r];
    }
    else
    {
	int x;
	
	for(x=r-1;x>0;x--)
	{
	    if (getpiece(f,x)==WPAWN)
		goto ppdone;
	    if (getpiece(f-1,x)==WPAWN)
		goto ppdone;
	    if (getpiece(f+1,x)==WPAWN)
		goto ppdone;
	}
	bonus += weights[PASSED_PAWN+7-r];
    }
    ppdone:
    
#endif    
    
    if (board->pawns[c][f+1]>1)
    {
	bonus -= weights[DOUBLED];
	verbose_print(f,r,-weights[DOUBLED],"doubled pawns");
    }
    if (!board->pawns[c][f]&&!board->pawns[c][f+2])
    {
	bonus -= weights[ISOLATED];
	verbose_print(f,r,-weights[ISOLATED],"isolated pawn");
    }
    else
    {
	int i;
	if (c == WHITE)
	{
	    for (i=r;i>0;i--)
	    {
		if ((f>0)&&(getpiece(f-1,i)==WPAWN))
		    goto Escape;
		if ((f<7)&&(getpiece(f+1,i)==WPAWN))
		    goto Escape;
	    }
	    bonus -= weights[BACKEDUP];
	    verbose_print(f,r,-weights[BACKEDUP],"backedup pawn");
	}
	else
	{
	    for (i=r;i<8;i++)
	    {
		if ((f>0)&&(getpiece(f-1,i)==BPAWN))
		    goto Escape;
		if ((f<7)&&(getpiece(f+1,i)==BPAWN))
		    goto Escape;
	    }
	    bonus -= weights[BACKEDUP];
	    verbose_print(f,r,-weights[BACKEDUP],"backedup pawn");
	}
    }
    
    Escape:
    return bonus;
}
示例#18
0
int main(int argc, char **argv)
{
	int result;
	int option_idx = 0;
	int do_list_interfaces = 0;
	int do_config = 0;
	int do_capture = 0;
	int i;
	char* interface = NULL;
	char* remote_host = NULL;
	unsigned int remote_port = 22;
	char* remote_username = NULL;
	char* remote_password = NULL;
	int do_dlts = 0;
	char* fifo = NULL;
	char* remote_interface = NULL;
	char* remote_capture_bin = NULL;
	char* extcap_filter = NULL;
	char* sshkey = NULL;
	char* sshkey_passphrase = NULL;
	char* remote_filter = NULL;
	unsigned long int count = 0;

#ifdef _WIN32
	WSADATA wsaData;

	attach_parent_console();
#endif  /* _WIN32 */

	opterr = 0;
	optind = 0;

	if (argc == 1) {
		help(argv[0]);
		return EXIT_FAILURE;
	}

	for (i = 0; i < argc; i++) {
		verbose_print("%s ", argv[i]);
	}
	verbose_print("\n");

	while ((result = getopt_long(argc, argv, ":", longopts, &option_idx)) != -1) {

		switch (result) {

		case OPT_HELP:
			help(argv[0]);
			return EXIT_SUCCESS;

		case OPT_VERBOSE:
			verbose = TRUE;
			break;

		case OPT_VERSION:
			printf("%u.%u.%u\n", SSHDUMP_VERSION_MAJOR, SSHDUMP_VERSION_MINOR, SSHDUMP_VERSION_RELEASE);
			return EXIT_SUCCESS;

		case OPT_LIST_INTERFACES:
			do_list_interfaces = 1;
			break;

		case OPT_LIST_DLTS:
			do_dlts = 1;
			break;

		case OPT_INTERFACE:
			if (interface)
				g_free(interface);
			interface = g_strdup(optarg);
			break;

		case OPT_CONFIG:
			do_config = 1;
			break;

		case OPT_CAPTURE:
			do_capture = 1;
			break;

		case OPT_FIFO:
			if (fifo)
				g_free(fifo);
			fifo = g_strdup(optarg);
			break;

		case OPT_REMOTE_HOST:
			if (remote_host)
				g_free(remote_host);
			remote_host = g_strdup(optarg);
			break;

		case OPT_REMOTE_PORT:
			remote_port = (unsigned int)strtoul(optarg, NULL, 10);
			if (remote_port > 65535 || remote_port == 0) {
				printf("Invalid port: %s\n", optarg);
				return EXIT_FAILURE;
			}
			break;

		case OPT_REMOTE_USERNAME:
			if (remote_username)
				g_free(remote_username);
			remote_username = g_strdup(optarg);
			break;

		case OPT_REMOTE_PASSWORD:
			if (remote_password)
				g_free(remote_password);
			remote_password = g_strdup(optarg);
			memset(optarg, 'X', strlen(optarg));
			break;

		case OPT_SSHKEY:
			if (sshkey)
				g_free(sshkey);
			sshkey = g_strdup(optarg);
			break;

		case OPT_SSHKEY_PASSPHRASE:
			if (sshkey_passphrase)
				g_free(sshkey_passphrase);
			sshkey_passphrase = g_strdup(optarg);
			memset(optarg, 'X', strlen(optarg));
			break;

		case OPT_REMOTE_INTERFACE:
			if (remote_interface)
				g_free(remote_interface);
			remote_interface = g_strdup(optarg);
			break;

		case OPT_REMOTE_CAPTURE_BIN:
			if (remote_capture_bin)
				g_free(remote_capture_bin);
			remote_capture_bin = g_strdup(optarg);
			break;

		case OPT_EXTCAP_FILTER:
			if (extcap_filter)
				g_free(extcap_filter);
			extcap_filter = g_strdup(optarg);
			break;

		case OPT_REMOTE_FILTER:
			if (remote_filter)
				g_free(remote_filter);
			remote_filter = g_strdup(optarg);
			break;

		case OPT_REMOTE_COUNT:
			count = strtoul(optarg, NULL, 10);
			break;

		case ':':
			/* missing option argument */
			printf("Option '%s' requires an argument\n", argv[optind - 1]);
			break;

		default:
			printf("Invalid option: %s\n", argv[optind - 1]);
			return EXIT_FAILURE;
		}
	}

	if (optind != argc) {
		printf("Unexpected extra option: %s\n", argv[optind]);
		return EXIT_FAILURE;
	}

	if (do_list_interfaces)
		return list_interfaces();

	if (do_config)
		return list_config(interface, remote_port);

	if (do_dlts)
		return list_dlts(interface);

#ifdef _WIN32
	result = WSAStartup(MAKEWORD(1,1), &wsaData);
	if (result != 0) {
		if (verbose)
			errmsg_print("ERROR: WSAStartup failed with error: %d\n", result);
		return 1;
	}
#endif  /* _WIN32 */

	if (do_capture) {
		char* filter;
		int ret = 0;
		if (!fifo) {
			errmsg_print("ERROR: No FIFO or file specified\n");
			return 1;
		}
		if (g_strcmp0(interface, SSH_EXTCAP_INTERFACE)) {
			errmsg_print("ERROR: invalid interface\n");
			return 1;
		}
		if (!remote_host) {
			errmsg_print("Missing parameter: --remote-host");
			return 1;
		}
		filter = concat_filters(extcap_filter, remote_filter);
		ret = ssh_open_remote_connection(remote_host, remote_port, remote_username,
			remote_password, sshkey, sshkey_passphrase, remote_interface,
			filter, remote_capture_bin, count, fifo);
		g_free(filter);
		return ret;
	}

	verbose_print("You should not come here... maybe some parameter missing?\n");
	return 1;
}
示例#19
0
int main(int argc, char *argv[])
{
	struct array a;
	struct array_iterator ai;
	int i;
	int *t, *t_arr;
	
	while ((i = getopt(argc, argv, "vi:")) != -1) {
		switch (i) {
		    case 'v':
			++verbose;
			break;
		    case 'i':
			MAX_ITEMS = atoi(optarg);
			break;
		    default:
			fprintf(stderr, "bad option\n");
			exit(1);
		}
	}
	
	assert(t_arr = malloc(MAX_ITEMS * sizeof(int)));
	array_init(&a, 100);
	
	verbose_print(1, "start\n");
	for (i = 0; i < MAX_ITEMS; i++) {
		t = t_arr + i;
		*t = i;
		assert(array_put(&a, t) == i);
	}
	for (i = 0; i < MAX_ITEMS; i += 2) {
		t = t_arr + i;
		assert(array_remove(&a, t) == t);
	}
	for (i = 1; i < MAX_ITEMS; i += 2) {
		t = t_arr + i;
		assert(array_pop(&a) == t);
	}
	for (i = 0; i < MAX_ITEMS; i += 2) {
		t = t_arr + i;
		assert(array_put_at(&a, i, t) == NULL);
	}
	for (i = 1; i < MAX_ITEMS; i += 2) {
		t = t_arr + i;
		assert(array_put(&a, t) == i);
	}
	for (i = 0; i < MAX_ITEMS; i += 2) {
		t = t_arr + i;
		assert(array_remove_at(&a, i) == t);
	}
	array_iter_set(&ai, &a);
	i = 1;
	while ((t = array_iter_get(&ai))) {
		assert(*t == i);
		i += 2;
		verbose_print(2, "%d ", *t);
	}
	array_iter_end(&ai);
	printf("\n");
	
	array_free(&a);
	
	return 0;
}
示例#20
0
int run_receiver(UDR_Options * udr_options) {

    int orig_ppid = getppid();

    UDT::startup();

    addrinfo hints;
    addrinfo* res;

    set_verbosity(udr_options->verbose);

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    char receiver_port[NI_MAXSERV];
    UDTSOCKET serv;

    bool bad_port = false;

    for(int port_num = udr_options->start_port; port_num < udr_options->end_port; port_num++) {
        bad_port = false;
        snprintf(receiver_port, sizeof(receiver_port), "%d", port_num);

        if (0 != getaddrinfo(NULL, receiver_port, &hints, &res)) {
            bad_port = true;
        }
        else {
            serv = UDT::socket(res->ai_family, res->ai_socktype, res->ai_protocol);
            if (UDT::ERROR == UDT::bind(serv, res->ai_addr, res->ai_addrlen)) {
                bad_port = true;
            }
        }

        freeaddrinfo(res);

        if(!bad_port)
            break;
    }

    if(bad_port){
        fprintf(stderr, "[udr receiver] ERROR: could not bind to any port in range %d - %d\n", udr_options->start_port, udr_options->end_port);
        return 0;
    }

    unsigned char rand_pp[PASSPHRASE_SIZE];

    if (!RAND_bytes((unsigned char *) rand_pp, PASSPHRASE_SIZE)) {
        fprintf(stderr, "Couldn't generate random key: %ld\n", ERR_get_error());
        exit(EXIT_FAILURE);
    }

    //stdout port number and password -- to send back to the client
    printf("%s ", receiver_port);

    for(int i = 0; i < PASSPHRASE_SIZE; i++) {
        printf("%02x", rand_pp[i]);
    }
    printf(" \n");
    fflush(stdout);

    verbose_print("[udr receiver] server is ready at port %s\n", receiver_port);

    if (UDT::ERROR == UDT::listen(serv, 10)) {
        cerr << "[udr receiver] listen: " << UDT::getlasterror().getErrorMessage() << endl;
        return 0;
    }

    sockaddr_storage clientaddr;
    int addrlen = sizeof(clientaddr);

    UDTSOCKET recver;

    if (UDT::INVALID_SOCK == (recver = UDT::accept(serv, (sockaddr*)&clientaddr, &addrlen))) {
        fprintf(stderr, "[udr receiver] accept: %s\n", UDT::getlasterror().getErrorMessage());
        return 0;
    }

    char clienthost[NI_MAXHOST];
    char clientservice[NI_MAXSERV];
    getnameinfo((sockaddr *)&clientaddr, addrlen, clienthost, sizeof(clienthost), clientservice, sizeof(clientservice), NI_NUMERICHOST|NI_NUMERICSERV);


    string cmd_str = udt_recv_string(recver);
    const char * cmd = cmd_str.c_str();

    //perhaps want to at least check that starts with rsync?
    if(strncmp(cmd, "rsync ", 5) != 0){
        exit(1);
    }

    char * rsync_cmd;
    if(udr_options->server_connect){
        verbose_print("[udr receiver] server connect mode\n");

        rsync_cmd = (char *)malloc(100);

        if(strlen(udr_options->server_config) > 0){
            sprintf(rsync_cmd, "%s%s %s", "rsync --config=", udr_options->server_config, " --server --daemon .");
        }
        else{
            strcpy(rsync_cmd, "rsync --server --daemon .");
        }
    }
    else{
        rsync_cmd = (char *)malloc(strlen(cmd) + 1);
        strcpy(rsync_cmd, cmd);
    }

    verbose_print("[udr receiver] rsync cmd: %s\n", rsync_cmd);

    char ** sh_cmd = (char **)malloc(sizeof(char *) * 4);
    sh_cmd[0] = udr_options->shell_program;
    sh_cmd[1] = "-c";
    sh_cmd[2] = rsync_cmd;
    sh_cmd[3] = NULL;

    //now fork and exec the rsync on the remote side using sh (so that wildcards will be expanded properly)
    int child_to_parent, parent_to_child;

    int rsync_pid = fork_execvp(udr_options->shell_program, sh_cmd, &parent_to_child, &child_to_parent);

    //now if we're in server mode need to drop privileges if specified
    if(udr_options->rsync_gid > 0){
        setgid(udr_options->rsync_gid);
    }
    if(udr_options->rsync_uid > 0){
        setuid(udr_options->rsync_uid);
    }

    verbose_print("[udr receiver] rsync pid: %d\n", rsync_pid);

    struct thread_data recv_to_udt;
    recv_to_udt.udt_socket = &recver;
    recv_to_udt.fd = child_to_parent; //stdout of rsync server process
    recv_to_udt.id = 2;
    recv_to_udt.is_complete = false;

    struct thread_data udt_to_recv;
    udt_to_recv.udt_socket = &recver;
    udt_to_recv.fd = parent_to_child; //stdin of rsync server process
    udt_to_recv.id = 3;
    udt_to_recv.is_complete = false;

    if(udr_options->encryption){
        crypto encrypt(EVP_ENCRYPT, PASSPHRASE_SIZE, rand_pp,
            udr_options->encryption_type);
        crypto decrypt(EVP_DECRYPT, PASSPHRASE_SIZE, rand_pp,
            udr_options->encryption_type);
        recv_to_udt.crypt = &encrypt;
        udt_to_recv.crypt = &decrypt;
    }
    else{
        recv_to_udt.crypt = NULL;
        udt_to_recv.crypt = NULL;
    }

    pthread_t recv_to_udt_thread;
    pthread_create(&recv_to_udt_thread, NULL, handle_to_udt, (void *)&recv_to_udt);

    pthread_t udt_to_recv_thread;
    pthread_create(&udt_to_recv_thread, NULL, udt_to_handle, (void*)&udt_to_recv);

    verbose_print("[udr receiver] waiting to join on recv_to_udt_thread\n");
    verbose_print("[udr receiver] ppid %d pid %d\n", getppid(), getpid());

    //going to poll if the ppid changes then we know it's exited and then we exit all of our threads and exit as well
    //also going to check if either thread is complete, if one is then the other should also be killed
    //bit of a hack to deal with the pthreads
    while(true){
        if(getppid() != orig_ppid){
            pthread_kill(recv_to_udt_thread, SIGUSR1);
            pthread_kill(udt_to_recv_thread, SIGUSR1);
            break;
        }
        if(recv_to_udt.is_complete && udt_to_recv.is_complete){
            verbose_print("[udr receiver] both threads are complete: recv_to_udt.is_complete %d udt_to_recv.is_complete %d\n", recv_to_udt.is_complete, udt_to_recv.is_complete);
            break;
        }
        else if(recv_to_udt.is_complete){
            verbose_print("[udr receiver] recv_to_udt is complete: recv_to_udt.is_complete %d udt_to_recv.is_complete %d\n", recv_to_udt.is_complete, udt_to_recv.is_complete);
            break;
        }
        else if(udt_to_recv.is_complete){
            verbose_print("[udr receiver] udt_to_recv is complete: recv_to_udt.is_complete %d udt_to_recv.is_complete %d\n", recv_to_udt.is_complete, udt_to_recv.is_complete);
            break;
        }

        sleep(ppid_poll);
    }

    verbose_print("[udr receiver] Trying to close recver\n");
    UDT::close(recver);

    verbose_print("[udr receiver] Closed recver\n");

    UDT::close(serv);

    verbose_print("[udr receiver] Closed serv\n");

    UDT::cleanup();

    verbose_print("[udr receiver] UDT cleaned up\n");

    return 0;
}
示例#21
0
static bool rewrite_chain(bh_ir &bhir, const vector<bh_instruction*>& chain, const vector<bh_view*>& temps)
{
    bh_instruction& first  = *chain.at(0); // BH_MULTIPLY
    bh_instruction& second = *chain.at(1); // BH_MULTIPLY
    bh_instruction& third  = *chain.at(2); // BH_ADD or BH_SUBTRACT

    vector<bh_instruction*> frees;

    for(size_t pc = 0; pc < bhir.instr_list.size(); ++pc) {
        bh_instruction& instr = bhir.instr_list[pc];

        // Skip if the instruction is one of the three we are looking at
        if (instr == first or instr == second or instr == third) {
            continue;
        }

        for(auto it : temps) {
            bh_view view = *it;

            if (instr.opcode == BH_FREE) {
                if (view == instr.operand[0]) {
                    frees.push_back(&instr);
                }
            } else if (instr.opcode != BH_NONE) {
                if (view == instr.operand[0] or
                    view == instr.operand[1] or
                    view == instr.operand[2]) {
                    verbose_print("[Muladd] \tCan't rewrite - Found use of view in other place!");
                    return false;
                }
            }
        }
    }

    if (frees.size() != temps.size()) {
        verbose_print("[Muladd] \tCan't rewrite - Not same amount of views as frees!");
        return false;
    }

    if (third.opcode == BH_ADD) {
        first.constant.set_double(first.constant.get_double() + second.constant.get_double());
    } else { // BH_SUBTRACT
        first.constant.set_double(first.constant.get_double() - second.constant.get_double());
    }

    // Set the constant type to the result type
    first.constant.type = third.operand[0].base->type;

    // The result of the first operations should be that of the thrid
    first.operand[0] = third.operand[0];

    // Remove unnecessary BH_FREE
    for (auto it : frees) {
        it->opcode = BH_NONE;
    }

    // Set the two other operations to BH_NONE
    second.opcode = BH_NONE;
    third.opcode  = BH_NONE;

    return true;
}
示例#22
0
void Contracter::contract_muladd(bh_ir &bhir)
{
    bool rewritten = false;

    vector<bh_view*> temp_results;
    vector<bh_instruction*> instruction_chain;

    for(size_t pc = 0; pc < bhir.instr_list.size(); ++pc) {
        if (rewritten) {
            // We might catch more rewrites if we found one
            // so we loop back to the beginning
            pc        = 0;
            rewritten = false;
            temp_results.clear();
            instruction_chain.clear();
        }

        bh_instruction& instr = bhir.instr_list[pc];
        bh_view* multiplying_view;

        if (instr.opcode == BH_MULTIPLY) {
            if (bh_is_constant(&(instr.operand[1]))) {
                multiplying_view = &(instr.operand[2]);
            } else if (bh_is_constant(&(instr.operand[2]))) {
                multiplying_view = &(instr.operand[1]);
            } else {
                continue;
            }

            instruction_chain.push_back(&instr); // First BH_MULTIPLY found
            temp_results.push_back(&(instr.operand[0]));

            for(size_t sub_pc = pc+1; sub_pc < bhir.instr_list.size(); ++sub_pc) {
                if (rewritten) break;

                bh_instruction& other_instr = bhir.instr_list[sub_pc];

                if (other_instr.opcode == BH_MULTIPLY) {
                    if (!((bh_is_constant(&(other_instr.operand[1])) and *multiplying_view == other_instr.operand[2]) or
                          (bh_is_constant(&(other_instr.operand[2])) and *multiplying_view == other_instr.operand[1]))) {
                        continue;
                    }

                    instruction_chain.push_back(&other_instr); // Second BH_MULTIPLY found
                    temp_results.push_back(&(other_instr.operand[0]));

                    for(size_t sub_sub_pc = sub_pc+1; sub_sub_pc < bhir.instr_list.size(); ++sub_sub_pc) {
                        if (rewritten) break;

                        bh_instruction& yet_another_instr = bhir.instr_list[sub_sub_pc];

                        if (yet_another_instr.opcode == BH_ADD or yet_another_instr.opcode == BH_SUBTRACT) {
                            uint found = 0;
                            for(auto it : temp_results) {
                                if (*it == yet_another_instr.operand[1] or *it == yet_another_instr.operand[2]) {
                                    found += 1;
                                }
                            }

                            if (found >= 2) {
                                instruction_chain.push_back(&yet_another_instr);
                                verbose_print("[Muladd] Rewriting chain of length " + std::to_string(instruction_chain.size()));
                                rewritten = rewrite_chain(bhir, instruction_chain, temp_results);
                            }
                        }
                    }

                    instruction_chain.pop_back();
                    temp_results.pop_back();
                }
            }
        }
    }
}
示例#23
0
void
s_hierarchy_post_process (NETLIST * head)
{
    NETLIST *nl_current;
    CPINLIST *pl_current;
    char *source_net_name = NULL;
    int did_work = FALSE;

    nl_current = head;
    while (nl_current != NULL) {
	if (nl_current->composite_component) {
#if DEBUG
	    printf("Found composite %s\n", nl_current->component_uref);
#endif

	    if (nl_current->cpins) {
		pl_current = nl_current->cpins;

		while (pl_current != NULL) {

			verbose_print("p");

		    if (pl_current->pin_label == NULL) {
			fprintf(stderr,
				_("Found a pin [%1$s] on component [%2$s] which does not have a label!\n"),
				nl_current->component_uref,
				pl_current->pin_number);
		    } else {

#if DEBUG
			printf("# L: %s %s\n", pl_current->pin_number,
			       pl_current->pin_label);
#endif
			/* get source net name, all nets are named already */
      source_net_name = s_net_name_search (pl_current->nets);
#if DEBUG
			printf("name: %s\n", source_net_name);
			printf("Now we need to search for: %s/%s\n",
			       nl_current->component_uref,
			       pl_current->pin_label);
#endif

			did_work = s_hierarchy_setup_rename (head,
                                           nl_current->component_uref,
                                           pl_current->pin_label,
                                           source_net_name);
			if (!did_work) {
			    fprintf(stderr,
				    _("Missing I/O symbol with refdes [%1$s] inside schematic for symbol [%2$s]\n"),
				    pl_current->pin_label,
				    nl_current->component_uref);

			}
		    }
		    pl_current = pl_current->next;
		}
	    }
	}
	nl_current = nl_current->next;
    }
}
示例#24
0
void
s_hierarchy_traverse(TOPLEVEL * pr_current, OBJECT * o_current,
		     NETLIST * netlist)
{
    char *attrib;
    int page_control=-1;
    PAGE *p_current;
    PAGE *child_page;
    int count = 0;
    int pcount = 0;
    int looking_inside = FALSE;
    int loaded_flag = FALSE;
    char *current_filename;
    int graphical=FALSE;

    attrib = o_attrib_search_attached_attribs_by_name (o_current, "source", 0);

    /* if above is null, then look inside symbol */
    if (attrib == NULL) {
	attrib = o_attrib_search_inherited_attribs_by_name (o_current,
	                                                    "source", count);

	looking_inside = TRUE;
#if DEBUG
	printf("going to look inside now\n");
#endif
    }

    graphical = s_hierarchy_graphical_search(o_current, count);
    if (graphical) {
	/* Do not bother traversing the hierarchy if the symbol has an */
	/* graphical attribute attached to it. */
	if (attrib) {
	    g_free(attrib);
 	    attrib = NULL;
	}
    }

    while (attrib) {

	/* look for source=filename,filename, ... */
	pcount = 0;
	current_filename = u_basic_breakup_string(attrib, ',', pcount);

	/* loop over all filenames */
	while (current_filename != NULL) {

	    s_log_message(_("Going to traverse source [%1$s]"),
			  current_filename);

	    /* guts here */
	    /* guts for a single filename */
	    p_current = pr_current->page_current;
#if DEBUG
	    printf("Going down %s\n", current_filename);
#endif
            GError *err = NULL;
	    child_page =
		s_hierarchy_down_schematic_single(pr_current,
						  current_filename,
						  pr_current->page_current,
						  page_control,
                                                  HIERARCHY_FORCE_LOAD,
                                                  &err);

	    if (child_page == NULL) {
              g_warning (_("Failed to load subcircuit '%1$s': %2$s\n"),
                         current_filename, err->message);
              fprintf(stderr, _("ERROR: Failed to load subcircuit '%1$s': %2$s\n"),
                      current_filename, err->message);
              g_error_free (err);
              exit (2);

	    } else {
              page_control = child_page->page_control;
              s_page_goto (pr_current, child_page);

		loaded_flag = TRUE;

		verbose_print("v\n");
		verbose_reset_index();

		netlist->composite_component = TRUE;
		/* can't do the following, don't know why... HACK TODO */
		/*netlist->hierarchy_tag = u_basic_strdup (netlist->component_uref);*/
		s_traverse_sheet (pr_current,
		                  s_page_objects (pr_current->page_current),
		                  netlist->component_uref);

		verbose_print("^");
	    }

	    pr_current->page_current = p_current;

	    g_free(current_filename);
	    pcount++;
	    current_filename = u_basic_breakup_string(attrib, ',', pcount);
	}

	g_free(attrib);

	g_free(current_filename);

	count++;

	/* continue looking outside first */
	if (!looking_inside) {
	    attrib =
		o_attrib_search_attached_attribs_by_name (o_current, "source",
		                                          count);
	}

	/* okay we were looking outside and didn't */
	/* find anything, so now we need to look */
	/* inside the symbol */
	if (!looking_inside && attrib == NULL && !loaded_flag) {
	    looking_inside = TRUE;
#if DEBUG
	    printf("switching to go to look inside\n");
#endif
	}

	if (looking_inside) {
#if DEBUG
	    printf("looking inside\n");
#endif
	    attrib =
	        o_attrib_search_inherited_attribs_by_name (o_current,
	                                                   "source", count);
	}

        graphical = s_hierarchy_graphical_search(o_current, count);
        if (graphical) {
	  /* Do not bother looking further in the hierarchy if the symbol */
          /* has an graphical attribute attached to it. */
	  if (attrib) {
	     g_free(attrib);
	     attrib = NULL;
          }
       }
    }
}
示例#25
0
int run_sender(UDR_Options * udr_options, unsigned char * passphrase, const char* cmd, int argc, char ** argv) {
    UDT::startup();
    struct addrinfo hints, *local, *peer;

    set_verbosity(udr_options->verbose);

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    if (0 != getaddrinfo(NULL, udr_options->port_num, &hints, &local)) {
        cerr << "[udr sender] incorrect network address.\n" << endl;
        return 1;
    }

    UDTSOCKET client = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol);

    freeaddrinfo(local);

    if (0 != getaddrinfo(udr_options->host, udr_options->port_num, &hints, &peer)) {
        cerr << "[udr sender] incorrect server/peer address. " << udr_options->host << ":" << udr_options->port_num << endl;
        return 1;
    }

    if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) {
        cerr << "[udr sender] connect: " << UDT::getlasterror().getErrorMessage() << endl;
        return 1;
    }

    freeaddrinfo(peer);

    // not using CC method yet
    //CUDPBlast* cchandle = NULL;
//  int value;
//  int temp;

    char* data = new char[max_block_size];

    ssize_t n;

    //very first thing we send is the rsync argument so that the rsync server can be started and piped to from the UDT connection
    n = strlen(cmd) + 1;
    int ssize = 0;
    int ss;
    while(ssize < n) {
        if (UDT::ERROR == (ss = UDT::send(client, cmd + ssize, n - ssize, 0)))
        {
            cerr << "[udr sender] Send:" << UDT::getlasterror().getErrorMessage() << endl;
            break;
        }

        ssize += ss;
    }

    struct thread_data sender_to_udt;
    sender_to_udt.udt_socket = &client;
    sender_to_udt.fd = STDIN_FILENO; //stdin of this process, from stdout of rsync
    sender_to_udt.id = 0;
    sender_to_udt.is_complete = false;

    struct thread_data udt_to_sender;
    udt_to_sender.udt_socket = &client;
    udt_to_sender.fd = STDOUT_FILENO; //stdout of this process, going to stdin of rsync, rsync defaults to set this is non-blocking
    udt_to_sender.id = 1;
    udt_to_sender.is_complete = false;

    if(udr_options->encryption){
        crypto encrypt(EVP_ENCRYPT, PASSPHRASE_SIZE, (unsigned char *)passphrase,
            udr_options->encryption_type);
        crypto decrypt(EVP_DECRYPT, PASSPHRASE_SIZE, (unsigned char *)passphrase,
            udr_options->encryption_type);
        // free_key(passphrase);
        sender_to_udt.crypt = &encrypt;
        udt_to_sender.crypt = &decrypt;
    }
    else{
        sender_to_udt.crypt = NULL;
        udt_to_sender.crypt = NULL;
    }

    pthread_t sender_to_udt_thread;
    pthread_create(&sender_to_udt_thread, NULL, handle_to_udt, (void *)&sender_to_udt);

    pthread_t udt_to_sender_thread;
    pthread_create(&udt_to_sender_thread, NULL, udt_to_handle, (void*)&udt_to_sender);

    int rc1 = pthread_join(udt_to_sender_thread, NULL);

    verbose_print("[udr sender] joined on udt_to_sender_thread %d\n", rc1);

    UDT::close(client);
    pthread_kill(sender_to_udt_thread, SIGUSR1);

    int rc2 = pthread_join(sender_to_udt_thread, NULL);

    verbose_print("[udr sender] joined on sender_to_udt_thread %d\n", rc2);

    UDT::close(client);
    UDT::cleanup();

    delete [] data;
    return 0;
}
示例#26
0
void Contracter::contract_stupidmath(bh_ir &bhir)
{
    for(size_t pc = 0; pc < bhir.instr_list.size(); ++pc) {
        bh_instruction& instr = bhir.instr_list[pc];

        if (is_doing_stupid_math(instr)) {
            verbose_print("[Stupid math] Is doing stupid math with a " + std::string(bh_opcode_text(instr.opcode)));

            // We could have the following:
            //   BH_ADD B A 0
            //   BH_FREE A
            //   BH_SYNC B
            // We want to find the add and replace A in all above with B, if A is created in this flush.
            // Then remove the free of A.

            // Output operand
            bh_view* B = &(instr.operand[0]);

            // The one operand, that isn't constant
            bh_view* A;
            if (bh_is_constant(&(instr.operand[1]))) {
                A = &(instr.operand[2]);
            } else {
                A = &(instr.operand[1]);
            }

            if (bh_view_same(A, B)) continue;

            bool freed = false;
            for (size_t pc_chain = 0; pc_chain < bhir.instr_list.size(); ++pc_chain) {
                bh_instruction& other_instr = bhir.instr_list[pc_chain];

                // Look for matching FREE for B
                if (other_instr.opcode == BH_FREE and bh_view_same(&(other_instr.operand[0]), B)) {
                    freed = true;
                    break;
                }
            }

            if (!freed) {
                verbose_print("[Stupid math] \tCan't rectify as it isn't freeing in same flush.");
                continue;
            }

            // Check that A is created by us.
            bool created_before = false;

            for (size_t pc_chain = 0; pc_chain < pc; ++pc_chain) {
                bh_instruction& other_instr = bhir.instr_list[pc_chain];

                if (bh_view_same(&(other_instr.operand[0]), A)) {
                    created_before = true;
                    break;
                }
            }

            // Only if we have created A in this flush, are we allowed to change it.
            if (!created_before) {
                verbose_print("[Stupid math] \tCan't rectify as other view isn't created in same flush.");
                continue;
            }

            for (size_t pc_chain = 0; pc_chain < bhir.instr_list.size(); ++pc_chain) {
                if (pc == pc_chain) continue;

                bh_instruction& other_instr = bhir.instr_list[pc_chain];

                // Look for matching FREE for A
                if (other_instr.opcode == BH_FREE and bh_view_same(&(other_instr.operand[0]), A)) {
                    verbose_print("[Stupid math] \tFound and removed FREE.");
                    other_instr.opcode = BH_NONE; // Remove instruction
                } else {
                    // Rewrite all uses of A to B
                    for (int idx = 0; idx < bh_noperands(other_instr.opcode); ++idx) {
                        if (bh_view_same(&(other_instr.operand[idx]), A)) {
                            verbose_print("[Stupid math] \tRewriting A to B.");
                            other_instr.operand[idx] = *B;
                        }
                    }
                }
            }

            // Remove self
            verbose_print("[Stupid math] \tRemoving " + std::string(bh_opcode_text(instr.opcode)));
            instr.opcode = BH_NONE;
        }
    }
}
示例#27
0
static void
process_exports(void *dcontext, char *dllname, LOADED_IMAGE *img)
{
    IMAGE_EXPORT_DIRECTORY *dir;
    IMAGE_SECTION_HEADER *sec;
    DWORD *name, *code;
    WORD *ordinal;
    const char *string;
    ULONG size;
    uint i;
    byte *addr, *start_exports, *end_exports;

    verbose_print("Processing exports of \"%s\"\n", dllname);
    dir = (IMAGE_EXPORT_DIRECTORY *)
        ImageDirectoryEntryToData(img->MappedAddress, FALSE,
                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &size);
    verbose_print("mapped at "PFX" (preferred "PFX"), exports 0x%08x, size 0x%x\n",
                  img->MappedAddress, get_preferred_base(img), dir, size);
    start_exports = (byte *) dir;
    end_exports = start_exports + size;
    verbose_print("name=%s, ord base=0x%08x, names=%d 0x%08x\n",
                  (char *) ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                        dir->Name, NULL),
                  dir->Base, dir->NumberOfNames, dir->AddressOfNames);

    /* don't limit functions to lie in .text --
     * for ntdll, some exported routines have their code after .text, inside
     * ECODE section!
     */
    sec = img->Sections;
    for (i = 0; i < img->NumberOfSections; i++) {
        verbose_print("Section %d %s: 0x%x + 0x%x == 0x%08x through 0x%08x\n",
                      i, sec->Name, sec->VirtualAddress, sec->SizeOfRawData,
                      ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                   sec->VirtualAddress, NULL),
                      (ptr_uint_t) ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                                sec->VirtualAddress, NULL) +
                      sec->SizeOfRawData);
        sec++;
    }

    name = (DWORD *) ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                  dir->AddressOfNames, NULL);
    code = (DWORD *) ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                  dir->AddressOfFunctions, NULL);
    ordinal = (WORD *) ImageRvaToVa(img->FileHeader, img->MappedAddress,
                                    dir->AddressOfNameOrdinals, NULL);
    verbose_print("names: from 0x%08x to 0x%08x\n",
                  ImageRvaToVa(img->FileHeader, img->MappedAddress, name[0], NULL),
                  ImageRvaToVa(img->FileHeader, img->MappedAddress,
                               name[dir->NumberOfNames-1], NULL));

    for (i = 0; i < dir->NumberOfNames; i++) {
        string = (char *) ImageRvaToVa(img->FileHeader, img->MappedAddress, name[i], NULL);
        /* ordinal is biased (dir->Base), but don't add base when using as index */
        assert(dir->NumberOfFunctions > ordinal[i]);
        /* I don't understand why have to do RVA to VA here, when dumpbin /exports
         * seems to give the same offsets but by simply adding them to base we
         * get the appropriate code location -- but that doesn't work here...
         */
        addr = ImageRvaToVa(img->FileHeader, img->MappedAddress,
                            code[ordinal[i]], NULL);
        verbose_print("name=%s 0x%08x, ord=%d, code=0x%x -> 0x%08x\n",
                      string, string, ordinal[i], code[ordinal[i]], addr);
        if (list_exports) {
            print("ord %3d offs 0x%08x %s\n", ordinal[i],
                  addr - img->MappedAddress, string);
        }
        if (list_Ki && string[0] == 'K' && string[1] == 'i') {
            print("\n==================================================\n");
            print("%s\n\n", string);
            check_Ki(string);
            print("\ndisassembly:\n");
            decode_function(dcontext, addr);
            print(  "==================================================\n");
        }
        /* forwarded export points inside exports section */
        if (addr >= start_exports && addr < end_exports) {
            if (list_forwards || verbose) {
                /* I've had issues w/ forwards before, so avoid printing crap */
                if (addr[0] > 0 && addr[0] < 127)
                    print("%s is forwarded to %.128s\n", string, addr);
                else
                    print("ERROR identifying forwarded entry for %s\n", string);
            }
        } else if (list_syscalls) {
            process_syscall_wrapper(dcontext, addr, string, "export", img);
        }
    }
}
示例#28
0
文件: event.c 项目: letoram/arcan
/* another option to this mess (as the hashing thing doesn't seem to work out
 * is to move identification/etc. to another level and just let whatever device
 * node generator is active populate with coherent names. and use a hash of that
 * name as the ID */
static bool identify(int fd, const char* path,
	char* label, size_t label_sz, unsigned short* dnum)
{
	if (-1 == ioctl(fd, EVIOCGNAME(label_sz), label)){
		debug_print("input/identify: bad EVIOCGNAME, setting unknown\n");
		snprintf(label, label_sz, "unknown");
	}
	else
		verbose_print(
			"input/identify(%d): %s name resolved to %s", fd, path, label);

	struct input_id nodeid;
	if (-1 == ioctl(fd, EVIOCGID, &nodeid)){
		debug_print(
			"input/identify(%d): no EVIOCGID, reason:%s", fd, strerror(errno));
		return false;
	}

/*
 * first, check if any other subsystem knows about this one and ignore if so
 */
	if (arcan_led_known(nodeid.vendor, nodeid.product)){
		debug_print(
			"led subsys know %d, %d\n", (int)nodeid.vendor, (int)nodeid.product);
		arcan_led_init();
		return false;
	}

/* didn't find much on how unique eviocguniq actually was, nor common lengths
 * or what not so just mix them in a buffer, hash and let unsigned overflow
 * modulo take us down to 16bit */
	size_t bpl = sizeof(long) * 8;
	size_t nbits = ((EV_MAX)-1) / bpl + 1;

	char buf[12 + nbits * sizeof(long)];
	char bbuf[sizeof(buf)];
	memset(buf, '\0', sizeof(buf));
	memset(bbuf, '\0', sizeof(bbuf));

/* some test devices here answered to the ioctl and returned full empty UNIQs,
 * do something to lower the likelihood of collisions */
	unsigned long hash = 5381;

	if (-1 == ioctl(fd, EVIOCGUNIQ(sizeof(buf)), buf) ||
		memcmp(buf, bbuf, sizeof(buf)) == 0){

		size_t llen = strlen(label);
		for (size_t i = 0; i < llen; i++)
			hash = ((hash << 5) + hash) + label[i];

		llen = strlen(path);
		for (size_t i = 0; i < llen; i++)
			hash  = ((hash << 5) + hash) + path[i];

		buf[11] ^= nodeid.vendor >> 8;
		buf[10] ^= nodeid.vendor;
		buf[9] ^= nodeid.product >> 8;
		buf[8] ^= nodeid.product;
		buf[7] ^= nodeid.version >> 8;
		buf[6] ^= nodeid.version;

/* even this point has a few collisions, particularly some keyboards and mice
 * that don't respond to CGUNIQ and expose multiple- subdevices but with
 * different button/axis count */
		ioctl(fd, EVIOCGBIT(0, EV_MAX), &buf);
	}
示例#29
0
文件: s_traverse.c 项目: vzh/geda-gaf
void
s_traverse_sheet (TOPLEVEL * pr_current, const GList *obj_list, char *hierarchy_tag)
{
  NETLIST *netlist;
  char *temp;
  SCM scm_uref;
  char *temp_uref;
  gboolean is_hierarchy = TRUE;
  const GList *iter;
  GError *err = NULL;
  EdaConfig *cfg;

  cfg = eda_config_get_context_for_file (NULL);
  is_hierarchy = eda_config_get_boolean (cfg, "gnetlist", "traverse-hierarchy", &err);
  if (err != NULL) {
    is_hierarchy = TRUE;
    g_clear_error (&err);
  }

  if (verbose_mode) {
    printf("- Starting internal netlist creation\n");
  }

  for (iter = obj_list; iter != NULL; iter = g_list_next (iter)) {
    OBJECT *o_current = iter->data;

    netlist = s_netlist_return_tail(netlist_head);

    if (o_current->type == OBJ_PLACEHOLDER) {
      printf(_("WARNING: Found a placeholder/missing component, are you missing a symbol file? [%s]\n"), o_current->complex_basename);
    }

    if (o_current->type == OBJ_COMPLEX) {
      gboolean is_graphical = FALSE;

#if DEBUG
      printf("starting NEW component\n\n");
#endif

      verbose_print(" C");

      /* look for special tag */
      temp = o_attrib_search_object_attribs_by_name (o_current, "graphical", 0);
      if (g_strcmp0 (temp, "1") == 0) {
        /* traverse graphical elements, but adding them to the
	   graphical netlist */
	
	netlist = s_netlist_return_tail(graphical_netlist_head);
	is_graphical = TRUE;
	
    
      }
      g_free (temp);
      netlist = s_netlist_add(netlist);
      netlist->nlid = o_current->sid;

      scm_uref = g_scm_c_get_uref(pr_current, o_current);

      if (scm_is_string( scm_uref )) {
        temp_uref = scm_to_utf8_string (scm_uref);
        netlist->component_uref =
          s_hierarchy_create_uref(pr_current, temp_uref, hierarchy_tag);
        g_free(temp_uref);
      } else {
        if (hierarchy_tag) {
          netlist->component_uref = g_strdup (hierarchy_tag);
        } else {
          netlist->component_uref = NULL;
        }
      }
      
      if (hierarchy_tag) {
	netlist->hierarchy_tag = g_strdup (hierarchy_tag);
      }

      netlist->object_ptr = o_current;
      
      if (!netlist->component_uref) {
	
	/* search of net attribute */
	/* maybe symbol is not a component */
	/* but a power / gnd symbol */
	temp = o_attrib_search_object_attribs_by_name (o_current, "net", 0);
	
	/* nope net attribute not found */
	if ( (!temp) && (!is_graphical) ) {
	  
	  fprintf(stderr,
		  _("Could not find refdes on component and could not find any special attributes!\n"));
	  
	  netlist->component_uref = g_strdup("U?");
	} else {
	  
#if DEBUG
	  printf("yeah... found a power symbol\n");
#endif
	  /* it's a power or some other special symbol */
	  netlist->component_uref = NULL;
	  g_free(temp);
	}
	
      }

      netlist->cpins =
	s_traverse_component(pr_current, o_current,
			     hierarchy_tag);
      
      /* here is where you deal with the */
      /* net attribute */
      s_netattrib_handle(pr_current, o_current, netlist,
			 hierarchy_tag);
      
      /* now you need to traverse any underlying schematics */
      if (is_hierarchy) {
	s_hierarchy_traverse(pr_current, o_current, netlist);
      }
    }
  }

  verbose_done();
}